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

2019-09-11 16:36发布

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.

4条回答
姐就是有狂的资本
2楼-- · 2019-09-11 17:02

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"
查看更多
Evening l夕情丶
3楼-- · 2019-09-11 17:04

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楼-- · 2019-09-11 17:05

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
查看更多
Explosion°爆炸
5楼-- · 2019-09-11 17:11

I'd do it like this:

$CountHash += @{Total = $total}
查看更多
登录 后发表回答