Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output the date/time in PowerShell

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?

like image 235
ErocM Avatar asked Jul 21 '16 20:07

ErocM


People also ask

How do I show date and time in PowerShell?

Get-Date uses the UFormat parameter with format specifiers to display the current system date and time. The format specifier %Z represents the UTC offset of -07. The $Time variable stores the current system date and time. $Time uses the ToUniversalTime() method to convert the time based on the computer's UTC offset.

How do you call a date in PowerShell?

Utilize the “AddDays()” function and specify “-1” as a parameter for this function. Calling the “AddDays()” function with these specified settings will let you display Yesterday's date in your PowerShell.


3 Answers

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)"
like image 73
briantist Avatar answered Oct 12 '22 02:10

briantist


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
like image 23
Martin Brandl Avatar answered Oct 12 '22 04:10

Martin Brandl


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 
like image 5
HO LI Pin Avatar answered Oct 12 '22 04:10

HO LI Pin