10

Add A Column To A CSV Using PowerShell

 3 years ago
source link: https://thomasrayner.ca/add-a-column-to-a-csv-using-powershell/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK