我正在尝试自学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:对象引用未设置为对象的实例”
我尝试将这段代码保存到名为test的ps1文件中,然后导航到该目录所在的目录并运行“ ./test.ps1”,但出现相同的错误。
对我在这里做错的任何想法吗?我肯定在这里缺少一些基本的东西。
答案 0 :(得分:1)
在我的情况下,解决方案是引用psm1而不是psd1文件中的ps1
# 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'
答案 1 :(得分:0)
当您计划在PowerShell脚本中编写大量代码时,正确的做法是设置模块并使用Export-ModuleMember控制导出(或不导出)的内容。因此,如果您打算构建自己的模块以在其他PowerShell脚本中使用,那么您将走上正确的轨道。
您没有提到有关模块定义或使用这些功能的确切方式/位置的任何信息,因此我认为您可能缺少首先定义模块的部分。
您可以在这里按照逐步指南进行操作:PowerShell: Building a Module, one microstep at a time
答案 2 :(得分:0)
我也遇到了这个错误。就我自己而言,我发现“ 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