0

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!

2
  • 1
    Use ; in place of line breaks as a statement terminator. ... -as [datetime];$_ Commented Mar 3, 2022 at 13:08
  • $_.Time = is updating the object's Time property and produces no output, $_ after that assignment is needed to produce the output of the updated object. Commented Mar 3, 2022 at 13:11

1 Answer 1

2

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]; $_ }
Sign up to request clarification or add additional context in comments.

4 Comments

That answers one question, thanks! But why is it even neccessary to add $_ after the [datetime]? Why isn't { $_.Time = $_.Time -as [datetime] } just enough?
@IngovandenBersselaar Because you're just modifying the value of a property - why would that produce any output?
Ah, I think I get it, I figured if I modify the value I can call on it later and it accepts the value as a datetime format value, but adding the $_ afterwards does that part if I understand correctly.
No, $_ simply outputs the object that we received as input (and then modified). When you see a bare value expression like $_, PowerShell interprets it as Write-Output $_ - you're simply telling ForEach-Object: output the input object after modifying it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.