Search code examples
powershellscriptingnagiosnrpe

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


I write a little script in PowerShell for Nagios that check if file exists. If it exists the status should be "ok", and if not it should be "critical".

The problem is when the file does not exist the status is not "critical", it shows in Nagios as "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
}

Solution

  • There's nothing wrong with your code, although I'd probably streamline it like this:

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

    Your problem is most likely with the way you're executing the script. If you run the script using the -Command parameter, like this:

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

    or like this:

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

    the return value is 1 if an error occured, or 0 otherwise, regardless of what exitcode you set.

    To have PowerShell return the correct exit code you need to add an exit $LASTEXITCODE to the command string:

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

    or call the script using the -File parameter:

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