我们可以在同一个脚本中编写PowerShell模块并多次调用它吗?



我正在编写一个自动化脚本,需要重用某些代码段。我想到编写模块,并在同一个脚本中随心所欲地调用它。但是当我在线搜索时,看起来模块需要写入一个单独的文件并保存它(.psm1),并且必须在必要时导入到其他 scrips 上。

有没有办法用同一个脚本编写模块并在需要时调用它?就像在 Java 中一样。我不想在单独的文件中编写模块并导入它。我希望我的所有代码都在同一个文件中。

请指教。

嗨杰夫,

$Servers = {"server1","server2","server3"}
Function updatefile([string]$serverNames,[string]$PropName,[string]$PropValue,[string]$env)
{
Write-Output "serverNames" $serverNames
Write-Output "PropName" $PropName
Write-Output "PropValue" $PropValue
}
# Starting of code   
do {
$AppInput = Read-Host "Update required for (1) Application 1 (2) Application 2"
} until ($("1","2").Contains($AppInput))

If($AppInput -eq "Application 1" -or $AppInput -eq "1")
{
$PropName = Read-Host `n 'Enter parameter that requires update?'
$PropValue = Read-Host `n 'Enter the value for '$PropName
}
else
{
Write-Output "Work In Progress"
}
$env = Read-Host `n 'Which environment require change?'
If($env -eq "RD")
{
updatefile ($RDPFServers, $PropName, $PropValue,$env)
}
else
{
Write-Output "Work In Progress"
}

你可以这样做,但考虑到你描述的问题字段,它并没有真正的意义。相反,您可以将通常位于模块中的函数直接放入脚本中,当您运行脚本时,这些函数将可用于脚本的"工作"部分。PowerShell 模块用于有多个需要访问相同函数/cmdlet 的独立脚本;它们允许你为函数/cmdlet 编写一次代码,并在需要时使用它,因为知道它将始终是相同的函数。如果在脚本文件中包含函数(在实际调用它们之前定义!),则可以根据需要在脚本中调用函数 - 当脚本退出时,函数将从内存中消失。

PowerShell 使用"词法"作用域;这意味着您必须在调用函数之前定义该函数;因此,您的脚本文件应如下所示

function Do-Something {
<# function code here #>
}
function Do-SomethingElse {
<# function code here #>
}
Do-Something
Do-SomethingElse

如果尝试在定义出现之前调用函数,则会收到错误,指示函数名称未被识别为函数、别名、cmdlet 等。

最新更新