2009-11-06 85 views
4

我是Powershell的新手,試圖獲得一個簡單的腳本來運行。PowerShell:如何從源目錄中只複製選定的文件?

我有一個我想從src_dir複製到dst_dir的文件列表。我寫了一個簡單的腳本(這顯然是錯誤的,因爲它在執行時沒有做任何事情)。

有人可以幫忙檢查看看我做錯了什麼嗎?

# source and destionation directory 
$src_dir = "C:\Users\Pac\Desktop\C4new" 
$dst_dir = "C:\Users\Pac\Desktop\csci578-hw3\Prism\C4new" 

# list of files from source directory that I want to copy to destination folder 
# unconditionally 
$file_list = "C4newArchitecture.java", "CustomerData.java" 

# Copy each file unconditionally (regardless of whether or not the file is there 
for($i=0; $i -le $file_list.Length - 1; $i++) 
{ 
    Copy-Item -path $src_dir+$file_list[$i] -dest $dst_dir -force 
} 

回答

9

Oh..that其實很簡單:

# source and destionation directory 
$src_dir = "C:\Users\Pac\Desktop\C4new\" 
$dst_dir = "C:\Users\Pac\Desktop\csci578-hw3\Prism\C4new" 

# list of files from source directory that I want to copy to destination folder 
# unconditionally 
$file_list = "C4newArchitecture.java", 
      "CustomerData.java", 
      "QuickLocalTransState.java", 
      "QuickLocalTransState_AbstractImplementation.java", 
      "SaveSessionOK.java", 
      "SessionID.java", 
      "UserInterface.java", 
      "UserInterface_AbstractImplementation.java" 

# Copy each file unconditionally (regardless of whether or not the file is there 
foreach ($file in $file_list) 
{ 
    Copy-Item $src_dir$file $dst_dir 
} 

作爲一個程序員,我愛的foreach!

11

假設文件是​​直接理解過程$ src_dir你可以做到這一點多一點,即簡單的複製可以是一個班輪:

$file_list | Copy-Item -Path {Join-Path $src_dir $_} -Dest $dst_dir -ea 0 -Whatif 

電子藝界對於-ErrorAction參數和0別名值對應於SilentlyContinue。這會導致Copy-Item忽略如果其中一個源文件不存在就會得到的錯誤。但是,如果您遇到問題,請暫時刪除此參數,以便查看錯誤消息。

當以交互方式輸入這些東西時,我傾向於使用這樣的快捷方式,但是在腳本中,最好將它拼出來以提高可讀性。另請注意,-Path參數可以採用腳本塊,即花括號中的腳本。從技術上講,Copy-Item cmdlet不會看到scriptblock,只是它的執行結果。這通常適用於任何需要管道輸入的參數。刪除-WhatIf以使命令實際執行。

+0

wow..that看起來很酷。感謝分享信息! – sivabudh 2009-11-06 05:09:50

0
Get-ChildItem -Path $srcDir | Where-Object { $fileNames -contains $_.Name } | Copy-Item -Destination $dstDir 

這是在某些情況下確實方便,例如:

Get-ChildItem -Filter *.ocr.txt | Copy-Item -Destination $dstDir 
相關問題