在powershell

时间:2015-11-02 07:57:26

标签: powershell logging powershell-v2.0

我有以下的powershell代码,其中, 文件夹1中的(原始)文件备份在folder2中,文件夹1中的文件用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 !"

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

任何人都可以帮我这个吗? 我做了以下代码,但没有用,因为我无法同步这两个代码。

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  
}

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

1 个答案:

答案 0 :(得分:0)

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

| 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 
    }
}
相关问题