【问题标题】:Powershell Copy files and foldersPowershell 复制文件和文件夹
【发布时间】:2015-06-01 12:45:15
【问题描述】:

我有一个 PS 脚本,它压缩前几个月的日志并将压缩文件命名为 FILENAME-YYYY-MM.zip

这行得通

我现在要做的是将这些 zip 文件复制到网络共享,但保留一些文件夹结构。我目前的文件夹结构类似如下;

C:\Folder1\
C:\Folder1\Folder2\
C:\Folder1\Folder3\
C:\Folder1\Folder4\Folder5\

c:\Folder1下面的每个文件夹都有.zip文件 我想要的是让脚本将文件从c:\folder1 复制到\\networkshare 但保持文件夹结构,所以我应该在folder4 中有3 个文件夹和另一个子文件夹。

目前我只能让它复制整个结构,所以我在\\networkshare 中得到c:\folder1\...

我不断遇到诸如新文件夹结构不存在、我无法在Get-ChildItem 命令中使用-recurse 开关等问题...

我目前的脚本是;

#This returns the date and formats it for you set value after AddMonths to set archive date -1 = last month
$LastWriteMonth = (Get-Date).AddMonths(-3).ToString('MM')
#Set destination for Zip Files
$DestinationLoc = "\\networkshare\LogArchive\$env:computername"

#Source files
$SourceFiles = Get-ChildItem C:\Sourcefiles\*.zip -Recurse | where-object {$_.lastwritetime.month -le $LastWriteMonth} 
Copy-Item $SourceFiles -Destination $DestinationLoc\ZipFiles\
Remove-Item $SourceFiles

【问题讨论】:

  • 我在这里看到的类似问题已通过“不要重新发明轮子,只需使用 robocopy”得到回答,因此可能需要考虑一下。
  • 是的,我认为 robocopy 可以解决您的问题。如果对您有帮助,请看这个问题:stackoverflow.com/questions/21606259/…
  • @TonyHinkle 如果要解析 robocopy 日志,则使用 robocopy 可能会产生问题 - 我在使用该文件编码时遇到问题,如果通过 > file.log 记录,robocopy 也会放入 ^H 符号。而且,为什么不在 Powershell 上编写自己的解决方案,而不是依赖第三方软件呢?

标签: powershell


【解决方案1】:

有时,您不能(轻松)使用“纯 PowerShell”解决方案。这是其中之一,没关系。

Robocopy 将镜像目录结构,包括任何空目录,并选择您的文件(可能比使用get-childitem 的过滤器更快)。您可以像这样复制超过 90 天(大约 3 个月)的任何内容:

robocopy C:\SourceFiles "\\networkshare\LogArchive\$($env:computername)\ZipFiles" /E /IS /MINAGE:90 *.zip

您也可以使用/MINAGE 指定实际日期,如果您必须如此精确的话。

【讨论】:

  • 稍微修改了一下,但非常感谢! $LastWriteMonth = (Get-Date).AddMonths(-3).ToString('yyyyMMdd') $DestinationLoc = "\\networkshare\LogArchive\$env:computername\" Robocopy C:\sourcefiles\ $DestinationLoc -IS -E -MINAGE:$LastWriteMonth *.zip
【解决方案2】:

Copy-Item "C:\SourceFiles\" -dest $DestinationLoc\ZipFiles -container -recurse 怎么样?我对此进行了测试,发现它完整地复制了文件夹结构。如果您只需要*.zip 文件,则首先获取它们,然后为每个您提供call Resolve-Path with -Relative flag set,然后将生成的路径添加到Destination 参数中。

$oldloc=get-location
Set-Location "C:\SourceFiles\" # required for relative
$SourceFiles = Get-ChildItem C:\Sourcefiles\*.zip -Recurse | where-object {$_.lastwritetime.month -le $LastWriteMonth}
$SourceFiles | % { 
    $p=Resolve-Path $_.fullname -relative
    copy-item $_ -destination "$DestinationLoc\ZipFiles\$p"
}
set-location $oldloc # return back

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多