powershellexport-csvselect-object

Is it possible to change the date format while exporting to CSV in PowerShell


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 ?


Solution

  • 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