I have a PowerShell script I run on a regular basis. Part of the script creates csv files that I later use to import data into various software programs.
The data is in a variable $enrolledStudents and the type is a System.Array
I use the following to export part of the data:
$enrolledStudents | Select-Object @{Name="SFIRST";Expression={$_.FirstName}},`
@{Name="SLAST";Expression={$_.LastName}},`
@{Name="SGRADE";Expression={[int]$_.GradeLevel}},`
@{Name="SBIRTHDAY";Expression={$_.Birthdate }} |
Export-CSV C:\temp\Exported.csv -notype -Append
The Export looks like:
"SFIRST","SLAST","SGRADE","SBIRTHDAY"
"John","Doe","6","2009-11-22"
The software I upload the data to needs the date formatted as “11/22/2009” so it would look like:
"SFIRST","SLAST","SGRADE","SBIRTHDAY"
"John","Doe","6","11/22/2009"
Is there a way to do this in the Select-Object ?
CodePudding user response:
Sure thing. Just apply a little object typing magic...
$enrolledStudents | Select-Object `
@{Name="SFIRST";Expression={$_.FirstName}},`
@{Name="SLAST";Expression={$_.LastName}},`
@{Name="SGRADE";Expression={[int]$_.GradeLevel}},`
@{Name="SBIRTHDAY";Expression={([datetime]$_.Birthdate).ToString('MM/dd/yyyy')}} |
Export-CSV C:\temp\Exported.csv -notype -Append
Edit: Corrected the date format syntax
CodePudding user response:
I now have two working solutions and wanted to add a note. Both give the same output.
# Thanks mclayton
$enrolledStudents | Select-Object @{Name="SFIRST";Expression={$_.FirstName}},`
@{Name="SLAST";Expression={$_.LastName}},`
@{Name="SGRADE";Expression={[int]$_.GradeLevel}},`
@{Name="SBIRTHDAY";Expression={ "{1}/{2}/{0}" -f $_.Birthdate.split("-")}} |
Export-CSV C:\temp\test-Renaissance.csv -notype -Append
and
# Thanks Dennis
$enrolledStudents | Select-Object @{Name="SFIRST";Expression={$_.FirstName}},`
@{Name="SLAST";Expression={$_.LastName}},`
@{Name="SGRADE";Expression={[int]$_.GradeLevel}},`
@{Name="SBIRTHDAY";Expression={([DateTime]$_.Birthdate).ToString('MM/dd/yyyy')}} |
Export-CSV C:\temp\test-Renaissance.csv -notype -Append
I will use the second because for me, it is easier to read.
In my case it is very Important to have the [DateTime]$__.Birthdate. I found numerous examples using the .ToString but did not come across one that used the [datetime]$_