当文件不存在时,文件检查脚本不会引发关键标志

file check script doesn't raise critical flag when file doesn't exist

我在 PowerShell 中为 Nagios 编写了一个小脚本来检查文件是否存在。 如果存在,状态应为 "ok",如果不存在,则状态应为 "critical".

问题是当文件不存在时,状态不是 "critical",它在 Nagios 中显示为 "unknown"。

$path = "c:\test\test.txt"
$critical = 2
$ok = 0

if (-not (Test-Path $path)) {
  Write-Host "file not exists"
  exit $critical
} else {
  Write-Host "file exists"
  exit $ok
}

您的代码没有任何问题,尽管我可能会像这样简化它:

$path = "c:\test\test.txt"

$fileMissing = -not (Test-Path -LiteralPath $path)

$msg = if ($fileMissing) {'file does not exist'} else {'file exists'}

Write-Host $msg
exit ([int]$fileMissing * 2)

您的问题很可能与您执行脚本的方式有关。如果您 运行 使用 -Command 参数的脚本,如下所示:

powershell.exe -Command "&{& 'C:\path\to\your.ps1'}"

或者像这样:

cmd /c echo C:\path\to\your.ps1 | powershell.exe -Command -

如果发生错误,return 值为 1,否则为 0,无论您设置什么退出代码。

要让 PowerShell return 获得正确的退出代码,您需要在命令字符串中添加 exit $LASTEXITCODE

powershell.exe -Command "&{& 'C:\path\to\your.ps1'; exit $LASTEXITCODE}"

或者使用-File参数调用脚本:

powershell.exe -File "C:\path\to\your.ps1"