gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:23:17 25 4
gpt4 key购买 nike

我正在 Windows Server 机器上使用 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 中的函数。
此外,在控制台中运行脚本后,当我尝试使用以下命令行开关查找模块 B 中可用的功能时,
Get-Command -Module ModuleB

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

当我执行 Get-Module 时,我只看到 moduleA 和 moduleB。

所有模块都通过以下方式导入:
Import-Module  $PSScriptRoot/../lib/newmodules/moduleB.psm1 

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

通过给出如下的实际路径来导入模块也没有解决问题。
Import-Module C:\folderpath\ModuleB.psm1 

所有模块中的所有功能都定义如下。任何模块中的函数定义都没有区别。
function get-hostLocalCred {
Param($xmldata)
# Function Definition
return $result
}

我可能错过了一件简单的事情,但我无法得到它。长期以来,我一直在正常导入模块并使用它们,但这是我第一次遇到这个问题。在此先感谢您的帮助。

最佳答案

当您的 list (.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 = ''
...

关于powershell - 来自导入模块的函数在 powershell 脚本中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38316754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com