Monday, February 11, 2013

Powershell Script DIY: Adding a line at the begining of a file


Today we are going to add a header to our file, foo.txt.  This can be useful for adding a header to a CSV file, or just adding a title to your output for easy reference.  Whatever your reasons you always need to start by Setting your location and defining variables:

Set-Location “C:\Temp

$fooaltered = “fooaltered.txt
$H = "the title is foo"
$I = Get-Content “foo.txt”

Notice the Get-Content command in the definition for $I?  This is necessary to grab the contents of foo.txt and not the actual file itself.  Remember, you must encapsulate the actual object or value in quotations, but any command prior to that does not get the quotes.
Next we need to use the Set-content command

Set-Content

We tell powershell what variable we want to set the content to:

Set-Content $fooaltered

And we use the nifty –value switch to tell powershell that we are adding more than just one set of data:

Set-content $fooaltered –value

Now we use the variables $H and $I that we defined earlier to define the content of fooaltered.txt.  It is important to note that when using multiple values in this manner you need to separate them with a comma and a space:

Set-Content $fooaltered –value $H, $I

If you want to limit the size of your file to a certain number of lines, you can use the [x…y] definition where x and y are line numbers.  This is useful if you need to keep the file a certain size, or number of lines:

Set-Content $fooaltered -value $H, $I[0..5000]

Your end result should be:

Set-Location “C:\Temp

$foo = "foo.txt"
$fooaltered = “fooaltered.txt
$H = "the title is foo"
$I = Get-Content $foo
Set-Content $fooaltered -value $H, $I[0..5000]

As always if you have a correction or something to add, Please feel free to post below!

No comments:

Post a Comment