1

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

问题是当文件不存在时,状态不是“关键”,它在 Nagios 中显示为“未知”。

$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
}
4

1 回答 1

3

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

$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 -

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

要让 PowerShell 返回正确的退出代码,您需要exit $LASTEXITCODE在命令字符串中添加一个:

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

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

powershell.exe -File "C:\path\to\your.ps1"
于 2015-07-05T14:37:02.017 回答