Looping through a hash, or using an array in PowerShell

后端 未结 7 1597
暗喜
暗喜 2020-12-22 21:13

I\'m using this (simplified) chunk of code to extract a set of tables from SQL Server with BCP.

$OutputDirectory = \"c:\\junk\\\"
$ServerOption =   \"-SServe         


        
相关标签:
7条回答
  • 2020-12-22 21:40

    I prefer this variant on the enumerator method with a pipeline, because you don't have to refer to the hash table in the foreach (tested in PowerShell 5):

    $hash = @{
        'a' = 3
        'b' = 2
        'c' = 1
    }
    $hash.getEnumerator() | foreach {
        Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
    }
    

    Output:

    Key = c and Value = 1
    Key = b and Value = 2
    Key = a and Value = 3
    

    Now, this has not been deliberately sorted on value, the enumerator simply returns the objects in reverse order.

    But since this is a pipeline, I now can sort the objects received from the enumerator on value:

    $hash.getEnumerator() | sort-object -Property value -Desc | foreach {
      Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
    }
    

    Output:

    Key = a and Value = 3
    Key = b and Value = 2
    Key = c and Value = 1
    
    0 讨论(0)
提交回复
热议问题