34

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?

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
ErocM
  • 4,505
  • 24
  • 94
  • 161

3 Answers3

48

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)"
briantist
  • 45,546
  • 6
  • 82
  • 127
10

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 Backups
22.07.2016 08:31:15 - Backups Completed
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
7

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 
HO LI Pin
  • 1,441
  • 13
  • 13