hash tables in powershell

前端 未结 3 448
清酒与你
清酒与你 2021-01-18 23:36

I\'m developing an application in PowerShell. I am storing variables in a hashtable. How can I keep the order in the hashtable? I want the order to be the same as I when I f

相关标签:
3条回答
  • 2021-01-19 00:20

    Hash tables by nature don't maintain the order of values. There are a few workarounds already out on the net. Check these

    http://www.tellingmachine.com/post/2009/01/When-PowerShell-hash-table-magic-backfires.aspx

    http://huddledmasses.org/powershell-and-hashtable-oddities/

    Or Try

    PS C:\WINDOWS\system32> $OrderedList = New-Object System.Collections.Specialized.OrderedDictionary
    PS C:\WINDOWS\system32> $OrderedList
    PS C:\WINDOWS\system32> $OrderedList.Add("Name","Ravi")
    PS C:\WINDOWS\system32> $OrderedList.Add("Age","30")
    PS C:\WINDOWS\system32> $OrderedList
    
    Name                           Value
    ----                           -----
    Name                           Ravi
    Age                            30
    
    0 讨论(0)
  • 2021-01-19 00:28

    PowerShell v3 will support ordered hashtables, using the [ordered] modifier. I suspect under the hood this is just a sortcut for using OrderedDictionary.

    General v3 features overview: http://blogs.technet.com/b/windowsserver/archive/2012/05/30/windows-server-2012-powershell-3-0-and-devops-part-2.aspx

    Specific illustration of using [ordered]: http://arcanecode.com/2012/06/04/powershell-v3-ordered-hashtables/

    0 讨论(0)
  • 2021-01-19 00:34

    Hashtables do not hold order. If you want order then what you want is a System.Collections.Specialized.OrderedDictionary.

    0 讨论(0)
提交回复
热议问题