Formatting PowerShell Get-Date inside string

datetime, formatting, powershell

Solution

"This is my string with date in specified format $($theDate.ToString('u'))"

or

"This is my string with date in specified format $(Get-Date -format 'u')"

The sub-expression (`$(...)`) can include arbitrary expressions calls.

Microsoft Documents both standard and custom `DateTime` format strings.

Problem

I can't get my head around how formatting a datetime variable inside a string works in PowerShell. ``` $startTime = Get-Date Write-Host "The script was started $startTime" # ...Do stuff... $endTime = Get-Date Write-Host "Done at $endTime. Time for the full run was: $( New-TimeSpan $startTime $endTime)." ``` gives me the US date format while I want ISO 8601. I could use ``` $(Get-Date -Format u) ``` but I want to use $endTime to make the calculation of the timespan correct. I have tried all permutations of `$`, `(`, `)`, `endTime`, `-format`, `u`, `.ToString(...)` and `.ToShortDate()`, but the one that works.

Original source