这是我编写的脚本,用于检查具有给定IP的系统在Linux中是向上还是向下:
#!/bin/bash
clear
x=`date`
read -p "please enter ip:" ip
ping -c1 $ip>/dev/null 2>/dev/null
if [$?!= 0]; then
echo $ip on $x | mail -s "server is down…" admin
else
echo "server is up"
fi我想为PowerShell编辑这段代码,这是我的代码:
$x = date
$IP = Read-Host -Prompt "Please Enter IP"
ping $IP -n 1 > null 2>&1
if ($? -ne 0) {
echo "$IP the server is Down on $x"
} else {
echo "everything is fine"
}但是不管IP是什么,它总是输出"the server is Down"。
发布于 2018-01-25 00:29:04
$?是一个指示最后一个PowerShell语句是否成功执行的自动变量。它的值不是$true就是$false。PowerShell中的比较PowerShell计算为$true,因为第二个操作数被转换为与第一个操作数匹配的类型。0转换为bool成为$false (请看这里),$true -ne $false计算为$true。
如果要检查外部程序的退出代码,则需要使用不同的自动变量($LastExitCode)而不是$?。
ping $IP -n 1 > null 2>&1
if ($LastExitCode -ne 0 ) {
...但是,由于您正在编写PowerShell,所以我建议完全删除外部命令并使用Test-Connection:
if (Test-Connection $IP -Count 1 -Quiet -ErrorAction SilentlyContinue) {
'everything is fine'
} else {
"$IP the server is down on $(Get-Date)"
}发布于 2018-01-25 01:38:13
是否可以尝试使用powershell中内置的“测试连接”:)
$computer = Read-Host -Prompt "Please Enter IP"
test-connection $computer -Count 1 | Select Address,IPv4Address,ResponseTime,BufferSizehttps://stackoverflow.com/questions/48433574
复制相似问题