Output the date/time in PowerShell

ErocM picture ErocM · Jul 21, 2016 · Viewed 45.6k times · Source

I want to output the date time in various places in my script for logging so I am doing this:

$b = Get-Date
Write-Output "Backups complete at $b"

# more code here

$c = Get-Date
Write-Output "Backups complete at $c"

I am having to use multiple letters of the alphabet to get the most current date/time.

Is there an easier way of doing this or do I have to reestablish the date each time I want to use it again?

Answer

briantist picture briantist · Jul 21, 2016

Once you assign the current datetime to a variable, you are capturing the date and time at the moment you ran Get-Date.

Every time you want a new date and time, you need to run it again. You could avoid using a variable:

Write-Output "Backups complete at $(Get-Date)"