【发布时间】:2020-06-17 03:08:28
【问题描述】:
请告知,任何关于我需要做什么才能成功传递变量的见解将不胜感激。
这可以成功运行,但一次只能在管道列表中的每个 FQDN 上运行。我有 100 多台服务器,所以这可能需要比人们想象的更长的时间。每台服务器大约 1-6 秒
Write-Host "Confirm correct OS is installed" -ForegroundColor Yellow -BackgroundColor Black
$FQDNs | ForEach-Object {
Invoke-Command -ComputerName $_ -Credential $Credentials -ScriptBlock {
$OS = (Get-CimInstance -ClassName CIM_OperatingSystem).Caption
Write-Host "$Using:_`: $OS" -ForegroundColor Green -BackgroundColor Black
Write-Output "$Using:_`: $OS"
}
}
}
如果我添加 -Parallel 参数,它会立即失败并出现以下错误。如果自动变量是我看到 foreach-object 管道它们的唯一方式,我还应该如何提供变量? (我希望那是错误的)
ForEach-Object: C:\Scripts\Checklist.ps1:53
Line |
53 | $FQDNs | ForEach-Object -Parallel {
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| The value of the using variable '$using:_' cannot be retrieved because
| it has not been set in the local session.
这是插入 Parallel 参数的脚本,以准确显示我正在执行该操作的位置
Write-Host "Confirm correct OS is installed" -ForegroundColor Yellow -BackgroundColor Black
$FQDNs | ForEach-Object -Parallel {
Invoke-Command -ComputerName $_ -Credential $Credentials -ScriptBlock {
$OS = (Get-CimInstance -ClassName CIM_OperatingSystem).Caption
Write-Host "$Using:_`: $OS" -ForegroundColor Green -BackgroundColor Black
Write-Output "$Using:_`: $OS"
}
}
}
【问题讨论】:
标签: powershell foreach parallel.foreach