Powershell Export-ModuleMember 对象引用错误

Powershell Export-ModuleMember Object Reference Error

我正在尝试自学 Azure Powershell 脚本,最终目标是设置一个脚本,该脚本读取 Excel 电子表格,其中包含要创建的 Azure VM 的规范(例如,VM 类型,标签、时区、要将其添加到哪个 AD 组等)。如果有人对此有任何教程参考,那将非常有帮助。

目前,我对应该相对简单的事情感到困惑。导出函数。我已经打开 Powershell ISE 并尝试 运行 以下代码(摘自我在 MSDN 上找到的示例之一):

Function New-Test
{
    Write-Output 'I am New-Test function'
}
Export-ModuleMember -Function New-Test

function Validate-Test
{
    Write-Output 'I am Validate-Test function'
}
function Start-Test
{
    Write-Output 'I am Start-Test function'
}
Set-Alias stt Start-Test
Export-ModuleMember -Function Start-Test -Alias stt

但我收到一条错误消息: "Export-ModuleMember: Object Reference not set to an instance of an object"

我尝试将此代码保存到名为 test 的 ps1 文件中,然后导航到它所在的目录并 运行ning "./test.ps1" 但是出现同样的错误。

知道我做错了什么吗?我在这里肯定缺少一些基本的东西。

当您计划在 PowerShell 脚本中编写大量代码时,使用 Export-ModuleMember 设置您的模块并控制您导出(或不导出)的内容是正确的做法。因此,如果您计划构建自己的模块以在更多 PowerShell 脚本中使用,那么您就走对了。

您没有提及任何关于模块定义的内容,或者 how/where 您确实在使用这些函数,所以我认为您可能遗漏了首先定义模块的部分。

您可以按照此处的分步指南进行操作:PowerShell: Building a Module, one microstep at a time

我运行也陷入这个错误。对于我自己,我发现 "Export-ModuleMember" 和最后一个函数括号的末尾之间不能有任何换行符。

示例:

导入模块对象引用错误:

function Test-Import{
    Write-Host "import function success"
}

Export-ModuleMember -Function Test-Import

导入模块,没有错误

function Test-Import{
    Write-Host "import function success"
}
Export-ModuleMember -Function Test-Import

在我的例子中,解决方案是引用 psm1 而不是 ps1 找到 psd1 文件

# Script module or binary module file associated with this manifest.
RootModule = 'pf-rootscript.psm1'

而不是

# Script module or binary module file associated with this manifest.
RootModule = 'pf-rootscript.ps1'