779
Chapter 30: Confi guring and Managing SQL Server with PowerShell
30
The basic format of a function is as follows:
Function MyFunction {
#work
}
This, of course, doesn’t do anything. Between the braces the real work needs to be coded,
but most often functions need parameters. You can add functions in a number of ways, but
two ways are most commonly used. The fi rst, most obvious, format is like this:
Function MyFunction ($param) {
#work
}
This works fi ne, but the recommended method is to use a param block within the function,
which enables the specifi cation of multiple parameters, the specifi cation of the data type
for each parameter, and default values for each parameter:
Function MyFunction {
param (
[int]$x = 7,
[int]$y = 9
)
#work
}
The GetSysInfo.ps1 script (refer to Listing 30-1) is useful when run on an individual
server but would be even more so if it could be run against all servers in the data center. By
putting the working code from GetSysInfo.ps1 into a function (and adding the
–computername parameter to each Get-WMIObject command within the function to
specify which server to run the command against), it’s possible to iterate through the set of
servers in the $servers collection discussed earlier.
Listing 30-2 shows exactly how to do this. The function with the calls to the four WMI
classes is defi ned fi rst, followed by the main part of the script. Note that before attempt-
ing to get the server information, the main part of the script uses the WMI class Win32_
PingStatus to determine whether the computer is reachable through the network. This
saves time because the script doesn’t attempt to run the four main queries against a server
that doesn’t respond.
LISTING 30-2 ServerStatus.ps1
function getwmiinfo ($svr) {
gwmi -query "select * from
Win32_ComputerSystem" -computername $svr | select Name,
Model, Manufacturer, Description, DNSHostName,
Domain, DomainRole, PartOfDomain, NumberOfProcessors,
SystemType, TotalPhysicalMemory, UserName,
Continues
c30.indd 779c30.indd 779 7/31/2012 9:46:22 AM7/31/2012 9:46:22 AM
http://www.it-ebooks.info