2011-08-22 114 views
3

我想製作一個腳本,該腳本將帶有一個父目錄,該目錄中有許多包含文件的子目錄。使用列表我希望將子目錄中的所有文件移動到父目錄中。Powershell,批量移動某種類型的文件

我已經創建了以下代碼,它給出了子目錄中指定類型的所有文件的列表,但我不確定如何對所有子文件進行批量移動。

Write-host "Please enter source Dir:" 
$sourceDir = read-host 

Write-Host "Format to look for with . :" 
$format = read-host 

#Write-host "Please enter output Dir:" 
#$outDir = read-host 

$Dir = get-childitem -Path $sourceDir -Filter $format -recurse | format-table name 

$files = $Dir | where {$_.extension -eq "$format"} 
$files #| format-table name 

回答

7

有幾件事情:

  1. 您可以通過您直接寫入到讀主機cmdlet的文本,它爲每個用戶輸入節省了一行。作爲一個經驗法則,如果您打算對命令的輸出做更多的事情,請不要將它傳遞給format- * cmdlet。格式cmdlet生成格式化對象,指示powershell如何在屏幕上顯示結果。

  2. 儘量避免將結果分配給一個變量,如果結果中含有大量一套文件系統,內存消耗可以走得很高,你可以遭受性能下降。

  3. 同樣,在性能方面,嘗試使用,而不是其中對象小命令(服務器端篩選與客戶端)小命令的參數。第一種方法是過濾目標上的對象,而後者僅在獲取到機器後過濾對象。

WhatIf開關會告訴你哪些文件會移動。刪除它以執行該命令。您可能還需要用它來處理重複的文件名。

$sourceDir = read-host "Please enter source Dir" 
$format = read-host "Format to look for" 

Get-ChildItem -Path $sourceDir -Filter $format -Recurse | Move-Item -Destination $sourceDir -Whatif 
+0

謝謝你的提示,我會盡量改進我的方法在未來,並採取你已經傳授的。 PowerShell的語法似乎很有些不適應的,我需要進行這樣學習如何使用它的任務是用途不同高我的目標名單上 –

1

如果我理解正確你的問題,你可以使用Move-Item上的文件將其移動到輸出目錄:

$Dir = get-childitem $sourceDir -recurse 
$files = $Dir | where {$_.extension -eq "$format"} 
$files | move-item -destination $outDir 
0

以前的帖子指出腳本會覆蓋同名文件。可以通過測試來擴展腳本並避免這種可能性。這樣的事情:

$sourceDir = read-host "Please enter source Dir" 
$format = read-host "Format to look for?" 
$destDir = read-host "Please enter Destination Dir" 

Get-ChildItem -Path $sourceDir -Filter $format -Recurse | Copy-Item -Destination $DestDir 
$files = $DestDir | where {$_.extension -eq "$format"} 

If (Test-Path $files) { 
    $i = 0 
    While (Test-Path $DestinationFile) { 
     $i += 1 
     $DestinationFile = "$files$i.$format" 
     Copy-Item -Destination $DestDir $DestinationFile 
    } 
} 
Else { 
    $DestinationFile = "$files$i.$format" 
    Copy-Item -Destination $DestDir $DestinationFile 
} 
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force