I’ve just started working with Powershell recently and wanted to create a CSV file from scratch.
I thought it’d be as simple as piping a string to Export-CSV
, however Export-CSV
only takes objects.
This meant that I had to create my own objects to then dump into Export-CSV
.
This wasn’t immediately obvious to me initially, as I’ve little experience with Powershell, but since I’ve worked out how to do it, I’m going to document it here for reference.
$csvContents = @() # Create the empty array that will eventually be the CSV file
$row = New-Object System.Object # Create an object to append to the array
$row | Add-Member -MemberType NoteProperty -Name "User" -Value "John Doe" # create a property called User. This will be the User column
$row | Add-Member -MemberType NoteProperty -Name "UserID" -Value "JD01" # create a property called UserID. This will be the UserID column
$row | Add-Member -MemberType NoteProperty -Name "PC" -Value "PC01" # create a property called PC. This will be the PC column
$csvContents += $row # append the new data to the array
$csvContents | Export-CSV -Path C:\tmp\user.csv
The code above will result in the following output
#TYPE System.Object
"UserName","UserID","PC"
"John Doe","JD01","PC01"
How would you add more rows of data to this? Just curious.
All this code below is to create a row and add it to the array to then convert it to CSV.
$row = New-Object System.Object # Create an object to append to the array
$row | Add-Member -MemberType NoteProperty -Name "User" -Value "John Doe" # create a property called User. This will be the User column
$row | Add-Member -MemberType NoteProperty -Name "UserID" -Value "JD01" # create a property called UserID. This will be the UserID column
$row | Add-Member -MemberType NoteProperty -Name "PC" -Value "PC01" # create a property called PC. This will be the PC column
$csvContents += $row # append the new data to the array