2012-07-19 91 views
0

我正在使用PS腳本將5個最新文件按源文件類型從源目錄移動到目標目錄,同時保留子文件夾結構。例如,我想將任何以AB_開頭的文件從ParentFolder1 \ FolderA,ParentFolder1 \ FolderB,ParentFolder1 \ FolderC等移動到ParentFolder2 \ FolderA,ParentFolder2 \ FolderB,ParentFolder2 \ FolderC。PowerShell - 將特定文件從源子文件夾移動到具有相同子文件夾結構的目標

ParentFolder1

--FolderA

---- AB_1234.txt

---- AB_5678.txt

---- XY_9876.txt

- --- XY_9876.txt

- 文件夾B

---- AB_1234.txt

---- AB_5678.txt

---- XY_9876.txt

---- XY_9876.txt

--FolderC

---- AB_1234.txt

---- AB_5678.txt

---- XY_9876.txt

---- XY_9876.txt

有沒有一種方法,以配合成這樣的循環?這是我到目前爲止:

$source = "C:\Test" 
$dest = "E:\archive" 
$AB = Get-ChildItem -Path $source -include AB_* -Recurse | Where-Object {-not $_.PsIsContainer} 
$XY = Get-ChildItem -Path $source -include XY_* -Recurse | Where-Object {-not $_.PsIsContainer} 
$keep = 5 
$logfile = "E:\_archive\temp\log_{0:MM-dd-yyyy}.log" -f (Get-Date) 

if ($AB.Count -gt $keep) { 
    $AB | Sort -property LastWriteTime | Select-Object -First ($AB.Count - $keep) | Move-Item -destination $dest\AB -Force -Verbose 
    } 
Else 
    {"No AB_ files to archive." | Out-File $LogFile -Append -Force} 

if ($XY.Count -gt $keep) { 
    $XY | Sort -property LastWriteTime | Select-Object -First ($XY.Count - $keep) | Move-Item -destination $dest\XY -Force -Verbose 
    } 
Else 
    {"No XY_ files to archive." | Out-File $LogFile -Append -Force} 

回答

0

你可能會更好使用Robocopy

+0

我沒有使用xcopy或robocopy的主要原因是我找不到一種方法來保留最新的5個文件並移動其餘的文件。 Robocopy有沒有辦法做到這一點? – user1539274 2012-07-20 20:36:22

+0

對不起,我沒注意到最新的5個文件。 – Neil 2012-07-20 23:21:29

2
function Move-Newest-Files 
{ 
    param (
     [parameter(Mandatory = $true)] [string] $source, 
     [parameter(Mandatory = $true)] [string] $destination, 
     [parameter(Mandatory = $true)] [array] $filter, 
     [parameter(Mandatory = $false)][int] $keep = 5 
    ) 

    try 
    { 
     $source = Resolve-Path $source 

     $list = Get-ChildItem -Path $source -Include $filter -Recurse -Force | 
      Where-Object { -not $_.psIsContainer } | 
      Sort-Object -property LastWriteTime -descending | 
      Select-Object -First $keep 

     foreach ($file in $list) 
     { 
      $destfile = $file -replace [regex]::Escape($source), $destination 
      $destpath = Split-Path $destfile -Parent 

      if (!(Test-Path $destpath)) 
       { $null = New-Item -ItemType Container -Path $destpath } 

      Move-Item $file -Force -Destination $destfile 
     } 
    } 

    catch 
    { 
     Write-Host "$($MyInvocation.InvocationName): $_" 
    } 
} 

Move-Newest-Files . "D:\xyzzy" @("*.cs", "*.txt", "*.exe") 10 
+0

謝謝大衛。你能爲我定義$ filter和$ file變量嗎? – user1539274 2012-07-20 21:25:55

+0

$ filter是一個數組,其文件擴展名爲要保留的文件:類似於@(「* .cs」,「* .txt」,「* .exe」)或這個@(「*。*」 ) – 2012-07-21 08:41:55

相關問題