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