![](/img/trans.png)
[英]Copy folders without files, files without folders, or everything using 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.