带时间戳的错误日志

时间:2019-06-27 15:42:37

标签: powershell

我很难在此简单命令中添加时间戳。无论如何,我可以在错误之前或之后添加时间戳?我还想添加其他脚本,如果可以做到的话,时间戳会很有帮助。

Rename-Item C:\Windows\SoftwareDistribution\Download Download.old -Confirm:$false -Verbose -ErrorAction Continue *>> c:\temp\verbose.txt

项目不存在时的结果是:

    Performing the operation "Rename Directory" on target "Item: C:\Windows\SoftwareDistribution\Download Destination: C:\Windows\SoftwareDistribution\Download.old".
    Rename-Item : Cannot rename because item at 'C:\Windows\SoftwareDistribution\Download' does not exist.
    At line:1 char:1

+ Rename-Item C:\Windows\SoftwareDistribution\Download Download.old -Co ...

1 个答案:

答案 0 :(得分:0)

您可以使用日志功能:

function Write-Log
{
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [String] $Message 
    )

    process
    {
        $logMessage = "{0:dd-MM-yyyy HH:mm:ss.FFF}: {1}" -f (Get-Date), $Message

        Write-Information $logMessage
        Out-File -FilePath "c:\temp\verbose.txt" -Append -InputObject $logMessage
    }
}

$InformationPreference = "Continue"

Write-Log "Renaming 'Download' to 'Download.old'"
Rename-Item "C:\Windows\SoftwareDistribution\Download" "Download.old" -Force -Verbose -ErrorAction Continue *>> "c:\temp\verbose.txt"
Write-Log "Finished renaming 'Download' to 'Download.old'"