导入模块中的函数在 powershell 脚本中不可用

Functions from an imported module are not available in a powershell script

我正在 Windows 服务器计算机上使用 PowerShell V 4.0。我遇到了无法调试或找不到解决方案的问题。

我有一个 ps1 脚本导入两个 psm1 模块 A 和 B。(B 又导入另一个模块 C)。

Import-Module  $PSScriptRoot\..\lib\infra\moduleA.psm1 
Import-Module  $PSScriptRoot\..\lib\nwm\moduleB.psm1 

#get-logger function works fine. This is defined in moduleA
$log = get-logger

$smisXmlData = [xml] $smisConfigData

#The function get-hostLocalCred is defined in moduleB. This is where the error occurs. 
($username, $password) = get-hostLocalCred $smisXmlData

我无法在脚本中使用第二个模块 moduleB 中的函数。当我 运行 脚本时,它会在使用模块 B 中的函数的地方抛出错误。报错如下(get-hostLocalCred 为函数名)

get-hostLocalCred : The term 'get-hostLocalCred' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling  of the name, or if a path was included, verify that the path is correct and try again.

以下是moduleB中的内容。

#Importing moduleC. 
Import-Module  $PSScriptRoot/../infra/moduleC.psm1

#Defining required functions. These are the functions that are not available in the above script. 
function get-hostLocalCred {
    Param($xmldata)
    $log.entry()
    $username = $xmldata.component.yourhost.localcred.username
    $log.debug("USERNAME: $username")
    $password = $xmldata.component.yourhost.localcred.password
    $log.exit()
    return $username, $password
}

function new-ArrayCredObj {
Param([Parameter(Mandatory = $true)] $user,
  [Parameter(Mandatory = $true)] $password)
    $log.entry()
    $log.info("Creating custom Object")
    $log.debug("User : $user")
    $log.debug("Pwd : $password")
    $arrayCred = New-Object psobject
    $arrayCred | Add-Member -MemberType NoteProperty -Name auser -Value $user
    $arrayCred | Add-Member -MemberType NoteProperty -Name password -Value $password
    $log.exit()
    return $arrayCred
}
.
.
.
.

moduleA 中的函数正在正常执行,但我无法执行moduleB 中的函数。 此外,在控制台中 运行ning 脚本之后,当我尝试使用以下命令行开关查找模块 B 中可用的功能时,

Get-Command -Module ModuleB

我只看到moduleB导入的ModuleC中定义的函数,没有看到moduleB中定义的任何函数。我一直在使用 powershell,但这是我第一次看到这个问题。

当我执行 Get-Module 时,我只看到模块 A 和模块 B。

所有模块都按以下方式导入:

Import-Module  $PSScriptRoot/../lib/newmodules/moduleB.psm1 

全局导入模块也没有解决问题。

像下面这样通过给出实际路径导入模块也没有解决问题。

Import-Module C:\folderpath\ModuleB.psm1 

所有模块中的所有函数定义如下。任何模块中的功能定义都没有区别。

function get-hostLocalCred {
    Param($xmldata)
    # Function Definition 
    return $result
}

我可能遗漏了一个简单的东西,但我无法得到它。很长一段时间以来,我一直在正常导入模块并使用它们,但这是我第一次 运行 解决这个问题。先谢谢您的帮助。

我有类似的问题,通过将“-Scope Global”添加到 import-module cmdlet

当您的清单 (.psd1) 没有指定根模块时会出现此问题。

@{

# Script module or binary module file associated with this manifest.
RootModule = 'mymodule.psm1' 
...

以前,在从 New-ModuleManifest 生成它时,它会默认被注释掉

@{

# Script module or binary module file associated with this manifest.
# RootModule = '' 
...

也许您在从 PS 会话测试时正在更新模块 B 中的代码。

然后根据 Microsoft's documentation 如果您的模块在同一个调用会话期间发生更改,您应该使用 Import-Module 的 Force 参数。

Import-Module $PSScriptRoot\..\lib\nwm\moduleB.psm1 -Force