简体   繁体   中英

Date format when exported to CSV using Powershell

I Have a powershell script that executes a sql query, then exports the information to a CSV file. However the CSV file reformats all DateTimes entry to mm/d/yyyy hh:mm:ss . I need the entries to be in the format yyyy-mm-dd-hh.mm.ss.00

$SqlCmd.CommandText = $sqlSelectCVS
$SqlCmd.Connection = $SqlConnection
$SqlAdapter.SelectCommand = $SqlCmd
$SqlAdapter.Fill($export)

#Close the SQL connection
$SqlConnection.Close()

#Creates the New file with out Column header inforamtion
$export.tables[0] |export-csv -Path ($ExportTo + '\' + $ExportName) -notypeinformation 
(Get-Content ($ExportTo + '\' + $ExportName)| Select-Object -Skip 1) | Set-Content      ($ExportTo + '\' + $ExportName)

The database connections and query work just fine. Also as a side note Ive tried opening it in notepad with no luck and the date is a future date.. I am still very new to powershell so if you could explain any suggestions so i could understand it, i would appreciate it.

Thanks

You can use .NET libraries in PowerShell to format the string, like so:

"{0:yyyy-mm-dd-hh.hh.mm.ss.00}" -f [datetime]$stringOrWhateverDateVariable

$stringOrWhateverDateVariable would be the date variable from the SQL table.

I cannot test on an SQL datababe, but it works for strings to your DateTime format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM