簡體   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