2016-10-10 124 views
0

試圖簡化此代碼的顯而易見的原因..... 發現這個小snippit作爲一個開始,但我真的不知道如何將其納入更大的計劃。簡化PowerShell代碼

它基本上是一個電話簿CSV文件,我們需要分解成多個文件。下面的代碼的工作,但它的效率非常低:低於

[char[]](65..90) 

代碼:

GC C:\Users\x\documents\Telephonebook.csv | %{ 
if ($_.StartsWith("A")){ 
$_ | out-file -filepath c:\users\aricci\documents\A.asp -append 
} 

ElseIf ($_.StartsWith("B")){ 
$_ | out-file -filepath c:\users\aricci\documents\B.asp -append 
} 

ElseIf ($_.StartsWith("C")){ 
$_ | out-file -filepath c:\users\aricci\documents\C.asp -append 
} 

ElseIf ($_.StartsWith("D")){ 
$_ | out-file -filepath c:\users\aricci\documents\D.asp -append 
} 

ElseIf ($_.StartsWith("E")){ 
$_ | out-file -filepath c:\users\aricci\documents\E.asp -append 
} 

ElseIf ($_.StartsWith("F")){ 
$_ | out-file -filepath c:\users\aricci\documents\F.asp -append 
} 

ElseIf ($_.StartsWith("G")){ 
$_ | out-file -filepath c:\users\aricci\documents\G.asp -append 
} 

ElseIf ($_.StartsWith("H")){ 
$_ | out-file -filepath c:\users\aricci\documents\H.asp -append 
} 

ElseIf ($_.StartsWith("I")){ 
$_ | out-file -filepath c:\users\aricci\documents\I.asp -append 
} 

ElseIf ($_.StartsWith("J")){ 
$_ | out-file -filepath c:\users\aricci\documents\J.asp -append 
} 

ETC ....

回答

6

Martin的回答woul ð肯定工作,但如果你想軟化IO開銷,你可以按首字母使用Group-Object cmdlet來組中的條目,然後寫所有的人都對每個文件一次:

$Sets = Get-Content C:\Users\x\documents\Telephonebook.csv |Group-Object {$_[0]} 
foreach($Set in $Sets) { 
    $Set.Group |Out-File ("c:\users\aricci\documents\{0}.asp" -f $Set.Name[0]) 
} 

正如安斯加爾中指出注意,這種方法比使用流水線更耗費內存

+1

可能值得注意的是,對於非常大的文件,應避免使用此方法(文件不適合可用內存=>系統啓動交換=>操作減慢到爬行)。 –

2

下面將只使用第一個字符作爲文件名(注意這也可以是你可以使用過濾器排除的數字):

GC C:\Users\x\documents\Telephonebook.csv | % { 
    $_ | out-file -filepath ("c:\users\aricci\documents\{0}.asp" -f $_[0]) -append  
}