检查系统是否已关闭

check if the system is down or not

这是我编写的脚本,用于检查具有给定 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"

$? 是一个 automatic variable indicating whether or not the last PowerShell statement was executed successfully. Its value is either $true or $false. A comparison $true -ne 0 in PowerShell evaluates to $true, because the second operand is cast to a type matching the first operand. 0 cast to bool becomes $false (see here),$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)"
}

也可以尝试使用 powershell 中的内置 "test-connection" :)

$computer = Read-Host -Prompt "Please Enter IP"
test-connection $computer -Count 1 | Select Address,IPv4Address,ResponseTime,BufferSize