PowerTip: Creating an Empty Hash Table

PowerTip: Creating an Empty Hash Table

  • Comments 7
  • Likes

Summary:  Learn to create a Windows PowerShell hash table.

Hey, Scripting Guy! Question How can I create an empty hash table?

Hey, Scripting Guy! Answer Use @{} and assign it to a variable:

            $hash = @{}

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • hi ed,

    here another variant:

    PS II> $ht=New-Object Hashtable

    PS II> $ht.GetType()

  • To create more than one:

    @{} | sv hash1,hash2,hash3,hash4

    Now you have 4 of them: $hash1, $hash2, $hash3, and $hash4.

  • Create and empty ordered hash table

    #requires -version 3

    $h=[ordered]@{}

  • @mjolinor & @Doug Finke

    ---> this is a great suggestion, thanks for sharing.

    I can not test with ps3, are that this works ?

    PS III> [ordered]@{} | sv hash1,hash2,hash3,hash

    sorry for my english

  • @Walid It does indeed.

    PS C:\> [ordered]@{}|sv hash1,hash2,has3,hash4

    PS C:\>

    PS C:\> $hash2.gettype()

    IsPublic IsSerial Name                                     BaseType

    -------- -------- ----                                     --------

    True     True     OrderedDictionary                        System.Object

    PS C:\>

  • Always, helpful.

  • Also folks, depending on your font, be careful about these 2 declarations:

    @()

    @{}

    I've just about torn my hair out on a script when I accidentally declared an array instead of a hashtable...