2015-12-08 29 views
0

我知道有很多與這個問題有關的答案,但他們從來沒有完全按照我的意願去做。Powershell在文件夾之間移動文件

我有一個根文件夾,在那可能是1或許多子文件夾。最初文件在根文件夾Rejected中創建,程序將嘗試並處理它,如果不成功,則將其移動到特定的子文件夾中,具體取決於錯誤。所以在這種情況下,我們有:

| - Rejected 
    | 
    | - duplicate_found 
    | | - Informed 
    | 
    | - no_name 
     | - Informed 

我的程序要通過每個子文件夾(而不是Informed文件夾)的循環,並保持在子文件夾中的文件列表,然後通過電子郵件發送列表一個接受者然後將進行調查。

在通過電子郵件發送所有文件後,我想將這些文件移動到與其父拒絕原因子文件夾相關的子文件夾Informed

因此,如果文件在duplicate_found中找到,該文件將被移動到duplicate_found/Informed。如果在no_name找到的文件然後將被移動到no_name/Informed等。

我可以做電子郵件的一部分,它是循環通過每個子文件夾,然後移動文件,我無法得到處理的一部分。

我不能在流程結束時完成一個完整的文件夾移動,因爲新文件可能已經進入,但尚未在電子郵件中發送。所以我是否需要在循環時移動文件,並同時保留電子郵件列表。不確定最好的方法。

幫助非常感謝

回答

1

下面是一個例子(PS 3.0所需的Get-ChildItem-File-Directory參數):

#set root folder 
$baseFolder = "C:\Rejected" 

#get folders inside root 
$folders = Get-ChildItem $baseFolder -Directory 

#for each folder 
foreach($folder in $folders) { 

    #list the files 
    $files = Get-ChildItem $folder.FullName -File 

    #if there are files 
    if($files.Count) { 

     #build the move destination path 
     $destination = Join-Path $folder.FullName "Informed" 

     #move the files 
     $files | % { Move-Item $_.FullName $destination } 

     #build an email message with some information + the file listing 
     $emailMessage = "$($files.Count) files reported and moved in folder $destination" 

     #this could be formatted, i'm only pushing what you would see 
     #in the console in the text message 
     $emailMessage += $files | Out-String 

     #i.e.: 5 files reported in folder duplicate_found and moved to 
     #C:\Rejected\duplicate_found\Informed 
     # 
     # [file listing] 

     #send email report for this folder 

     $emailMessage 
    } 
} 
+0

即優異。看到代碼時看起來很簡單,但找到使用的代碼似乎總是最難的部分。謝謝 – AndrewH

+0

非常歡迎:-)。如果你喜歡這個答案,你可以點擊它下面的綠色支票來接受它。 – sodawillow

相關問題