Output the date/time in PowerShell
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)"
Another way to do this is using a format string and since you are using this for logging purpose I would recommend you to write a function because this will allow you to change the format of all log messages in a single place:
function Log-Message{ [CmdletBinding()] Param ( [Parameter(Mandatory=$true, Position=0)] [string]$LogMessage ) Write-Output ("{0} - {1}" -f (Get-Date), $LogMessage)}
Now you can simple log using:
Log-Message "Starting Backups"Log-Message "Backups Completed"
Output:
22.07.2016 08:31:15 - Starting Backups22.07.2016 08:31:15 - Backups Completed
Here is simple 1 which allow you format date time in your desire format
$currentTime = Get-Date -format "dd-MMM-yyyy HH:mm:ss"Write-Host $currentTime " Other log string message "
OUTPUT
17-Aug-2020 10:06:19 other log string message