0

Trying to simplify this code for obvious reasons..... found this little snippit as a start, but I'm not really sure how to incorporate it into the larger scheme.

It's basically a phonebook CSV file that we need broken out into multiple files. The code below does work but it's very inefficient:

[char[]](65..90)

Code below:

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....

2 Answers 2

6

Martin's answer would definitely work, but if you want to soften the IO overhead, you could use the Group-Object cmdlet to group the entries by first letter and then write all of them to each file once:

$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]) 
}

As Ansgar points out in the comments, this approach is more memory intensive than just using the pipeline

Sign up to request clarification or add additional context in comments.

1 Comment

Might be worth noting that this approach should be avoided for very large files, though (file doesn't fit in the available memory => system starts swapping => operation slows to a crawl).
2

The following will just use the first character as the filename (be aware that this could also be a number which you can exclude using a filter):

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.