繁体   English   中英

Powershell复制文件和文件夹

[英]Powershell Copy files and folders

我有一个PS脚本,它会拉上前几个月的日志,并将zip文件命名为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\\...

我一直在-recurse新的文件夹结构不存在的问题,我不能在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

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

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

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

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

如何Copy-Item "C:\\SourceFiles\\" -dest $DestinationLoc\\ZipFiles -container -recurse 我测试了这个并发现它完整地复制了文件夹结构。 如果您只需要*.zip文件,则首先获取它们,然后为每个文件调用Resolve-Path并设置-Relative标志 ,然后将结果路径添加到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

暂无
暂无

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

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