2012-08-08 67 views
0

我想使用powershell腳本來計算代碼計數。如何在哈希表的末尾添加鍵/值對?

我在網絡中發現了一個腳本,並試圖在最後添加總行。

我已經添加了列

$ CountHash.Add( 「合計」,$總計)

末。

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

Clear-Host 

$Files=Get-ChildItem -re -in $include -ex $exclude $path 
[email protected]{} 
$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 

但是,當我顯示$ CountHash,它顯示在中間的「總計」鍵。通過在最後添加Add不能確保它在最後添加。

如何在哈希表的末尾添加鍵/值對?

更新:我將這個哈希表導出爲csv文件,但總行數在中間。

回答

3

假設總數只是用於顯示,我想沒有必要將它添加到哈希集。 刪除行

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

,並添加爲最後一行

Write-Host "Total: $Total" 
+0

我已更新我的問題。對不起,我不只是顯示它 – Samselvaprabu 2012-08-08 10:24:57

1

要回答你的問題,你可以通過使用Add方法,如@Kenned做,或創建一個新的鍵指定它:

$CountHash.Total = $Total 

但是,我會採取一個更簡單的方法,自定義對象,而不是哈希表。

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 
0

我會做這樣的:

$ CountHash + = @ {總= $總}

1

哈希表不維護他們的價值觀的順序。如果您想要訂購類似的數據結構,請嘗試使用System.Collection.Specialized.OrderedDictionary。你的例子會看起來像這樣

$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 
相關問題