Introduction to Scripting PowerShell Function
As you may expect from a top-notch scripting language, PowerShell supports functions. There are several advantages of investing time in creating functions. One benefits 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.
PowerShell Function Topics
- Our Practical Task – Enumerate svchost
- A Function called Plist
- Here is the Code for the Plist Function
- How to Create a Function
- Registry Information on SVCHOST
- Another PowerShell Function Example
- Summary of PowerShell Functions
♣
Our Practical Task – Enumerate svchost
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.
Preliminary Commands
To get the idea of what we want to achieve, try these two commands individually:
Get-Process * | Sort-Object ProcessName
And then
Get-WmiObject win32_service | Sort ProcessId | Group-Object ProcessId
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:
Name Id service
—– — ——————-
svchost 740 {ERSvc}
svchost 916 {TapiSrv}
svchost 1120 {RemoteRegistry}
svchost 1392 {DcomLaunch}
svchost 1712 {RpcSs}
svchost 1772 {Dnscache, Dhcp}
svchost 1832 {LmHosts, W32Time}
svchost 1904 {TrkWks, WZCSVC, AeLookupSvc}
svchost 2884 {W3SVC}
svchost 3904 {TermService}
An Example of a PowerShell Function called Plist
When you declare a function it requires as a minimum: Function Name {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 {}.
Here is the Code for My Plist Function
# The Plist function identifies the individual process in svchost:
Function Plist([string]$name="*")
{
$Svc = Get-WmiObject Win32_Service | Sort ProcessId | Group ProcessId
$Process = @(Get-Process $name | sort Id)
$i=0
$j=0
while($i -lt $Process.count -And $j -lt $svc.count)
{
if($Process[$i].Id -lt $Svc[$j].Name)
{
$i++;
continue;
}
if($Process[$i].id -gt $svc[$j].Name)
{
$j++;
continue;
}
if($Process[$i].id -eq $svc[$j].Name)
{
$Process[$i]| Add-Member NoteProperty service $Svc[$j].group;
$i++;
$j++;
}
} # End of While
$Process;
} # End of Plist Function
Plist svchost* | Format-List 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
$pst[$i]| add-Member NoteProperty service $Svc[$j].group;
Plan B: 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 Plists([string]$a)
{
$FormatEnumerationLimit = 100
Gwmi win32_service |? {$_.PathName -Match ‘svchost’ -And $_.ProcessId -ne 0} | Group ProcessId | FT
} # End of Function
Plists
Guy Recommends: A Free Trial of the Network Performance Monitor (NPM)
v11.5
SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network. This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.
What I like best is the way NPM suggests solutions to network problems. Its also has the ability to monitor the health of individual VMware virtual machines. If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.
Download a free trial of Solarwinds’ Network Performance Monitor
Registry Information on SVCHOST
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.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost.
Another PowerShell Function Example: WMI Class SystemRestore
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
# Corrected by Jamie Lynch
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.Enable("C:\")}
}
} # End of function
GuyRestore -RestoreOpt disable -SysName 192.168.1.166
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 8 or Vista, and are not found on 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 8 or Vista machine is unlikely to have an IP address of 192.168.1.166. You could of course use the hostname.
Example:
GuyRestore -RestoreOpt enable -SysName MyWin7Computer
Guy Recommends: SolarWinds Engineer’s Toolset v10
This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems. Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.
There are so many good gadgets; it’s like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools. Try the SolarWinds Engineer’s Toolset now!
Download your fully functional trial copy of the Engineer’s Toolset v10
The Underling Windows Process
To inspect the underlying Windows processes launch the Task Manager. Now you can click on 'Image Name', then you can sort the processes into alphabetical order.
Get a Matching Listing with PowerShell's Get-Process
# PowerShell Get-Process list
Get-Process *
See another PowerShell function »
Summary of PowerShell Functions
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 Windows PowerShell Examples Functions
• Scripting PowerShell Function • PowerShell Create Shortcut • PowerShell Function Shortcut
• PowerShell Tutorials • PowerShell Temp • PowerShell Get-Item Env: • Clear-WinEvent Function
• Create PowerShell Function • PowerShell Examples • PowerShell Function Format DiskSize
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.