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


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]$include = "*.*",
       [string]$exclude = "")


$Files = Get-ChildItem -re -in $include -ex $exclude $path
$CountHash = @{}
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)

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 Answers: 

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"

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
Foreach ($File in $Files) { 
   #Write-Host "Counting $File.FullName"
   $fileStats = Get-Content $File.FullName | Measure-Object -line
   $linesInFile = $fileStats.Lines

   $Total += $linesInFile


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

I'd do it like this:

$CountHash += @{Total = $total}

More Articles

android - Mock Location permission issue on release app

I developed Fake GPS application and all my codes work nicely on debug mode.When i try "mock location" on **release version**, i got this error;java.lang.SecurityException: Requires `ACCESS_MOCK_LOCATION` permissionI already had ACCESS_MOCK_LOCATION in debug/AndroidManifest file.<uses-permission

android - Why getLastKnownLocation(provider) doesn't return null after clearTestProviderLocation(provider)

I was assuming that getLastKnownLocation does return null for a given provider after calling clearTestProviderLocation for same provider.Why ? because documentation says for clearTestProviderLocation; Removes any mock location associated with the given provider.public void test() throws SecurityExc

php - Key for HMAC Algorithm

How to generate the secret key for the HMAC algorithm as I have to use it for data verification at the other clients end?Thanks in advance.

How do I cross-compile a Linux kernel to a MIPS little endian host?

The kernel in question is 2.6.18. If I callmake ARCH=mips CROSS_COMPILE=mipsel-linux- menuconfigthere will be only the option to build a big endian kernel in the menu. If I use ARCH=mipsel, it will complain about not having an arch/mipsel dir.How's this done?

android - Can't find class [org/drinkless/td/libcore/telegram/TdApi$Object]

I am getting this error "Can't find class [org/drinkless/td/libcore/telegram/TdApi$Object]" but I haven't used this class anywhere in my project.I haven't used that class anywhere.But i am getting the above errorCan anyone please let me know how to solve the above error.

.net - HMACSHA256.ComputeHash - Unexpected Result

I'm trying to generate a signature in VB.NET using the following vendor documentation as a reference guide:https://shuttle.support.signiant.com/customer/en/portal/articles/2807676-media-shuttle-metadata-developer-s-guide#AppendixAThey also provide this sample JS code:https://github.com/Signiant/medi

r - adding two column of a data where col1 contains date and col2 contains days

I have a data frame in which i have two columns date and days and i want to add date column with days and show the result in other column data frame-1col date is in format of mm/dd/yyyy formatdate days3/2/2019 83/5/2019 43/6/2019 43/21/2019 33/25/2019 7and i want my output like t

parsing - How to parse an array of json object using jq

I need to parse a Json file which have a lot of arrays. This is the json source:{"iabVersion": "IAB_V2","categories": [{ "categories": [{ "categories": [{ "id": "1.1.1", "name": "Commercial Trucks" }, { "id": "1.1.2", "name": "Conve

android - Exception while instantiating MockRunner- [NoSuchMethodError] [Kotlin]

I have created a library for distribution the network requests amongst different clients. I am using OkHttp3 in one of the clients. For testing my library, I am trying to mock the response using the okhttp3.mockwebserver. The way I am trying to set up my mock web server is as follows:val server = Mo

C++/C#/Java video analysis question

Could someone give references / frameworks, which allow to do something like Microsoft Kinect does, but using only one video stream?I would like to see algorithm abstracts and papers if there are some (I hope there are).If somebody had practical experience of using them, please share it :)