This past week I needed to take a text file and append a piece of data to every record in the file. Of course, I knew that this was a prime target for PowerShell and just another reason why I needed to use this impressive tool. Before I went down that road, I first took the time to seriously think about all the ways that this simple task could be accomplished. I came up with several solutions within a few seconds. However, thinking through the process of how each solution would be implemented, none of those seemed quick enough or all needed another tool, development environment, etc. Enter PowerShell...
In my opinion the power behind PowerShell is truly the .Net framework. In this specific situation I needed to add a GUID to the end of each record. Knowing how to do this because of exposure to the .Net framework made this task even simpler. Now the only issues were to process the file, use the correct syntax to create the GUID and then write the file. Below is the source.
$filedata = get-content myinputfile.txt
foreach ($data in $filedata)
$data + "`t" + [System.Guid]::NewGuid().ToString() `
| Out-File "c:\myoutputfile.txt" -append
The first line of the script creates a collection of each record in the file. This is accomplished by the Get-Content call and storing the results into a variable.
The foreach is iterating through the filedata collection and for each item in that collection will create a object to store that record.
Take the contents in the data object and append a tab and then the generated GUID.
Append the results to a new file calling Out-File.
I look forward to other simple scripts that make tasks easier and/or faster to get to the desired result.