Generating files with PowerShell

Link. April 9, 2008. Comments [0]. Posted in: PowerShell

Yesterday I needed to generate a bunch of small files to use as input for testing, as I needed to reproduce a bug I was tracking down. More to the point, I needed to generate 2000 files of size 781 bytes.

Update: I screwed up the code snippets on my first attempt. Fixed now!

Naturally, I turned to PowerShell and whipped this script:

$fc = new-object string ('a', 781)
1..2000 | %{ [io.file]::WriteAllText("$(pwd)\$_.txt", $fc) }

Is this the only way to do it? Certainly no, but a couple of things are worth mentioning about my specific solution. A savvy reader might ask: Why didn't you just use the redirection operator instead?

1..2000 | %{ $fc > "$_.txt" }

That is indeed shorter, but has one major drawback for my problem: The redirection operator when writing to files defaults to using UTF-16LE encoding, which meant my files would come out the wrong size.

Now, the redirection operator in this case is nothing more than a way to implicitly call the out-file cmdlet, which does provide a way to select the encoding:

1..2000 | %{ $fc | out-file "$_.txt" -enc ascii }

This is much better,  but, unfortunately, still screws up the file size because it will add a CR LF pair at the end. And it isn't remarkably shorter than my original solution using File::WriteAllText().



Comments are closed.

About

Tomas Restrepo is co-founder of devdeo. His interests include .NET, Connected Systems, PowerShell and, lately, dynamic programming languages. More...

email: tomas@winterdom.com
msn: tomasr@passport.com
twitter: tomas_restrepo

Technorati Profile

devdeo logo

View my profile on LinkedIn

MVP logo

Syndicate

Ads


Links

Categories

Statistics

Total Posts: 1006
This Year: 76
This Month: 7
This Week: 0
Comments: 771

Blogroll

Post Archive

Other

Copyright © 2002-2008, Tomas Restrepo.

Powered by: newtelligence dasBlog 1.9.7174.0

Sign In