2015-06-01 189 views
1

我有一個PS腳本,拉鍊了前幾個月的日誌和名稱的zip文件FILENAME-YYYY-MM.zipPowerShell的複製文件和文件夾

這工作

我現在想要做的就是複製這些zip文件開了個網絡共享但保留一些文件夾結構。我目前的文件夾結構類似於以下;

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

有以下c:\Folder1 我要的是對腳本文件複製從c:\folder1\\networkshare但保持文件夾結構,每個文件夾中的.zip文件,所以我應該有3個文件夾,並在folder4另一個子文件夾。

目前我只能得到它,所以我在我的\\networkshare

我一直運行到的問題,如新的文件夾結構不存在,我無法使用-recurse開關獲得c:\folder1\...複製整個結構在Get-ChildItem命令等內...

我到目前爲止的腳本是;

#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 
+3

類似的問題我在這裏看到的回答是「不要重新發明輪子,只是使用robocopy」,因此可能需要考慮。 –

+0

是的,我認爲robocopy可以解決你的問題。看看這個問題,如果幫助你:http://stackoverflow.com/questions/21606259/robocopy-copy-files-preserving-folder-structure-but-adding-a-subfolder – wallybh

+0

@TonyHinkle使用robocopy可以產生問題,如果robocopy日誌將被解析 - 我遇到了與該文件編碼有關的麻煩,如果通過'> file.log'記錄,robocopy會放入^ H符號。而且,爲什麼不在Powershell上編寫自己的解決方案,而不是依賴第三方軟件? – Vesper

回答

2

有時,您不能(很容易)使用「純PowerShell」解決方案。這是其中的一次,沒關係。

Robocopy將鏡像目錄結構,包括任何空目錄,並選擇您的文件(可能比使用get-childitem的過濾器更快)。你可以這樣複製任何東西超過90天(約3個月)以上:

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

您可以/MINAGE指定實際日期也一樣,如果你要那麼精確。

+0

修改了這一點,但感謝一堆! $ $ LastWriteMonth =(Get-Date).AddMonths(-3).ToString('yyyyMMdd') $ DestinationLoc =「\\ networkshare \ LogArchive \ $ env:computername \」 Robocopy C:\ sourcefiles \ $ DestinationLoc - 是-E -MINAGE:$ LastWriteMonth * .zip' – Wiggum123

0

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 
相關問題