Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting CSV data to datetime format

I’m still learning Powershell and in order to complete an assignment I need to convert written data in CSV files to a powershell accepted datetime format.

The dates in the CSV format are written as: 1-1-2014.

In order to convert them I found out (through a bit of brute force) that I can use the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$Files = gci $Source\*.csv 

$Data = Import-CSV $Files -Delimiter ";"

$Data | ForEach-Object { $_.Time = $_.Time -as [datetime] 
$_ 
}

However, it would seem to me that this should work as well when written as follows:

$Data | ForEach-Object { $_.Time = $_.Time -as [datetime] $_ }

When I run it like that it returns a bunch of errors.

The $_ after [datetime] I also only added because a colleague used that in his functions, I don’t really understand why it has to be put there, and why it needs to be put on a new line. Could anyone explain? If there is a different/better way to convert CSV data to a datetime format I’d be interested in hearing those as well, thanks in advance!

>Solution :

The first (multi-line) version works because PowerShell interprets a line-break after a complete statement as a terminator – it knows that $_ is a separate statement from $_.Time = $_.Time -as [datetime].

To place multiple separate statements on a single line, you’ll have to use a semicolon ; to separate them:

$Data | ForEach-Object { $_.Time = $_.Time -as [datetime]; $_ }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading