Powershell not importing functions from module - powershell

I'm trying to setup a NuGet Feed here, and that worked ok. I installed a module from my feed via
Install-Module -Name MyCmdlets -Repository $RepoName -Scope CurrentUser -Force
Import-Module -Name MyCmdlets
However when I run Get-Module, I get no functions and it's a manifest?
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.0 MyCmdlets
If I manually go to the installed location and import manually
Import-Module <my-path>\1.0\MyCmdlets.psm1
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 0.0 MyCmdlets {Create-Project, Get-AuditLogs, Get-..
My manifest file does have these lines so I don't understand why Import-Module isn't working correctly.
FunctionsToExport = '*'
CmdletsToExport = '*'

I guess you haven't set the root module in your .psd1 like so
#
# Module manifest for module 'YourModule'
#
#{
# Script module or binary module file associated with this manifest
RootModule = 'YourModule.psm1'
# Version number of this module.
ModuleVersion = '1.0.0'
...
This is necessary so that when you import your manifest module it also loads the script module

For anyone coming across this looking for why their module wont import check that RootModule = 'YourModule.psm1' isn't commented out.
By default when creating a new manifest using New-ModuleManifest it throws a hash in front of this line..
ugh I feel so stupid.

Related

Commandlets from a custom Module not being recognised

I have a custom Powershell module I have been working on for the past few days, I am now trying to integrate it into powershell as a module that always gets auto loaded.
My module is placed under the C:\Users\...\Documents\PowerShell\Modules , which is one of the places Powershell expects modules from.
This is the structure for the module:
C:\Users\...\Documents\PowerShell\Modules\MetaData-System\MetaData-System.psm1
C:\Users\...\Documents\PowerShell\Modules\MetaData-System\MetaData-System.psd1
The MetaData-System.psd1 files contents are:
#{
ModuleVersion = '0.0.1'
GUID = '9e976eac-1010-4e0b-95e4-76c8bfc1ece1'
Author = '...'
CompanyName = 'Unknown'
Copyright = '(c) .... All rights reserved.'
FunctionsToExport = #( 'Set-Metadata', 'Clear-Metadata')
CmdletsToExport = #()
VariablesToExport = '*'
AliasesToExport = #()
PrivateData = #{
    PSData = #{
    }
}
}
The MetaData-System.psm1 files contents consists of two functions called Set-MetaData and Clear-MetaData.
In Terminal running Get-Module -ListAvailable lists:
Directory: C:\Users\...\Documents\PowerShell\Modules
ModuleType Version PreRelease Name PSEdition ExportedCommands
---------- ------- ---------- ---- --------- ----------------
Manifest 0.0.1 MetaData-System ... {Set-Metadata, Clear-Metadata}
But when I try to use one of the functions from the module by typing "Set-Met" no autocomplete occurs, neither do any parameters get suggested. If I write it all down such as:
Set-Metadata -path "C:\Users\...\Documents\test.txt" -Flags "Hello World
I get this error:
Set-Metadata: The term 'Set-Metadata' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I have searched everywhere to see what I am doing wrong and
out of ideas now.
I have taken the liberty to cross post this question on other forums as well.
Any help would be greatly appreciated!
EDIT: As suggested by #Abraham Zinala, I tried Get-Module:
ModuleType Version PreRelease Name ExportedCommands
---------- ------- ---------- ---- ----------------
Manifest 0.0.1 MetaData-System
Manifest 7.0.0.0 Microsoft.PowerShell.Management {Add-Content, Clear-Content, Clear-Item, Clear-ItemProperty…}
Manifest 7.0.0.0 Microsoft.PowerShell.Utility {Add-Member, Add-Type, Clear-Variable, Compare-Object…}
Script 2.1.0 PSReadLine {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler…}
No commands are present for the MetaData-System module.
Your module manifest is missing the following entry:
RootModule = 'MetaData-System.psm1'
This is necessary for the implementing script module file (*.psm1) to be discovered.
In the absence of it, it is only the manifest file (.psd1) that is discovered, and the implementation of the exported commands is effectively missing.
This is evidenced by your sample Get-Module output listing the ModuleType as Manifest rather than Script.

PowerShell custom module manifest does not expose functions declared

I've created a PowerShell module. The module exposes 3 functions. When I install it without a manifest directly the output will be:
> Import-Module AzureDD
> Get-Module | Where { $_.Name -eq 'AzureDD' }
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 0.0 AzureDD {New-AzureDDAppPermission, New-AzureDDAppRegistration, Sync-AzureDDStorageContainer}
This works because my last line in the psm file is:
Export-ModuleMember -Function New-AzureDDAppRegistration, New-AzureDDAppPermission, Sync-AzureDDStorageContainer
Now I wanted to add versionning and more meta data and went on with
> New-ModuleManifest -Path .\AzureDD.psd1 -ModuleVersion "2.0"
which creates a new file AzuerDD.psd1. In here I edited a lot of stuff. Besides other changes I also defined the exported functions as follows:
FunctionsToExport = #('New-AzureDDAppPermission', 'New-AzureDDAppRegistration', 'Sync-AzStorageContainer')
I can test this successfully:
> Test-ModuleManifest .\AzureDD.psd1
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 2.0 AzureDD {New-AzureDDAppPermission, New-AzureDDAppRegistration, Sync-AzStorageContainer}
But when I actually import this it will not show any exported command:
> Import-Module .\AzureDD.psd1
> Get-Module | Where { $_.Name -eq 'AzureDD' }
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 2.0 AzureDD
See how it changed to Manifest compared to my very first snippet! I've ensured that I did Remove-Module AzureDD -Force all the time before I re-imported it.
FunctionsToExport is like a sieve - it just allows nested modules to export their functions via the manifest, but they still have to be defined somewhere.
Make sure the script module (the .psm1 file) is specified as the RootModule (or at least a NestedModule) in the manifest:
#{
# Script module or binary module file associated with this manifest.
RootModule = 'AzureDD.psm1'
# ...
}

remote IBM MQ monitoring from power-shell commands / scripts

I am trying to get queue depth for remote IBM MQ using PowerShell script/commands. Seems it is not working correctly, please help.
{
$myremoteconns = New-WMQQmgrConnDef -Name T.test.TEST.QM1 -Hostname abcd_testhost01 -Port 1111 -Channel T.test.MQMQ.TESTCHN
$qm = Get-WMQQueueManager -Connections $myremoteconns | where {$_.Name -like 'T.test.TEST.QM1'}
Error New-WMQQmgrConnDef the term 'New-WMQQmgrConnDef' is not recognized
Already installed WebSphere MQ - Windows PowerShell Library from below.
http://www-01.ibm.com/support/docview.wss?uid=swg24017698
Thanks
This error means that PowerShell cannot find this cmdlet. You need to check if the module you installed is properly found by PowerShell. Check this first:
Get-Module -ListAvailable
The result will be like:
PS C:\Users\username\PowerShell> get-module -ListAvailable
Directory: C:\Program Files\WindowsPowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 3.0.1 ImportExcel {Import-Html, ConvertFrom-ExcelSheet, PieChart, Import-UPS...}
If you don't find the module on the list you can import it manually using:
Import-Module -Name 'C:\path\to\module.psm1'
In PowerShell (starting at V3) modules should be imported automatically if they are inside on of the path specified in environment variable PSModulePath. You can check its value by using:
$env:PSModulePath
Once you know which folders are included in this variable you can either move the module there or just add another path using
$env:PSModulePath = $env:PSModulePath + ";c:\path\to\module"
This will work for current session. If you want to modify it for all session you can add the line below to PowerShell profile.
More info:
Importing a module
Modifying PSModulePath
PowerShell profiles

Import-Module works only when piped from Get-Module

I wrote a simple PowerShell module. I need to keep more versions of the module. All paths to versions are added to $env:PSModulePath. I'm facing strange problem when importing the module to my session.
This fails:
Import-Module Contoso.PowerShell -RequiredVersion "0.0.2"
Import-Module : The specified module 'Contoso.PowerShell' with version '0.0.2'
was not loaded because no valid module file was found in any module directory.
At line:1 char:1
+ Import-Module Contoso.PowerShell -RequiredVersion "0.0.2"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (Contoso.PowerShell:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleWithVersionNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
And now the strange thing - the module with the "0.0.2" version exists. I can successfully list it (with Get-Module -ListAvailable). I can even import it and work with it, but the only way how to do it is this:
Get-Module Contoso.PowerShell -ListAvailable |
? { $_.Version -eq "0.0.2" } |
Import-Module
Everything works like a charm then. The question is: WHY? I'd like to be able to import the module with the first simple command.
EDIT:
Here is how I store the versions of the module:
Get-Module Contoso.PowerShell -ListAvailable
Directory: C:\Program Files\WindowsPowerShell\Modules\Contoso.PowerShell\Contoso.PowerShell.0.0.1
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 0.0.1 Contoso.PowerShell
Directory: C:\Program Files\WindowsPowerShell\Modules\Contoso.PowerShell\Contoso.PowerShell.0.0.2
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 0.0.2 Contoso.PowerShell
And sorry for confusion - I do NOT have paths to each version in the PSModulePath environment variable.
The reason Import-Module works is because it uses a different parameter set; one where it accepts one or more [PSModuleInfo] objects, which are what Get-Module returns.
Likely, it uses the work already done by Get-Module to determine which file to load.
The next question then is "why doesn't Import-Module find the version the same way Get-Module does?" and the answer to that is "I don't know."
While they should be consistent in any case, a possible cause for trouble is your directly structure. How are you storing multiple versions?
It looks to me like your module paths are incorrect.
Your structure should be:
Contoso.PowerShell\0.0.2
Contoso.PowerShell\0.0.3
etc.
The module files go directly in the version number folder, and it shouldn't additionally have the name inside it.
You can see this structure by using Install-Module to install one from a repository and taking a look at how it handles it.

Powershell Binary Module not found but installed

I've created a Binary Powershell Module called ODBCManager. After installing from a feed, I am able to use it's functions successfully, but Get-Module does not find it by name (Get-Module -Name ODBCManager returns null). Get-Module -ListAvailable will show it after a 2 minute query, so it's definitely installed. Also -Verbose on installation says success.
C:\Users\xxxxx> Get-Module -ListAvailable
Directory: C:\Program Files\WindowsPowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.0.1 Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValidation}
Binary 0.1.0.1 ODBCManager {Add-OracleODBC, Get-ODBCDrivers, New-OracleODBC}
Binary 1.0.0.1 PackageManagement {Find-Package, Get-Package, Get-PackageProvider, Get-PackageSource...}
Script 3.4.0 Pester {Describe, Context, It, Should...}
Script 1.0.0.1 PowerShellGet {Install-Module, Find-Module, Save-Module, Update-Module...}
Script 1.2 PSReadline {Get-PSReadlineKeyHandler, Set-PSReadlineKeyHandler, Remove-PSReadlineKeyHandler, Get-PSReadlineOption...}
Manifest 20.0 SqlServer {Add-SqlColumnEncryptionKeyValue, Complete-SqlColumnMasterKeyRotation, Get-SqlColumnEncryptionKey, Get-SqlColumnMasterKey...}
Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.0.0.0 ActiveDirectory {Add-ADCentralAccessPolicyMember, Add-ADComputerServiceAccount, Add-ADDomainControllerPasswordReplicationPolicy, Add-ADFineGrainedPasswordPolicySu... Manifest 1.0.0.0 AppBackgroundTask {Disable-AppBackgroundTaskDiagnosticLog, Enable-AppBackgroundTaskDiagnosticLog, Set-AppBackgroundTaskResourcePolicy, Unregister-AppBackgroundTask...} Manifest 2.0.0.0 AppLocker {Get-AppLockerFileInformation, Get-AppLockerPolicy, New-AppLockerPolicy, Set-AppLockerPolicy...}
Manifest 1.0.0.0 AppvClient {Add-AppvClientConnectionGroup, Add-AppvClientPackage, Add-AppvPublishingServer, Disable-Appv...}
Manifest 2.0.0.0 Appx {Add-AppxPackage, Get-AppxPackage, Get-AppxPackageManifest, Remove-AppxPackage...}
Script 1.0.0.0 AssignedAccess {Clear-AssignedAccess, Get-AssignedAccess, Set-AssignedAccess}
Manifest 1.0 BestPractices {Get-BpaModel, Get-BpaResult, Invoke-BpaModel, Set-BpaResult}
......................
Directory: C:\Program Files (x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.0 SQLASCMDLETS {Add-RoleMember, Backup-ASDatabase, Invoke-ASCmd, Invoke-ProcessCube...}
Manifest 1.0 SQLPS {Backup-SqlDatabase, Add-SqlAvailabilityDatabase, Add-SqlAvailabilityGroupListenerStaticIp, Disable-SqlAlwaysOn...}
Directory: C:\Program Files (x86)\Microsoft SQL Server\130\Tools\PowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 2.0 SQLASCMDLETS {Add-RoleMember, Backup-ASDatabase, Invoke-ASCmd, Invoke-ProcessCube...}
Manifest 1.0 SQLPS {Add-SqlColumnEncryptionKeyValue, Complete-SqlColumnMasterKeyRotation, Get-SqlColumnEncryptionKey, Get-SqlColumnMasterKey...}
C:\Users\xxxxxx> Install-Module -Name ODBCManager -Scope AllUsers -Force -ErrorAction Stop -Verbose
VERBOSE: Using the provider 'PowerShellGet' for searching packages.
VERBOSE: The -Repository parameter was not specified. PowerShellGet will use all of the registered repositories.
VERBOSE: Getting the provider object for the PackageManagement Provider 'NuGet'.
VERBOSE: The specified Location is 'https://www.powershellgallery.com/api/v2/' and PackageManagementProvider is 'NuGet'.
VERBOSE: An error occurred while sending the request.
VERBOSE: Retry downloading 'https://www.powershellgallery.com/api/v2/' for '2' more times
VERBOSE: An error occurred while sending the request.
VERBOSE: Retry downloading 'https://www.powershellgallery.com/api/v2/' for '1' more times
VERBOSE: An error occurred while sending the request.
VERBOSE: Retry downloading 'https://www.powershellgallery.com/api/v2/' for '0' more times
WARNING: Unable to resolve package source 'https://www.powershellgallery.com/api/v2/'.
VERBOSE: Total package yield:'0' for the specified package 'ODBCManager'.
VERBOSE: Getting the provider object for the PackageManagement Provider 'NuGet'.
VERBOSE: The specified Location is 'http://srv-proget/nuget/QASolutions-PS/' and PackageManagementProvider is 'NuGet'.
VERBOSE: Searching repository 'http://srv-proget/nuget/QASolutions-PS/FindPackagesById()?id='ODBCManager'' for ''.
VERBOSE: Total package yield:'1' for the specified package 'ODBCManager'.
VERBOSE: Performing the operation "Install-Module" on target "Version '0.1.0.1' of module 'ODBCManager'".
VERBOSE: The installation scope is specified to be 'AllUsers'.
VERBOSE: The specified module will be installed in 'C:\Program Files\WindowsPowerShell\Modules'.
VERBOSE: The specified Location is 'NuGet' and PackageManagementProvider is 'NuGet'.
VERBOSE: Downloading module 'ODBCManager' with version '0.1.0.1' from the repository 'http://srv-proget/nuget/QASolutions-PS/'.
VERBOSE: Searching repository 'http://srv-proget/nuget/QASolutions-PS/FindPackagesById()?id='ODBCManager'' for ''.
VERBOSE: InstallPackage' - name='ODBCManager', version='0.1.0.1',destination='C:\Users\xxxxxxx\AppData\Local\Temp\191916'
VERBOSE: DownloadPackage' - name='ODBCManager', version='0.1.0.1',destination='C:\Users\xxxxxx\AppData\Local\Temp\191916\ODBCManager\ODBCManager.nupkg',
uri='http://srv-proget/nuget/QASolutions-PS/package/ODBCManager/0.1.0.1'
VERBOSE: Downloading 'http://srv-proget/nuget/QASolutions-PS/package/ODBCManager/0.1.0.1'.
VERBOSE: Completed downloading 'http://srv-proget/nuget/QASolutions-PS/package/ODBCManager/0.1.0.1'.
VERBOSE: Completed downloading 'ODBCManager'.
VERBOSE: Hash for package 'ODBCManager' does not match hash provided from the server.
VERBOSE: InstallPackageLocal' - name='ODBCManager', version='0.1.0.1',destination='C:\Users\xxxxxx\AppData\Local\Temp\191916'
VERBOSE: Catalog file 'ODBCManager.cat' is not found in the contents of the module 'ODBCManager' being installed.
VERBOSE: For publisher validation, current module 'ODBCManager' with version '0.1.0.1' with publisher name ''. Is this module signed by Microsoft: 'False'.
VERBOSE: For publisher validation, using the previously-installed module 'ODBCManager' with version '0.1.0.1' under 'C:\Program Files\WindowsPowerShell\Modules\ODBCManager\0.1.0.1' with publisher name ''. Is this module signed by Microsoft: 'False'.
VERBOSE: Module 'ODBCManager' was installed successfully to path 'C:\Program Files\WindowsPowerShell\Modules\ODBCManager\0.1.0.1'.
I have it hosted in ProGet under a Powershell Modules Feed
On Publish, folder name and DLL name are the same
Manifest has been created
Functions export and execute as expected
Manifest:
#{
RootModule = 'ODBCManager.dll'
ModuleVersion = '0.1.0.1' # filled in by cake-build process
CmdletsToExport = '*'
GUID = 'xxx-xxx-xxx-xx-xx'
DotNetFrameworkVersion = '4.0'
Author = 'xxx'
Description = 'PowerShell Binary Module for manipulating ODBCs.'
CompanyName = 'xxx'
Copyright = '(c) 2017 xxx. All rights reserved.'
PrivateData = #{
PSData = #{
ProjectUri = 'xxxxxxxxxx'
LicenseUri = ''
ReleaseNotes = 'First Release'
}
}
}
Have I forgot something? Because I've tried everything.
EDIT: After help from #BenH I was able to research further and found you can call Get-Module -ListAvailable -Name ODBCManager to quickly show your module installed, but not imported. -- For future reference!
Install-Module and Import-Module are different. Get-Module returns all of the Modules that are imported and Get-Module -ListAvailable returns all of the modules that are installed.
Thus your module is "Installed" but not "Imported".
With later versions of PowerShell, modules are dynamically imported if their functions/cmdlets are defined in the exported functions/cmdlets of the .psd1. But until they are imported, Get-Module will not list them.
Try this:
Import-Module ODBCManager
Get-Module ODBCManager