Showing posts with label CSV. Show all posts
Showing posts with label CSV. Show all posts

Thursday, January 26, 2017

Getting rid of trailing spaces in CSV's with Powershell

There I was, banging my head against the table because I thought I was perfectly able to select stuff from a CSV file, but I could not figure out why my selections weren't showing the stuff I wanted. It turns out my CSV file entries were full of trailing spaces!

Googling around, I saw this in a forumpost somewhere, but to prevent me from losing it, I've put the script below:

$CSV = import-csv  'C:\scripts\trailingspaces.csv'
        $CSV | Foreach-Object {  
            $_.PSObject.Properties | Foreach-Object { $_.Value = $_.Value.Trim() }
        }

$CSV | ConvertTo-Csv -UseCulture -NoTypeInformation | Out-File 'C:\scripts\trimmed.csv'

Yeay, no more going mad!

Tuesday, June 9, 2015

Reading in a CSV file in Powershell

CSV files make my life a whole lot easier, especially with large numbers. If you have an excel file with a hostname and an IP address, you get a csvfile like:

Server,IPAddress
server1,192.168.1.10
server2,192.168.1.11


You can import it with the following statement:

$csvfile = Import-Csv C:\Book2.csv

foreach ($value in $csvfile){

$hostname = $value.server

$IP = $value.IPAddress

Write-Host "do whatever here to $hostname with IP address: $IP"

}