773
Chapter 30: Confi guring and Managing SQL Server with PowerShell
30
2
4
6
8
Now, within the script block operating on the members of the collection, conditions can be
checked. For example, if the script should operate only on elements with a value not greater
than 4, the script would read as follows:
PS> $stuff | foreach-object { if ($_ -gt 4) {break}
else {write-output $_}}
1
2
4
The following list shows most of the comparison operators within PowerShell.
■ (^) -lt: Less than
■ (^) -le: Less than or equal to
■ (^) -gt: Greater than
■ (^) -ge: Greater than or equal to
■ (^) -eq: Equal to
■ (^) -ne: Not equal to
■ (^) -like: Like wildcard pattern matching
Suppose you have a text fi le called servers.txt that contains a list of servers, one server
name per line. The fi le might resemble something like this:
SQLTWSS
SQLTBXP
SQLTBW7
SQLPROD1
SQLPROD2
By using the Get-Content cmdlet, this list of servers can easily be brought into a
PowerShell variable as a collection by issuing the following command:
$servers = Get-Content 'servers.txt'
Each element in the collection can be addressed by its ordinal number, so the fi rst item is
referenced by $servers[0], the second item by $servers[1], and so on. This ability to
create collections can come in handy later in this discussion.
Comments, always good in any language, are specifi ed in PowerShell 1.0 by using the pound
(#) character, with the comments following that character on the line. (PowerShell 2.0 can
support an additional comment operator, enabling multiline comments, for example,
<# Multi-Line Comment #>.)
c30.indd 773c30.indd 773 7/31/2012 9:46:21 AM7/31/2012 9:46:21 AM
http://www.it-ebooks.info