【问题标题】:creating a log file in powershell在 powershell 中创建日志文件
【发布时间】:2015-11-03 17:44:10
【问题描述】:

我有以下 powershell 代码,其中, folder1 中(原始)文件的备份在 folder2 中进行,并且 folder1 中的文件使用 folder3 文件进行更新。

修补程序的概念!!

cls
[xml] $XML = Get-content -Path <path of xml>
$main = $XML.File[0].Path.key
$hotfix = $XML.File[1].Path.key
$backup = $XML.File[2].Path.key
Get-ChildItem -Path $main | Where-Object {
    Test-Path (Join-Path $hotfix $_.Name)
} | ForEach-Object {
    Copy-Item $_.FullName -Destination $backup -Recurse -Container
}
write-host "`nBack up done !"
Get-ChildItem -Path $hotfix | ForEach-Object {Copy-Item $_.FullName -Destination $main -force}
write-host "`nFiles replaced !"

现在,由于文件的备份是在文件夹 2 中进行的,我需要创建一个日志文件,其中包含 - 进行备份的文件的名称、日期和时间、进行备份的位置

谁能帮我解决这个问题? 我做了以下代码,但它没有用,因为我无法同步两者。

cls
$path = "C:\Log\Nlog.log"   
$numberLines = 25

For ($i=0;$i -le $numberLines;$i++)
{
 $SampleString = "Added sample {0} at {1}" -f $i,(Get-Date).ToString("h:m:s")
 add-content -Path $path -Value $SampleString -Force  
}

感谢任何帮助或不同的方法!

【问题讨论】:

    标签: powershell logging powershell-2.0


    【解决方案1】:

    您可以使用-PassThru 开关参数让Copy-Item 返回它刚刚复制的新项目 - 然后立即在ForEach-Object 脚本块内进行日志记录:

    | ForEach-Object {
        $BackupFiles = Copy-Item $_.FullName -Destination $backup -Recurse -Container -PassThru
        $BackupFiles |ForEach-Object { 
            $LogMessage = "[{0:dd-MM-yyyy hh:mm:ss.fff}]File copied: {1}" -f $(Get-Date),$_.FullName 
            $LogMessage | Out-File ".\backups.log" -Append 
        }
    }
    

    【讨论】:

    • ok @Mathias .. 但我还需要打印日期和时间。我应该如何管道?
    • 在循环中使用Get-Date 检索当前日期和时间,然后使用-f 运算符格式化日志消息。答案已更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2014-04-10
    • 2019-05-30
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多