views:

634

answers:

3

Hi,

So I can format the Get-Date commandlette no problem like this:

$date = Get-Date -format "yyyyMMdd"

but once I've got a date in a variable, how do I format it. This errors:

$dateStr = $date -format "yyyMMdd"

saying:

"You must provide a value expression on the right-hand side of the '-f' operator"

+2  A: 

One thing you could do is:

$date.ToString("yyyMMdd")
John Weldon
Thanks I did this - bugs me that -format doesn't work though.
Ev
Ya, @Josh Einstein's solution is right on the money :)
John Weldon
+2  A: 

Same as you would in .NET.

$DateStr = $Date.ToString("yyyyMMdd")

or

$DateStr = '{0:yyyyMMdd}' -f $Date
Josh Einstein
Thanks for the -f answer mate!
Ev
+1  A: 

The question is answered, but there is some more info missing:

Variable vs. Cmdlet

You have a value in $Date variable and -f operator does work in this form: 'format string' -f values. If you call Get-Date -format "yyyyMMdd" you call a command let with some parameters. The value "yyyyMMdd" is value for parameter Format (try help Get-Date -param Format).

-f operator

There is plenty of format strings, look at least at part1 and part2. She uses string.Format('format string', values'). Think of it as 'format-string' -f values, because -f operator works very similarly as string.Format method (although there are some differences (for more info look at question at StackOverflow: how exactly does the RHS of the -f operator work?

stej
Thanks a lot for the info.
Ev