PowerShell


Scripting PowerShell Functions

Introduction to Scripting PowerShell Function

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.

PowerShell Function Topics

 ♣

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 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: 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 {}.

Here is the code for the plist function

function plist([string]$name="*")
{

$Svc = get-wmiobject win32_service | sort ProcessId | group-Object ProcessId
$ps = @(get-Process $name | sort Id)
$i=0
$j=0
while($i -lt $ps.count -and $j -lt $svc.count)
   {

   if($ps[$i].Id -lt $Svc[$j].Name)
  {

   $i++;
   continue;
   }
   if($ps[$i].id -gt $svc[$j].Name)
   {
   $j++;
   continue;
   }
   if($ps[$i].id -eq $svc[$j].Name)
   {
   $ps[$i]| add-Member NoteProperty service $Svc[$j].group;
   $i++;
   $j++;
  }
  }
$ps;
}
 

# 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 Engineer's Toolset v10Engineer's Toolset v10

The Engineer's Toolset v10 provides a comprehensive console of utilities for troubleshooting computer problems.  Guy says it helps me monitor what's occurring on the network, and the tools teaches me more about how the system literally operates.

There are so many good gadgets, it's like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.  Download your copy of the Engineer's Toolset v 10

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.

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.

See more PowerShell examples for syntax advice

PowerShell Home  • Syntax  • -f format  • Pipeline  • Quotes  • Format-table  • Group  • Select-String

Please write in if you see errors of any kind.  Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Google

Web  This website

Review of Orion NPMGuy Recommends: Orion's NPM - Network Performance Monitor

Orion's performance monitor is designed for detecting network outages. A network-centric view make it easy to see what's working, and what needs your attention.

This utility guides you through troubleshooting by indicating whether the root cause is faulty equipment or resource overload.

Download a free trial of the Network Performance Monitor

 

Home Copyright © 1999-2010 Computer Performance LTD All rights reserved

Please report a broken link, or an error.