Creating custom types in PowerShell, revisited for v2

In June, I blogged on creating custom types within PowerShell. In PowerShell v2, released with Windows 7 and Windows Server 2008 R2, things are a bit easier.

Now, the syntax for adding properties is far nicer, as you can pass a hashtable of values to add-member. Namely, the previous example of enumerating the applications run at startup could be more cleanly written as:

$runkey = Get-Item 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run'
$values = Get-ItemProperty $runkey.PSPath
foreach ($app in $runkey.Property) {
    $result = New-Object PSObject –prop @{ 
       Application = $app;
       Path = $values.$app
    }  
    Write-Output $result
}

Compared to the syntax of using separate add-member calls or even using the select-object shortcut as described earlier, this is much cleaner. Of course, it can also be compressed on a single line if so desired.

January 20, 2010 · Jouni Heikniemi · 3 Comments
Tags:  Â· Posted in: .NET

3 Responses

  1. Heikniemi Hardcoded » PowerShell: PSObject, custom types and the add-member cmdlet - January 20, 2010

    […] I’ll discuss some of the aspects involved in handling custom objects in PowerShell. Note: I have posted an update to this article regarding PowerShell v2, which cleans up the syntax described here. The theory […]

  2. Aleksandar - February 5, 2010

    # here is a slightly different way to create a hashtable with name/value pairs

    $ht = @{}
    $runkey = Get-Item 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run'

    $runkey.getvaluenames() | % {if ($_) {$ht.$_ = $runkey.getvalue($_)}}

    new-object psobject -property $ht

  3. Heikniemi Hardcoded » PowerShell Basics #4: Matching and capturing with regular expressions - February 13, 2010

    […] username and domain parts separately from the addresses. While you’re at it, you might as well construct some objects from the matches to get a cleaner view and help you manipulate the […]

Leave a Reply