Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PowerShell中输出日期/时间_Powershell_Powershell 4.0 - Fatal编程技术网

在PowerShell中输出日期/时间

在PowerShell中输出日期/时间,powershell,powershell-4.0,Powershell,Powershell 4.0,我想在脚本中的不同位置输出日期和时间,以便进行日志记录,因此我正在执行以下操作: $b = Get-Date Write-Output "Backups complete at $b" # more code here $c = Get-Date Write-Output "Backups complete at $c" 我必须使用字母表中的多个字母来获取最新的日期/时间 是否有更简单的方法来执行此操作,或者每次我想再次使用时都必须重新建立日期?将当前日期时间分配给变量后,您将在运行“获取

我想在脚本中的不同位置输出日期和时间,以便进行日志记录,因此我正在执行以下操作:

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

# more code here

$c = Get-Date
Write-Output "Backups complete at $c"
我必须使用字母表中的多个字母来获取最新的日期/时间


是否有更简单的方法来执行此操作,或者每次我想再次使用时都必须重新建立日期?

将当前日期时间分配给变量后,您将在运行“获取日期”时捕获日期和时间

每次需要新的日期和时间时,都需要再次运行它。您可以避免使用变量:

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

另一种方法是使用格式字符串,由于您将其用于日志记录,我建议您编写一个函数,因为这将允许您在单个位置更改所有日志消息的格式:

function Log-Message
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [string]$LogMessage
    )

    Write-Output ("{0} - {1}" -f (Get-Date), $LogMessage)
}
现在,您可以使用以下方法进行简单的日志记录:

Log-Message "Starting Backups"
Log-Message "Backups Completed"
输出:

22.07.2016 08:31:15 - Starting Backups
22.07.2016 08:31:15 - Backups Completed

下面是一个简单的1,它允许你按照你想要的格式格式化日期和时间

$currentTime = Get-Date -format "dd-MMM-yyyy HH:mm:ss"
Write-Host $currentTime " Other log string message "
输出

17-Aug-2020 10:06:19  other log string message 

好的,我在没有()的情况下试过了,但没用。我现在明白了。非常感谢。cough使日期可按年-月-日-小时-分钟-秒顺序排序
Write Output“备份以$(Get Date-Format u)完成”
cough您应该使用写入信息而不是写入输出