Thursday, September 25, 2008

Pipes, Loops, and Exploding Memory Usage

Background

Recently I wrote a script to automate some reports that are a huge pain.  I was pretty pleased with myself when I finished, but when I ran it, it kept going...and going...  It was taking a really long time, which might not have been strange because there was a lot of data, but I popped up my Task Manager, and that's when I noticed that powershell.exe was using up 1GB of RAM and climbing.  Clearly I had a problem with the design of the script, but what shocked me was that I was able to fix this  by replacing a foreach loop with a pipe to foreach-object, and the end result was that my powershell.exe process never uses more than 55MB of RAM.


Passing Objects Down the Pipe

One of the cool things about pipes is that as data is generated by a cmdlet or function it is passed down the pipe to the next one without having to wait for all of the data finish being generated. 

Consider the following:

C:\PowerShell> dir c:\ -include *.log -recurse | % {$_.FullName}

As each file is found that matches the pattern, it will be returned.  Now let's try it with a foreach loop:

foreach ($file in (dir c:\ -include *.log -recurse)) {
  $_.FullName
}

This time we have to wait for the entire hard drive to be scanned before the output comes out, and we'll use a lot more memory.  Why?   Because when you use parentheses, the expression between them is evaluated BEFORE the loop is processed.  This is essentially the same as the following:

$files = dir c:\ -include *.log -recurse

foreach ($file in $files) {
  $_.FullName
}

Most things you use PowerShell for probably won't be so large that this becomes a huge issue.  In my case I was querying Systems Management Server for inventory information on tens of thousands of computers, so it really started to impact the other things I was using.


Planning Ahead

As you're creating your scripts, try to be conscious of where you're using piped commands vs. loops, and consider how it would change your script if you refactored the code to do it a different way.  I tend to use loops more when I'm writing scripts because they are generally more readable and easier to update for the next poor sap who has to edit my code, but it's important no matter which way you choose to get the job done that you try to understand the flow of execution of your script.  

Some questions I try to ask myself when I think I'm done with my scripts:
  • Where am I causing my script to stop and collect all of the input pipeline before continuing?  (sorting in the middle of the pipeline is the classic example of this)  Does it matter?
  • What variables am I declaring at the top level that can be moved so that they are deleted automatically when they leave scope?
  • What is the impact on readability?

Sunday, September 21, 2008

I'm Not Dead

I've been really busy at work but keep an eye out for a real post very soon. If you want to check out some PowerShell scripts head on over to http://poshcode.org, where you can find PowerShell scripts submitted by users.

There has been talk in the community about trying to come up with a CPAN for PowerShell.  This is not it, but it's a start.  For one thing, CPAN grew enough that they could enforce readability and technique requirements by having someone actually review each module.  PowerShell is still too young for that.

I decided to post my SMS.psm1 module for making command-line managment of SMS easier, so here goes nothing.  I'll do a post on how to use it later.






Note:  You need PowerShell v2 CTP2 in order to use this.   Copy it into %userprofile%\Documents\WindowsPowerShell\Packages\SMS\.

Thursday, September 4, 2008

PowerShell Team Blog: Text Output Is Not a Contract


I just wanted to bring people's attention to this post from Jeffrey Snover, whose feet I am not worthy to wash with my perfume-soaked hair**.

It just reiterates the new mindset that Perlers and Pythonistas have to keep in mind when either transitioning to or assimilating with PowerShell topics.



** I know, too much information.

Monday, September 1, 2008

Putting the Fun in Functions

I just wanted to make a quick post to point out two neat features of functions that I left out of the last post since it was getting a little long, piping to functions, and autocomplete for functions.


AutoComplete for Cmdlets and Functions

You're probably used to using the TAB key to autocomplete file names, but have you noticed that you can autocomplete cmdlet and function names, too?  This comes in useful a lot since I don't have all of the standard cmdlets' names memorized yet.  Just start typing the name of a function or cmdlet and hit tab.  If the name that comes up isn't what you're looking for, just keep hitting TAB and you'll cycle through the available options.

For example:

PS C:\>  out-

Will give you, if you keep tabbing:
  • Out-Clipboard
  • Out-Default
  • Out-File
  • Out-GridView (super cool, I didn't know about this one)
  • Out-Host
  • Out-Null
  • Out-Printer
  • Out-String


Piping to Functions

Piping to functions is really easy.  Anything piped to a function is automatically added to an array called $input.  You can just add a loop in your function to cycle through the values in $input and voila!

Take the following example**:

# Get-Count()
# Gets the number of objects in the input pipeline.
#
# Returns:
#   An int with the count
#

function Get-Count () {
  $i = 0;

  foreach ($obj in $input) {
    $i++;
  }

  Write-Output $i
}


** "But Tojo," you're thinking, "Doesn't Measure-Object do the same thing?"  Indeed it does, but it's much slower in my experience because it also has a lot of extra bells and whistles that I don't need if I just want to see how many lines are in a file, etc.

Friday, August 29, 2008

Functions in PowerShell


What's a function?

A function is a script block with a name.  Most functions also take parameters and/or return a value, but that's not required.  The PSDrive called function: has a list of all defined functions, and there will be quite a few in there from the first time you install PowerShell.  You can use Get-Item (or gi, for short) cmdlet to get the Definition property of the function to see how they're made, as shown below.

Function Parameters and the param() Method

Let's make a test function and try this bad boy out.  I'm going to make a function that adds two numbers.  You can use the return statement to explicitly return a value, but any expression that is not assigned to a variable will be sent as output.

function Add-Numbers ($x, $y) {
  $x + $y
}

PS Function:\>  Add-Numbers 23 77
100

Okay, that worked, so let's look at the Definition property:

Function:\>  (gi Add-Numbers).Definition
param($x, $y) $x + $y

That's funny, I don't remember using the param() method in my function.

The param() method is implied when you put your parameters in parentheses before the script block.  This code would do the same thing:

function Add-Numbers {
  param($x, $y)
  $x + $y
}

Command-Line Switches and Named Parameters

So how do we set up named parameters?  We already did.  In PowerShell every variable name that you add to the param() method also is automatically created as a named parameter that you can use at the command-line.  Observe:

Function:\>  Add-Numbers -y 10 -x 20
30

Default Parameter Values

What if you have an optional variable?  Something that usually has the same value, that you'd rather not have to type in every time?   Easy.  Just assign it a value within the param method and you're done.  If you use the parameter when you call the function, then it will take on the value you assign, but if you don't, then it will keep the default value.

function Add-Numbers {
  param($x, $y=20)
  $x + $y
}

Function:\>  Add-Numbers 203
223

A Final Note about Parameters

There are two caveats when calling a function that you should be aware of:
  1. Unnamed parameters are assumed to be in the order that they were declared in param().  If you call Add-Numbers with only one number then it will be assigned to $x because that variable came first.  
  2. Any parameters left over after being assigned to parameters get dumped into an array called $args.

An Example Incorporating What We've Learned

# Get-SmsWmi
# A wrapper for Get-WmiObject that makes it easy to get objects from SMS.
#
# Args:
#   $Class: the WMI class to retrieve
#   $Filter: the where clause of the query
#   $Computername: the SMS server hosting the SMS Provider
#   $Site: the SMS Site Code of the target site
# Returns:
#   An array of WMI objects

function Get-SmsWmi {
  param([string]$Class = $(throw "ERROR: You must enter a class name.`n"), 
        [string]$Filter = $null, 
      [string]$ComputerName = 'sms-server', 
      [string]$Site = 'S00')
  
  [string]$query = "Select * from $Class"
  
  if ($Filter) {
    $query += " Where $Filter"
  }
  
  # Now that we have our parameters, let's execute the command.
  gwmi -ComputerName $ComputerName -Namespace ('root\sms\site_' + $Site) -Query $query
}

Get All Shared Printers with WMI and PowerShell

I whipped up this handy dandy script yesterday for work, and I think it makes a good simple example script, so I'm posting it here:

# Finds all servers that are hosting printers.
#
# Author: Tojo2000 
#
# Note: Requires a text file with one server per line named 'winserv.txt'.

$credential = Get-Credential
$servers = gc winserv.txt | sort

echo "ServerName`tShareName`tName`tDriverName`tStatus" > .\printers.txt

foreach ($server in $servers) {
  echo $server
  $ping = gwmi Win32_PingStatus -Filter "address = `"$server`""

  if ((!$ping.StatusCode) -and (!$ping.PrimaryAddressResolutionStatus)) {
    $printers = gwmi -Credential $credential -ComputerName $server -class Win32_Printer -Filter 'Shared = "True"'

    foreach ($printer in $printers) {
      if ($printer) {
        $output = $server, $printer.ShareName, $printer.Name, $printer.DriverName, $printer.Status
        echo ($output | Join-String2 "`t") >> .\printers.txt
      }
    }
  }
}

__________________________________________

# Join-String2
# Args:
#   $join_string: the string to paste between each element of the string array
#
# Returns:
#   The resulting string to the pipeline

function global:Join-String2 ([string]$join_string) {
  $output = '';
  $input_array = @($input);
  
  foreach ($string in $input_array[0..($input_array.Length - 2)]) {
    $output += $string;
  $output += $join_string;
  }
  $output += $input_array[-1];
  
  Write-Output $output;
}


There are a couple of things worthy of note here.  The Get-Credential cmdlet pops up a prompt to enter a username and password and stores it as a SecureString This is vastly more secure than storing the string in your script or typing it in to the console window.  Get-WMIObject, like many cmdlets, has a -Credential option that takes a credential as an input and runs the cmdlet under that account.  You can also specify a username here, and Get-Credential will be invoked to prompt you for the password.

The Join-String2 function is because there is already a cmdlet that is part of the PowerShell Comunity Extensions called Join-String, but apparently it freaks out if any of the values being printed are null, so I created a function that does a basic join.

The -Filter option of Get-WMIObject is basically just the "where clause" of the wmi query, which is to say that

gwmi Win32_Printer -Filter 'Shared = "True"'

is the same thing as

gwmi -Query 'Select * From Win32_Printer Where Shared = "True"'

It's just a lot more PowerShell-ish and a little less verbose.

Thursday, August 21, 2008

PowerShell and COM

I mentioned to a few people today that you can use PowerShell to create COM objects, but I think that warrants a little explaining.  VBScript automation examples use COM a lot, and if you're going to want to use PowerShell to automate Word documents or any of that other neat stuff, you'll need to use it as well.  

Consider the code below:

PS C:\> $sms_client = New-Object -COM 'CPApplet.CPAppletMgr'             #1
PS C:\> $sms_client | gm                                                 #2


   TypeName: System.__ComObject#{279463bb-1034-4fb5-878e-4a330a08beab}

Name                MemberType Definition
----                ---------- ----------
GetClientActions    Method     IClientActions GetClientActions ()
GetClientComponents Method     IClientComponents GetClientComponents ()
GetClientProperties Method     IClientProperties GetClientProperties ()

PS C:\> $actions = $sms_client.GetClientActions()                        #3
PS C:\> $actions | select Name                                           #4

Name
----
Software Inventory Collection Cycle
MSI Product Source Update Cycle
Hardware Inventory Collection Cycle
Standard File Collection Cycle
Discovery Data Collection Cycle
Request & Evaluate User Policy
Request & Evaluate Machine Policy
Software Metering Usage Report Cycle

PS C:\> $machine_policy = $actions | ?{$_.Name -like "*Machine Policy"}  #5
PS C:\> $machine_policy.PerformAction()                                  #6

In the code above, "CPApplet.CPappletMgr" is the name of the COM type that is equivalent tot he Systems Management applet in the control panel, so here's what the code does:

  1. Creates a new COM object of type 'CPApplet.CPAppletMgr'.  This is the equivalent of "sms_client = CreateObject('CPApplet.CPAppletMgr')" in VBScript.
  2. Runs Get-Member (gm) on the variable I just set to see what methods are available.
  3. Calls the GetClientActions method and stores the resulting array in $actions.
  4. Uses Select-Object (select) to get just the names of each action
  5. Uses Where-Object (?) to get just the action whose name is like "*Machine Policy" and assign it to $machine_policy
  6. Invokes the PerformAction() method of $machine_policy.

Worthy of note is that piping to where technically creates a one-element array, but PowerShell automatically converts that to a scalar by default, so I didn't have to use $machine_policy[0].  If I had actually wanted it to be treated as an array (let's say I'll be using the .Length() method of an array to see how many items were returned, I would have to use the @() syntax to force it:

PS C:\> $machine_policy = @($actions | ?{$_.Name -like "*Machine Policy"})