0

In PowerShell, I can use Expanding strings to insert variable values into strings (Answer with more details about that):

PS C:\> $UtcNow = [DateTime]::UtcNow
PS C:\> "UtcNow = $UtcNow"
UtcNow = 08/10/2020 09:31:51

I can do it less conveniently using String.Format or the -f operator, and then I can provide format specifiers:

PS C:\> "UtcNow = {0:u}" -f $UtcNow
UtcNow = 2020-08-10 09:31:51Z

PS C:\> [string]::Format("UtcNow = {0:u}", $UtcNow)
UtcNow = 2020-08-10 09:31:51Z

Question: Is there a way to use a format specifier in and expanding string?

What I've tried

PS C:\> "UtcNow = $UtcNow:u"   # Doesn't work
UtcNow = 

PS C:\> "UtcNow = ${UtcNow:u}"   # Doesn't work
UtcNow = 

PS C:\> "UtcNow = $($UtcNow.ToString("u"))"  # Works, but is quite cumbersome
UtcNow = 2020-08-10 09:31:51Z
Jonathan
  • 6,939
  • 4
  • 44
  • 61
  • You can probably just change your culture settings of the session if you want it in the same format for the whole session. Then you dont need to bother about the format later on in your script. – Daniel Björk Aug 10 '20 at 09:47
  • Have a look at this one: https://devblogs.microsoft.com/scripting/use-culture-information-in-powershell-to-format-dates/ – Daniel Björk Aug 10 '20 at 09:50
  • @DanielBjörk: Interesting... But doesn't work, since PowerShell always uses Invariant culture for expanding string - see [this answer](https://stackoverflow.com/a/37603732) linked from the answer in the OP. – Jonathan Aug 10 '20 at 10:31

1 Answers1

0

No, expandable strings in PowerShell don't evaluate format specifiers

-f is the way to go :)

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206