Output the date/time in PowerShell

一曲冷凌霜 提交于 2020-04-09 05:22:15

问题


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?


回答1:


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)"



回答2:


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


来源:https://stackoverflow.com/questions/38513806/output-the-date-time-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!