Add A Column To A CSV Using PowerShell

Say you have a CSV file full of awesome, super great, amazing information. It’s perfect, except it’s missing a column. Luckily, you can use Select-Object along with the other CSV cmdlets to add a column.

In our example, let’s say that you have a CSV with two columns “ComputerName” and “IPAddress” and you want to add a column for “Port3389Open” to see if the port for RDP is open or not. It’s only a few lines of code from being done.

PS> $servers = Import-Csv C:\Temp\demo\servers.csv

PS> $servers

Name     IPAddress
----     ---------
server01 10.1.2.10
server02 10.1.2.11

Now, let’s borrow some code from my post on calculated properties in PowerShell to help us add this column and my post on seeing if a port is open using PowerShell to populate the data.

PS> $servers = $servers | Select-Object -Property *, @{label = 'Port3389Open'; expression = {(Test-NetConnection -ComputerName $_.Name -Port 3389).TcpTestSucceeded}}

You can run $servers to see the if the new data shows up correctly (spoiler alert, it did), and then use Export-Csv to put the data into the same, or a new CSV file.

PS> $servers | Export-Csv -Path c:\temp\demo\servers-and-port-data.csv -NoTypeInformation

Use the -Force flag if you’re overwriting an existing CSV.

Written on August 9, 2017