New-Object PSObject –Property [HashTable]

New-Object PSObject –Property [HashTable]

Rate This
  • Comments 24
Let me start of by suggesting you take a few minutes and read Laerte Junior’s excellent blog 
entry Exceptional PowerShell DBA Pt1 Orphaned Users. Laerte does a great job describing the
scenario, the approach he took to solving it and then he included the scripts! Really good
stuff Laerte!
When I looked at Laerte’s code, I recognized one of my least favorite PowerShell V1isms:
		$Object = New-Object PSObject                                       
               $Object | add-member Noteproperty LineNumber       $LineNumber                 
               $Object | add-member Noteproperty Date             $TodayDate              
               $Object | add-member Noteproperty ServerName       $svr            
               $Object | add-member Noteproperty DatabaseName     $Database            
               $Object | add-member Noteproperty UserName         $user.name            
               $Object | add-member Noteproperty CreateDate       $CreateDate            
               $Object | add-member Noteproperty DateLastModified $DateLastModified            
               $Object | add-member Noteproperty AsymMetricKey    $user.AsymMetricKey            
               $Object | add-member Noteproperty DefaultSchema    $user.DefaultSchema            
               $Object | add-member Noteproperty HasDBAccess      $user.HasDBAccess            
               $Object | add-member Noteproperty ID               $user.ID            
               $Object | add-member Noteproperty LoginType        $user.LoginType            
               $Object | add-member Noteproperty Login            $user.Login            
               $Object | add-member Noteproperty Orphan           ($user.Login -eq "")            
                                

Gosh that is a horrible looking thing.  This is one of the things we fixed with PowerShell V2 so you take a few minutes to
learn this so you never have to do that mess again.  Let’s get some help:

PS> Get-Help New-Object -Parameter Property

-Property <hashtable>
    Sets property values and invokes methods of the new object.
    Enter a hash table in which the keys are the names of properties or methods and the values are property value
    s or method arguments. New-Object creates the object and sets each property value and invokes each method in
    the order that they appear in the hash table.
    If the new object is derived from the PSObject class, and you specify a property that does not exist on the o
    bject, New-Object adds the specified property to the object as a NoteProperty. If the object is not a PSObjec
    t, the command generates a non-terminating error.
    Required?                    false
    Position?                    named
    Default value               
    Accept pipeline input?       false
    Accept wildcard characters?  false

 

Thats right – you can now specify a hashtable and we’ll set these as NoteProperties on an object.  What that means is that you can now write code like this:

    $Object = New-Object PSObject -Property @{            
        LineNumber       = $LineNumber                 
        Date             = $TodayDate              
        ServerName       = $svr            
        DatabaseName     = $Database            
        UserName         = $user.name            
        CreateDate       = $CreateDate            
        DateLastModified = $DateLastModified            
        AsymMetricKey    = $user.AsymMetricKey            
        DefaultSchema    = $user.DefaultSchema            
        HasDBAccess      = $user.HasDBAccess            
        ID               = $user.ID            
        LoginType        = $user.LoginType            
        Login            = $user.Login            
        Orphan           = ($user.Login -eq "")            
    }                           
                                    

or if you prefer:

   $hash = @{            
        LineNumber       = $LineNumber                 
        Date             = $TodayDate              
        ServerName       = $svr            
        DatabaseName     = $Database            
        UserName         = $user.name            
        CreateDate       = $CreateDate            
        DateLastModified = $DateLastModified            
        AsymMetricKey    = $user.AsymMetricKey            
        DefaultSchema    = $user.DefaultSchema            
        HasDBAccess      = $user.HasDBAccess            
        ID               = $user.ID            
        LoginType        = $user.LoginType            
        Login            = $user.Login            
        Orphan           = ($user.Login -eq "")            
    }                           
                                    
    $Object = New-Object PSObject -Property $hash            

 

This is SO much better than V1 – be sure to use it and to tell all your friends about it as well! 

Experiment!  Enjoy!  Engage!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Leave a Comment
  • Please add 2 and 8 and type the answer here:
  • Post
  • Thanks for the tip, this have made me already changing my scripts!! Thanks again.

  • Great blog i like to read this blog daily it has all the useful stuff, i would like to subscribe it so can you please tell me when your blog gets updated.

  • What a great tip

  • I suggest considering a data table in Powershell, as it does retain the order in which the properties are added, and it is truly a data table versus a hash table.

  • Thanks for the comments. I have a question here,

    How do I create an object that inherits properties/methods of a super-class ?

  • Hi Gurus,

    I have created a custom object using this method,

    $object = New-Object Object |            

       Add-Member NoteProperty MyField 5 -PassThru |            

       Add-Member ScriptMethod xTimesMyField {            

           param($x)            

           $x * $this.MyField            

           } -PassThru            

    $object            

    $object.xTimesMyField(10)  

    Now I want to create another object that inherits the properties and methods of this object. How do I do that ?

  • Hi,

    This is a very nice post.

    Thanks for sharing...

    Aman

    http://www.amandhally.net/

  • Hi what's the difference for this custom array objects:

    $Objects = @(

       $(New-Object PSObject -Property @{

           Name = "Objekt1"

           Value = "value1","value2"

       }),

       $(New-Object PSObject -Property @{

           Name = "Objekt2"

           Value = "value1","value2"

       })

    )

    $Objects2 = @(

        @{

           Name = "Objekt3"

           Value = "value1","value2"

       },

        @{

           Name = "Objekt4"

           Value = "value1","value2"

       }

    )

  • Great simple post

Page 2 of 2 (24 items) 12