## Check-Exchange2007Backups
## Julius Schlosburg
## October 2010
#
# Simple script to check whether Exchange has been backed up
# recently. Returns codes compatible with Nagios
#
# Usage: Check-Exchange2007Backups.ps1 -d <MailboxDatabase Identity> -w <warning days ago> -c <critical days ago>
# e.g. Check-Exchange2007Backups.ps1 -d "CONTOSO-MAIL-01\First Storage Group\Mailbox DB 1" -w 2 -c 4
#
#Script can be called from NSClient++ like this:
##
## [NRPE Handlers]
## check_exchange2007backups = CMD /C ECHO C:\Scripts\Check-Exchange2007Backups.ps1 -w 2 -c 4 -d
##  "CONTOSO-MAIL-01\First Storage Group\Mailbox DB 1" ; exit $LASTEXITCODE | powershell.exe -PSConsoleFile 
##  "D:\Program Files\Microsoft\Exchange Server\Bin\ExShell.psc1" -command -
# The check command should all be on one line. You pipe the command into powershell.exe and include the
# $LASTEXITCODE so that Nagios can parse the state properly. Kind of round about but it works.

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.


##                  INIT               ##

param($w,$c,$d)
$warning = $w
$critical = $c
$exchangeDB = $d

$state = 2
$exitCode = 255

##                  FUNCTIONS          ##

function getDaysOld($exchangeDB){
	# Current date minus date of last full backup, returns an int representing the
	# difference in days.
	return ((Get-Date) - (Get-MailboxDatabase -Identity $exchangeDB -Status).LastFullBackup).Days
}

##                  MAIN               ##

$daysOld = (getDaysOld $exchangeDB)

if ($daysOld -ge $warning){
	$state++
}
elseif ($temp -lt $warning){
		$state--
}
if ($daysOld -gt $critical){
	$state++
}
elseif ($daysOld -lt $critical){
		$state--
}
if ($state -eq 0){
	$message = "OK: Exchange backups are good at " + $daysOld + " day(s) old."
	$exitCode = 0
}
elseif ($state -lt 3){
		$message = "WARNING: Last Exchange backup was " + $daysOld + " days ago!"
		$exitCode = 1
}
elseif ($state -le 4){
		$message = "CRITICAL: Last Exchange backup was " + $daysOld + " days ago!"
		$exitCode = 2
}

$perfData = "|daysold=" + $daysOld + ";" + $warning + ";" + $critical

Write-Host $message$perfData
exit $exitCode