Cla*_*lay 2 powershell foreach
我正在努力解决以下问题。我正在尝试从我们的 2016 终端服务器接收当前安装的 Edge 版本。但是当我运行到 powershell 下面的代码时,显示版本 95.0.1020.30 已安装。
$Servers = get-content C:\users\xxx\Documents\Servers.txt
$servers|foreach-object -parallel {
Get-Ciminstance -ComputerName $Servers -Class Win32_Product | where {$_.Name -Like "*Edge*"} | foreach {$_.Version}
}
Run Code Online (Sandbox Code Playgroud)
现在到有趣的部分:当我使用通常的 foreach 循环时,它会返回正确的版本。
$Servers = get-content C:\users\cma-admin\Documents\Servers.txt
foreach($server in $servers){
Get-Ciminstance -ComputerName $Server -Class Win32_Product | where {$_.Name -Like "*Edge*"} |
foreach {$_.Version}
}
Run Code Online (Sandbox Code Playgroud)
我很乐意将它与“-parallel”一起使用,因为这样可以更快地获取这些信息。我确实在强大的互联网上爬行了很多,但我没有找到任何特定于这个“错误”的内容。我不太确定我是否正确使用了 foreach -parallel。
此致,
黏土
使用$servers | foreach-object -parallel { ... }要求您使用自动$_变量来引用脚本块内的当前服务器(管道输入对象):
$servers|foreach-object -parallel {
# Note the use of $_
Get-Ciminstance -ComputerName $_ -Class Win32_Product |
where {$_.Name -Like "*Edge*"} |
foreach {$_.Version}
}
Run Code Online (Sandbox Code Playgroud)
但是,不需要循环(具有并行性),因为CIM cmdlet(例如Get-CimInstance)具有内置并行性,您只需将服务器名称数组传递-ComputerName给即可利用它:
Get-Ciminstance -ComputerName $servers -Class Win32_Product |
where Name -Like "*Edge*" |
foreach Version
Run Code Online (Sandbox Code Playgroud)
注意:以上使用简化语法。
结果将不按特定顺序到达。您可以使用.PSComputerNamePowerShell 装饰所有输出对象的属性来标识特定结果对象源自的服务器。