【发布时间】:2023-10-13 06:36:01
【问题描述】:
我目前正在编写一行代码来对多个 IP 进行 ping 测试并让它返回单个状态更新。我试图拥有它,所以如果所有结果都是$true,则显示绿色,如果结果包含$false,但还有一个$true,则显示黄色,最后如果所有结果均为$false,则显示红色。
以下是我所拥有的。这是我尝试过的东西的一个迭代,但我只能让它用黄色而不是红色来响应。非常感谢任何帮助。
$octets = (Get-NetIPAddress | ?{$_.PrefixOrigin -eq "Manual","Dhcp"}).IPAddress.Split(".")
$ipFirst3 = $octets[0] + "." + $octets[1] + "." + $octets[2]
$ESX1MGT = $ipFirst3 + '.' + "181" #esxi management
$ESX1STG = $ipFirst3 + '.' + "151" #esxi storage
$ESX1VMO = $ipFirst3 + '.' + "71" #esxi vmotion
If(Test-Connection $ESX1MGT -count 2 -Quiet){
$MGTStatus = "True"
}else{
$MGTStatus = "False"
}
If(Test-Connection $ESX1STG -count 2 -Quiet){
$STGStatus = "True"
}else{
$STGStatus = "False"
}
If(Test-Connection $ESX1VMO -count 2 -Quiet){
$VMOStatus = "True"
}else{
$VMOStatus = "False"
}
$ESX1Status = @($MGTStatus,$STGStatus,$VMOStatus)
If($ESX1Status -eq "True"){
$ESX1StatusLabel.BackColor = "Green"
}elseif ($ESX1Status -contains "False") {
$ESX1StatusLabel.BackColor = "Yellow"
}elseif ($ESX1Status -eq "False") {
$ESX1StatusLabel.BackColor = "Red"
}
编辑这是我尝试过的另一个想法
$ESX1Status = @($ESX1MGT,$ESX1STG,$ESX1VMO)
$result = Foreach($ESX in $ESX1Status){
Test-Connection $ESX -Count 2 -Quiet
}
If($result -is $true){
$ESX1StatusLabel.BackColor = "Green"
}
If($result -contains $false -and $true){
$ESX1StatusLabel.BackColor = "Yellow"
}
If($result -is $false){
$ESX1StatusLabel.BackColor = "Red"
}
同时运行两个版本时,有时会出现此错误
Cannot convert value "True" to type "System.Type". Error: "Invalid cast from 'System.Boolean' to 'System.Type'."
At C:\Source\Scripts\PowerShell\Verification.ps1:420 char:4
+ If($result -is $true){
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
【问题讨论】:
-
-is用于检查特定类型(例如$result -is [bool]),-eq用于比较变量的相等性(例如:$result -eq $true)。
标签: powershell ping status