当前正在制作将使用PowerShell生成的新报告。使用PowerShell构建HTML电子邮件。我有另一份报告工作正常,但在此报告上遇到了意外问题。
以下代码只是我仍在构建的脚本的示例。仍在脚本中添加片段,但在前进时对其进行测试。我添加了Test-Connection
来查看计算机是否响应,并且失去了构建阵列的能力。
我使用此报告的最终目标是从文件中导入名称列表,然后遍历所有计算机以查看它们是否能够ping通,并使用Get-WMIObject
等从它们中收集一些信息。
以下代码将复制我遇到的问题,但是我不确定如何解决。我已将问题范围缩小到Test-Connection
返回'False'时。在第26行上,我只过滤在Test-Connection
上返回'False'的结果,以将其保存到自己的数组中,这样我就可以在代码的不同部分中使用该数组来构建HTML表/ HTML以发送出去电子邮件。
只有反面,如果我告诉它只寻找'True',它将保存到数组中而不会出现问题。
这是PowerShell通过“False”进行过滤时给出的错误。
如果还有其他信息,请告诉我。我已经坚持了一段时间。同事们甚至都说这很奇怪。Test-Connection
返回'False'的方式有什么独特之处吗?
CLS
[string]$ErrorActionPreference = "Continue"
[System.Collections.ArrayList]$Names = @(
"Computer1"
"Computer2"
)
[System.Collections.ArrayList]$WMI_Array = @()
[System.Collections.ArrayList]$Ping_Status_False = @()
foreach ($Name in $Names) {
[bool]$Ping_Status = Test-Connection $Name -Count 1 -Quiet
$WMI_Array_Object = [PSCustomObject]@{
'Computer_Name' = $Name
'Ping_Status' = $Ping_Status
}
$WMI_Array.Add($WMI_Array_Object) | Out-Null
}
$WMI_Array | Format-Table
[System.Collections.ArrayList]$Ping_Status_False = $WMI_Array | Where-Object {$_.Ping_Status -eq $false} | Select-Object Computer_Name, Ping_Status
$Ping_Status_False
最佳答案
问题不在于Test-Connection
,而是该语句
$WMI_Array | Where-Object {$_.Ping_Status -eq $false} | Select-Object Computer_Name, Ping_Status
只产生一个结果。它不是数组,因此不能转换为
ArrayList
。当您仅使用一个匹配对象过滤$_.PingStatus -eq $true
时,行为是相同的,因此我怀疑在测试该条件时,您可以成功ping通一个主机,或者根本没有一个可以ping通的主机,并且不会引发相同的错误。您可以通过将语句包装在数组子表达式运算符中来减轻问题:
[Collections.ArrayList]$Ping_Status_False = @($WMI_Array |
Where-Object {$_.Ping_Status -eq $false} |
Select-Object Computer_Name, Ping_Status)
或者,您可以简单地从代码中删除所有毫无意义的类型转换:
$ErrorActionPreference = "Continue"
$Names = 'Computer1', 'Computer2'
$WMI_Array = foreach ($Name in $Names) {
[PSCustomObject]@{
'Computer_Name' = $Name
'Ping_Status' = [bool](Test-Connection $Name -Count 1 -Quiet)
}
}
$WMI_Array | Where-Object { -not $_.Ping_Status }
关于arrays - 测试连接$ False不会转换为ArrayList,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51090847/