Wednesday, August 5, 2009

Removing Header/Footer lines from CSV files

I was recently tasked with scheduling a script to read in a TSM.out file and create a usable CSV file from it. The TSM *.out file has at least 9 header lines that are not relevant to the end file as well as some extra footer lines. I also noticed that the column headers are not descriptive either. So, to automate the file transformation, we look to PowerShell!
function Create-CSV {
param( [int]$HeaderLines,
[int]$FooterLines,
[string]$SourceFilePath,
[string]$DestinationFilePath,
[string]$NewColumnNames )

if(Test-Path -literalPath $SourceFilePath) {
$a = Get-Content -path $SourceFilePath
if ($NewColumnNames -ne $null) {
Add-Content -path $DestinationFilePath `
-value $NewColumnNames
}
# Grab only the lines we need
$a[$HeaderLines..($a.count - $FooterLines)] | `
foreach{Add-Content -path $DestinationFilePath -value $_}
}
else {
Write-Error "$SourceFilePath does not exist."
}
} # End of function

Create-CSV -HeaderLines 9 `
-FooterLines 4 `
-SourceFilePath 'c:\temp\test.out' `
-DestinationFilePath 'c:\temp\test.csv' `
-NewColumnNames "Nodename,hostname,tcpipaddress"

Enjoy!

No comments: