我正在迭代一组主机名,需要检查它们正在运行的PowerShell版本。如果检查失败(机器关闭,没有PowerShell,没有配置远程处理等等),那么我将要生成一条消息,指出主机的查询失败。
即使$PSVersionTable.PSVersion
没有PSComputerName
属性,Invoke-Command
似乎也会将其添加为NoteProperty
。
为了处理失败情况,我创建了一个新的System.Version
对象,并为其添加了PSComputerName
NoteProperty
。这是最好的OO或PowerShell方式吗?是否有更好或更简洁的东西?
Try {
$v = Invoke-Command -ComputerName $thishost {$PSVersionTable.PSVersion} -ErrorAction Stop
}
Catch
{
$v = New-Object -TypeName "System.Version"
$v | Add-Member -MemberType NoteProperty -Name PSComputerName -Value "$thishost connect failed"
}
$v
输出类似于:
"BUFFALO","98b47c10-3dcf-4da2-xxxx-xxxx335c7daa","True","2","0","-1","-1","-1","-1"
"BISON","79d4d003-d740-4474-xxxx-xxxx7d801b3a","True","2","0","-1","-1","-1","-1"
"ZEBRA connect failed",,,"0","0","-1","-1","-1","-1"
"WOLF connect failed",,,"0","0","-1","-1","-1","-1"
"FUGU","b26f0c5c-1549-411b-xxxx-xxxxef53ecce","True","5","0","10586","117","0","117"