gpt4 book ai didi

powershell - 当传递给invoke-command时,Powershell 7 ForEach-Object Parallel会中断自动变量

转载 作者:行者123 更新时间:2023-12-03 01:26:33 25 4
gpt4 key购买 nike

请告知,我需要做些什么才能成功传递变量,我们将不胜感激。

这可以成功工作,但是一次可以处理管道列表中的每个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"
}
}
}

最佳答案

调用命令计算机名comp1,comp2,comp3已并行运行。

# elevated prompt
start-service winrm
invoke-command localhost,localhost,localhost { sleep 10 }
(get-history)[-1] | fl

Id : 3
CommandLine : invoke-command localhost,localhost,localhost { sleep 10 }
ExecutionStatus : Completed
StartExecutionTime : 6/19/2020 10:05:02 AM
EndExecutionTime : 6/19/2020 10:05:13 AM # 11 seconds for all three

关于powershell - 当传递给invoke-command时,Powershell 7 ForEach-Object Parallel会中断自动变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62420837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com