Compare jobs with PowerShell

I’m more amazed every day at how much easier powershell makes administering sql server.  We currently have this big messy home-grown monitoring system to compare and track changes in sql server.  It’s complicated, fragmented and difficult to debug.  I just duplicated the whole job-compare section of the monitoring system with 9 lines of code.  This will tell you which jobs were added and which ones were removed.  I’ve not tested it thoroughly (nay, at all), like what happens when you change a schedule on a job or whatnot, but this is a good start:

sl SQLSERVER:\SQL\SERVERNAME\DEFAULT\JobServer\Jobs
$jobs = Get-ChildItem
$jobsPrevious = Import-Clixml -Path C:\JobsPrevious.xml
$difference = Compare-Object -ReferenceObject $jobsPrevious -DifferenceObject $jobs
$Removed = @($difference | Where {$_.SideIndicator -eq "<="} | foreach {$_.InputObject}) -join ", "
$Added = @($difference | Where {$_.SideIndicator -eq "=>"} | foreach {$_.InputObject}) -join ", "

Write-Host "Removed:  $Removed"
Write-Host ""
Write-Host "Added:  $Added"

This just does the jobs, but there’s no reason why you couldn’t apply this code to other nodes in the SMO object model.

Powershell is amazing.  If you’re not using powershell to administer SQL Server, you’re really doing yourself a HUGE disservice.  Use at your own risk.

Update:  The xml that returns from get-childitem will be huge.  Also note, that you should actually write the $jobs out to file and re-load it using the Import-Clixml in order for the compare-object to compare properly.  I’m STILL working on getting this up to snuff, but I’m currently stretched too thin to dedicate any time to this at the moment.  I’ll put up a better post once I’m done with it, but this is a good starting point.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: