【问题标题】:How to generate a log file using copy command in powershell for successfully copied files如何在 powershell 中使用复制命令为成功复制的文件生成日志文件
【发布时间】:2023-01-03 18:30:37
【问题描述】:

我是 powershell 脚本的新手。我想使用 powershell 将文件(重复文件)从一个文件夹复制到另一个文件夹。我只想生成一个文本文档,其中包含有多少文档已成功复制到目的地的信息。我在谷歌上找到了以下脚本,但它不起作用。谁能帮我解决这个问题。

$source = "C:\FolderA"
$destination = "C:\FolderB"
$Date = get-date
$items = Get-ChildItem -Path $source -Recurse | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-2) -and ($_.PSisContainer -eq $true) }
foreach($item in $items)
{
    try
    {
        $copiedItems=Copy-Item "$source\$item" -Destination $destination -Force -Recurse -PassThru 
        "$([DateTime]::Now)" + "`t$source\$item`t is copied onto $destination"| out-file c:\scripts\copied.txt -Append
    }
    catch
    {
        "$source\$item"+": " + $_.Exception.message | Out-File c:\scripts\Notcopied.txt -Append
    }
}

提前谢谢了。

【问题讨论】:

  • $copiedItems 变量在分配后当前未使用。要插入复制项目的计数:"`t$source\$item`t is copied onto $destination (number of items: $($copiedItems.Count)"
  • 嗨 @zett42,非常感谢您的快速回复。但是当我尝试你提到的方法时,它对我不起作用。如果你不介意,你能不能用你提到的评论修改我的代码?并在此链中发布该代码。再次感谢。
  • 你想复制吗全部项目从一个文件夹到另一个?因为这个脚本没有这样做 - 它过滤文件夹和超过 2 天的任何东西。
  • 是的! folder1(源)中有数千个重复文档,我只想将所有这些文档复制到 folder2(目标)。所以代码应该生成一个 txt 文件,说明有多少文档被复制到目的地。 @scepticalist 对此有什么想法吗?

标签: powershell


【解决方案1】:

见下文:

$source = "C:FolderA"
# Set source and destination. This script will not create the destination folder, it has to exist
$destination = "C:FolderB"
$Date = get-date
# Get list of all files, exclude directories
$items = Get-ChildItem -Path $source -Recurse -File

ForEach($item in $items) {
    Try {
        Copy-Item $item.FullName -Destination $destination$item -Force -Recurse -PassThru -ErrorAction Stop
        "$([DateTime]::Now)" + "`t$source$item`t copied to $destination"| out-file c:	empcopied.txt -Append
    }
    Catch {
        "$source$item"+": " + $_.Exception.message | Out-File c:	empNotcopied.txt -Append
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多