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:
$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!
CodePudding user response:
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]; $_ }