简体   繁体   English

Powershell 将文件复制到新目标的脚本

[英]Powershell Script to Copy Files to new Destination

I'm using the below powershell script to move files from $Source to $Destination based on a date range.我正在使用下面的 powershell 脚本根据日期范围将文件从 $Source 移动到 $Destination。 During testing, it's moving all of files within a directory that may have been updated within the date range, but I only require the updated or new files with the Directory/Subdirectory.在测试期间,它会移动目录中可能已在日期范围内更新的所有文件,但我只需要目录/子目录中的更新文件或新文件。 I like how it's working, except for copying everything.我喜欢它的工作方式,除了复制所有内容。

Any thoughts on how the script can can be tweaked?关于如何调整脚本的任何想法?

$source = "C:\Documents and Settings"
$destination = "C:\Documents and Settings\Test"
[datetime]$start = '2/18/2021 11:00:00'
[datetime]$end = '2/18/2021 11:15:00'

 #Prod
 dir $source | %{ dir $_.FullName | ?{ $_.LastWriteTime -gt $start-and $_.LastWriteTime -lt $end } | 
 Copy-Item -Destination $destination -Recurse -Force }

I think what you probably need to do, if you're staying in Powershell and not using something like Robocopy to sync the folders, would be to push the path recursion up a level and then check a file at a time:我认为您可能需要做的是,如果您留在 Powershell 并且不使用 Robocopy 之类的工具来同步文件夹,那么您可能需要将路径递归提升一个级别,然后一次检查一个文件:

  1. Get-ChildItem -Recurse on the source path Get-ChildItem -Recurse在源路径上递归
  2. ForEach-Object on the result结果上的ForEach-Object
  3. Test-Path on the destination (doing a Replace of $source to $destination in the path)目标上的Test-Path (在路径中将$source Replace$destination
  4. Copy-Item from $source to $destination where the file doesn't exist or the LastFileWrite property is newer at the source path$source Copy-Item$destination文件不存在或LastFileWrite属性在源路径较新

In Posh, you filter as far left for faster results.在 Posh 中,您过滤到最左边以获得更快的结果。

$source = "C:\Documents and Settings"
$destination = "C:\Documents and Settings\Test"
[datetime]$start = '2/18/2021 11:00:00'
[datetime]$end = '2/18/2021 11:15:00'

Get-ChildItem -Path $source -Recurse | Where-Object { $_.lastwriteTime -le $start -lt $end } | ForEach-Object -Process { Copy-Item -Path $_.FullName -Destination $destination -Force }

You're doing redundant work when you pipe another dir down the line.当您 pipe 另一个dir时,您正在做多余的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM