As you may expect from a top-notch scripting language, PowerShell supports functions.
There are several advantages of investing in the time needed to create functions. One advantage of a function is that once you get it working, it's easy to call the commands later in the same script, moreover,
once perfected,
the code works consistently.
Another advantage of functions is that they help organize a long script into manageable chunks.
The task that I have set for our function is to enumerate which services are in each of the generic svchosts processes that you see in Task Manager. Incidentally, the reason for multiple svchosts is that
certain processes 'fight' and thus must be kept separate. The solution is for the operating system to create multiple svchosts; for example, RemoteRegistry cannot co-exist with TermService.
Our mission is to create a function which combines both of the above commands and thus achieves a single list of all the svchosts with their corresponding services.
This is the output of our goal, we want our function called plist to produce this output:
When you declare a function it requires as a minimum: FunctionNname {Block of Work}. The actual work is done by the PowerShell statements between the required {braces}. Functions may include
optional parameters, these are enclosed in (parenthesis) and are introduced after the function's name,
but before it gets to work with the {}.
Guy
Recommends: WMI Monitor and It's Free!
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems. Fortunately, Solarwinds
have created a
Free WMI Monitor so that you can discover these gems of performance
information, and thus improve your PowerShell scripts. Take the guess work out of which WMI counters to use when scripting the
operating system, Active Directory or Exchange Server.
# Here is the plist function in action
processing the svchost processes: plist svchost* | format-Table -autosize name,Id,service
Learning Points from the Function Example
Note 1:
Plist will be a string function and not an integer and is declared thus: function plist([string]$name="*")
Note 2: $Name="*" returns all the names of the objects that get processed.
Note 3: Let us consider the instructions inside the {Braces}, starting with the variable $Svc. What this does is get the wmi win32_service. Here is the command: $Svc = Get-wmiobject win32_service | sort ProcessId | group-Object ProcessId
Note 4: The loop is covered by this While construction, the key is lt (less than): while($i -lt $ps.count -and $j -lt $svc.count)
Note 5: The process name is controlled by: $ps = @(Get-Process $name | sort Id)
Note 6: This is the clever line that appends all the services to each individual svchost $ps[$i]| add-Member NoteProperty service $Svc[$j].group;
Footnote - Simpler code
It is possible to replace the plist function (above) with more efficient code, nevertheless, remember that the purpose of this page is to introduce PowerShell functions.
Here is the alternative code if you just wish to check the instances of svchost
function plist([string]$a) {
$FormatEnumerationLimit = 100 gwmi win32_service |? {$_.PathName -match 'svchost' -and $_.ProcessId -ne 0} | group ProcessId | ft
}
Plist
Guy Recommends: Solarwinds' Free Bulk Import Tool
Import users from a spreadsheet. Just provide a list of the
users with their fields in the
top row, and save as .csv file. Then launch this FREE utility and match
your fields with AD's
attributes, click to import the users. Optionally, you can
provide the name of the OU where the new accounts will be born.
There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:
It always amazes my how researching PowerShell increases my knowledge of
other fields, in this instance I discovered that the SVCHOST (s) are
populated by settings in the registry.
Firstly, some possible reasons for turning off System Restore. Perhaps you dealing with an Anti-virus program which is interfering
with the restore process and you need to turn off System Restore while
you deal with other program. Maybe the drive has run out of free
space and you need to stop system restore consuming any more disk space.
At the heart of this example is [WmiClass]"\\$SysName\root\default:systemrestore".
Once we assign it to the variable $SysRestore, we can apply one of two
methods, .Disable("C:\") or .Enable("C:\").
The rest of the script consists of two wrappers, one to switch
between "Enable" and "Disable", the other wrapper is
the function called GuyRestore.
# PowerShell Function Example Clear-Host Function GuyRestore { param( $RestoreOpt =
$(throw "Specify option, disable or enable"), $SysName = $(throw
"Specify computer name or IP Address.) ) switch ($RestoreOpt) {
"disable" {$SysRestore = [WmiClass]"\\$SysName\root\default:systemrestore" $SysRestore.Disable("C:\")}
"enable" {$SysRestore = [WmiClass]"\\$SysName\root\default:systemrestore" $SysRestore.Disable("C:\")}
}
}
Note 0: This is one of those PowerShell scripts
where you need to 'Run as Administrator'. Also Restore Points are a feature of
client operating systems such as Windows 7 or Vista, and not servers.
Note 1: The last line puts the function
GuyRestore to work, and disables the system restore on the C:\.
Note 2: Pay close attention to -SysName, your
Windows 7 or Vista machine is unlikely to have an IP address of
192.168.1.166. You could of course use the hostname.
The purpose of this page is to understand how a PowerShell function is constructed. Take it one line at a time. My goal was to break down a complex task into a series of single commands. The
vehicle for our example task was the task manager, specifically, drilling down into the
contents of each SVCHOST process.
If you like this page then please share it with your friends
See more PowerShell examples for syntax constructions
Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems.
Fortunately, Solarwinds
have created the
Free WMI Monitor so that you can actually see and understand these gems of
performance information. Take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.