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.
Assuming the total is just for display, I guess there's no point in adding it to the hash set. Remove the line
And add this as the last line:
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:
But, I would have taken a simpler approach, custom objects instead of a hashtable:
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 thisI'd do it like this: