How to add key/value pair at the end of hash table

2019-09-11 17:07发布

问题:

I am trying to calculate code count using PowerShell script.

I found a script on the Internet and am trying to add the total line at the end.

I have added the column

$CountHash.Add("Total", $Total)

at the end.

Param( [string]$path,
       [string]$outputFile,
       [string]$include = "*.*",
       [string]$exclude = "")

Clear-Host

$Files = Get-ChildItem -re -in $include -ex $exclude $path
$CountHash = @{}
$Total=0
Foreach ($File in $Files) {
    #Write-Host "Counting $File.FullName"
    $fileStats = Get-Content $File.FullName | Measure-Object -line
    $linesInFile = $fileStats.Lines
    $CountHash.Add($File.FullName, $linesInFile)

    $Total += $linesInFile
}

$CountHash.Add("Total", $Total)
$CountHash

But when I display $CountHash, it displays "Total" key in the middle. By adding Add at the end wouldn't ensure that it is added at the end.

How do I add the key/value pair at the end of the hash table?

I am exporting this hash table as CSV file, but the total lines are coming in the middle.

回答1:

Assuming the total is just for display, I guess there's no point in adding it to the hash set. Remove the line

$CountHash.Add("Total", $Total)

And add this as the last line:

Write-Host "Total: $Total"


回答2:

Hash tables don't maintain the order of their values. If you want a similar datastructure with order, try using System.Collection.Specialized.OrderedDictionary. Your example would then look like this

$Files=Get-ChildItem -re -in $include -ex $exclude $path
$CountHash= New-Object System.Collections.Specialized.OrderedDictionary # CHANGED
$Total=0
Foreach ($File in $Files) { 
   #Write-Host "Counting $File.FullName"
   $fileStats = Get-Content $File.FullName | Measure-Object -line
   $linesInFile = $fileStats.Lines
   $CountHash.Add($File.FullName,$linesInFile)

   $Total += $linesInFile
}

$CountHash.Add("Total",$Total)
$CountHash


回答3:

To answer your question, you can do that by using the Add method, as Kenned did, or by creating a new key by specifying it:

$CountHash.Total = $Total

But, I would have taken a simpler approach, custom objects instead of a hashtable:

Get-ChildItem -Path $path -Include $include -Exclude $exclude -Recurse |
Select-Object FullName, @{Name='LineCount';Expression={ (Get-Content $_.FullName | Measure-Object -Line).Lines}} |
Export-Csv .\files.csv


回答4:

I'd do it like this:

$CountHash += @{Total = $total}