I's just a basic one, I am new to Powershell. Trying to get the statement below working.
$date = (Get-Date).AddDays(-1)
$currentdate = Get-Date -Format d
$check = Get-WinEvent -FilterHashtable @{LogName="CloudBackup";StartTime=$date;ID=3} *>$null
if ($check -eq $true) {
Write-Host "`nOK: Azure Backup was successful on $currentdate"
exit 0
} else {
Write-Host "`nCritical: Problem with Azure Backup - $currentdate"
exit 2
}
Specially if ($check -eq $true)
doesn't seem to do what expected. As $check
is checking for event ID 3 in the eventlog, if it's there it should return true, if not false. Unfortunately it's returning only false every time.
Could someone please advise? Is there a better way to do that?
$check = Get-WinEvent ... *>$null
Your redirection is suppressing all output, so $check
always has the value $null
, which is interpreted as $false
in a boolean operation.
What you want to use is the automatic variable $?
to check it if the last PowerShell operation was successful.
if ($?) {
Write-Host "OK: Azure Backup was successful on $currentdate"
exit 0
} else {
Write-Host "Critical: Problem with Azure Backup - $currentdate"
exit 2
}