PowerShell,无法弄清楚如何将变量传递给作业
PowerShell, can't figure out how to pass variables to a job
我有以下一段脚本有问题。它应该使用在作业之外分配的变量($FilePath 和 $Computer)来收集安装在指定机器上的修补程序,并将该信息保存在脚本 运行 所在的系统上。
在这个场景中,$host_array只包含127.0.0.1;所以 $Computer = 127.0.0.1。环回地址与命令一起使用,所以除了我得到的错误(在脚本下方列出)之外;我不确定我做错了什么。
ForEach($Computer in $Global:host_array){
Start-Job -ScriptBlock {
$HotFix=Get-HotFix -ComputerName $Computer
$HotFix | Export-CSV "$FilePath$Computer`_HotFix.csv" -NoTypeInformation
} -ArgumentList $FilePath $Computer
}
到目前为止,没有通过 Export-CSV 保存文件,我收到以下错误:
开始作业:无法绑定参数 'InitializationScript'。无法将类型“System.String”的值“127.0.0.1”转换为类型“System.Management.Automation.ScriptBlock”。
像这样:
$FilePath="$HOME\Documents\"
$host_array="127.0.0.1"
ForEach($Computer in $host_array){
Start-Job -ScriptBlock {
$FilePath=$args[0];$Computer=$args[1]
$HotFix=Get-HotFix -ComputerName $Computer
$HotFix | Export-CSV "$FilePath$Computer`_HotFix.csv" -NoTypeInformation
} -ArgumentList $FilePath,$Computer
}
或者像这样:
$FilePath="$HOME\Documents\"
$host_array="127.0.0.1"
ForEach($Computer in $host_array){
Start-Job -ScriptBlock {
$HotFix=Get-HotFix -ComputerName $using:Computer
$HotFix | Export-CSV "$using:FilePath$using:Computer`_HotFix.csv" -NoTypeInformation
}
}
全局变量不会在这里帮助你,因为作业的范围是在一个完全不同的过程中。此外,您可能想看看 ThreadJob 模块 https://docs.microsoft.com/en-us/powershell/module/threadjob/start-threadjob?view=powershell-7.1
我有以下一段脚本有问题。它应该使用在作业之外分配的变量($FilePath 和 $Computer)来收集安装在指定机器上的修补程序,并将该信息保存在脚本 运行 所在的系统上。
在这个场景中,$host_array只包含127.0.0.1;所以 $Computer = 127.0.0.1。环回地址与命令一起使用,所以除了我得到的错误(在脚本下方列出)之外;我不确定我做错了什么。
ForEach($Computer in $Global:host_array){
Start-Job -ScriptBlock {
$HotFix=Get-HotFix -ComputerName $Computer
$HotFix | Export-CSV "$FilePath$Computer`_HotFix.csv" -NoTypeInformation
} -ArgumentList $FilePath $Computer
}
到目前为止,没有通过 Export-CSV 保存文件,我收到以下错误:
开始作业:无法绑定参数 'InitializationScript'。无法将类型“System.String”的值“127.0.0.1”转换为类型“System.Management.Automation.ScriptBlock”。
像这样:
$FilePath="$HOME\Documents\"
$host_array="127.0.0.1"
ForEach($Computer in $host_array){
Start-Job -ScriptBlock {
$FilePath=$args[0];$Computer=$args[1]
$HotFix=Get-HotFix -ComputerName $Computer
$HotFix | Export-CSV "$FilePath$Computer`_HotFix.csv" -NoTypeInformation
} -ArgumentList $FilePath,$Computer
}
或者像这样:
$FilePath="$HOME\Documents\"
$host_array="127.0.0.1"
ForEach($Computer in $host_array){
Start-Job -ScriptBlock {
$HotFix=Get-HotFix -ComputerName $using:Computer
$HotFix | Export-CSV "$using:FilePath$using:Computer`_HotFix.csv" -NoTypeInformation
}
}
全局变量不会在这里帮助你,因为作业的范围是在一个完全不同的过程中。此外,您可能想看看 ThreadJob 模块 https://docs.microsoft.com/en-us/powershell/module/threadjob/start-threadjob?view=powershell-7.1