You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现文件夹文件单次自动复制至目标文件夹(含新增监控)

追踪文件复制与处理的PowerShell脚本问题

我遇到一个技术问题,自己解决不了,谷歌也没找到方案。

我有个名为Trace的文件夹(folder1),多个设备会在这里生成后缀为.trace的追踪文件,设备运行时会持续新增这类文件。我写了一段PowerShell脚本,能自动把所有.trace文件转为txt文件,合并成单个txt后删除这些txt文件,避免重复合并。脚本如下:

while (1)
{
Get-ChildItem -Path "C:\xxx\xxx\xxx\Trace2"*.trace | Rename-Item -NewName { $_.name -Replace '\.trace$','.txt' }
C:\xxx\xxx\xxx\Powershell\Combine-Files.ps1 -output "C:\xxx\xxx\xxx\Test\test.txt" -source "C:\xxx\xxx\xxx\Trace2\" -filter "*.txt" -append 
Get-ChildItem C:\xxx\xxx\xxx\Trace2\*.txt -File | Remove-Item -Force
Start-Sleep -Seconds 10
}

这个脚本能正常运行,但问题是我不能删除folder1里的原trace文件,所以需要第二个文件夹(folder2),folder2要满足以下条件:

  • folder1中已存在及后续新增的文件都要复制到folder2
  • 每个文件仅允许从folder1复制到folder2一次,若folder2中该文件被删除,不能再次从folder1复制

如果没法实现上述需求,仅复制folder1中新增文件的脚本或程序也可以,我会手动复制已存在的文件。

我试过一段相关PowerShell脚本,但因为folder2中的文件会被立即删除,没法对比判断文件是否已复制过;也试过robocopy /mir,但它会创建folder1的镜像副本,导致folder2中删除的文件被重新复制回去。


编辑1:测试脚本异常

我调整了Sirtao提供的脚本路径,代码如下:

$watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\Users\dabetschart\Documents\Trace2"
    $watcher.Filter = "*.txt"
    $watcher.EnableRaisingEvents = $true  
    $DestinationPath = "C:\Users\dabetschart\Documents\Test"

    $action = { 
                $FileCreated = $Event.SourceEventArgs.FullPath
                Start-Sleep -Seconda 1
                Copy-Item -Path $FileCreated -Destination $DestinationPath
              }    
    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 5}

但Trace2中新建的txt文件并没有复制到Test文件夹,而且没有报错,我设置*.txt过滤是为了先测试。


编辑2:解决后的可用脚本

我找到问题所在了,以下代码可以正常运行:

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\Users\dabetschart\Documents\Trace2"
    $watcher.Filter = "*.*"
    $watcher.EnableRaisingEvents = $true  
    $DestinationPath = "C:\Users\dabetschart\Documents\Test"

    
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { 
                $Path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                Copy-Item -Path $Path -Destination $DestinationPath
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
### Register-ObjectEvent $watcher "Changed" -Action $action
### Register-ObjectEvent $watcher "Deleted" -Action $action
### Register-ObjectEvent $watcher "Renamed" -Action $action
    while ($true) {sleep 1}

非常感谢Sirtao的帮助。


内容的提问来源于stack exchange,提问作者Hagstuud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:28:17