PowerShell Where Clause – Compare to a list of values

As a databases admin with a few dozen servers and a few hundred SQL Server database, I need to effectively build automated jobs to perform various administrative tasks such as backing up databases. I’m still new to PowerShell but I am beginning to see how immensely helpful it is to me and my work.

I found a good PowerShell script for backing up databases at this blog location. However, I wanted to change it slightly to accommodate backing up ALL, System, User, or a list of databases. Processing ALL, System, or User is straightforward enough but I had to it was the first time I came up against have to compare a value against a list of values. In SQL you simply use an IN operator with a list of values but I was not sure of how to accomplish the same process in PowerShell.

Here was my problem: the user could supply a list of databases to backup and the backup script has a line with captures all the database objects for that SQL Server instance. I need to backup only those which are in the users list.

I found that the PowerShell WHERE clause can use a -contains operator which effectively filters the selection for an array. To test the operation I set up a small script to build two arrays and then I piped one array through a WHERE filter of which the results are piped to a ForEach. The ForEach sees only the results of the WHERE which mimics the SQL IN operator.

Run this code in PowerShell to see what I mean.

$a = @("db1","db2","db3","db4")
$d = @("db1","db2","db3","db4","db5","db6","db7","db8")
$d | where { $a -contains $_ } | foreach { Write-Host $_ }

$a represents the list of database supplied by the user.
$d represents the array of databases returned when accessing the Microsoft.SqlServer.Management.Smo.Server object.
I can now back up the user supplied databases within the foreach script block.

Leave a Reply