2011-06-14 227 views
3

我是比較新的PowerShell的,我是想用此格式的文本文件來複制文件:PowerShell中的Copy-Item;給定路徑的格式不支持

file1.pdf 
dir1\dir2\dir3\dir 4 

file2.pdf 
dir1\dir5\dir7\di r8 

file3.pdf 
...etc. 

其中每一條目的第一行是一個文件名,第二個是C:\ Users的文件路徑。例如,要在文件中的第一項的完整路徑將是:

C:\Users\dir1\dir2\dir3\dir 4\file1.pdf 

下面的代碼是什麼,我現在有,但我得到的錯誤:「不支持給定路徑的格式。」之後的另一個錯誤告訴我它找不到路徑,我認爲這是第一個錯誤的結果。我已經玩了一下,並且我得到的印象是將這個字符串傳遞給Copy-Item。

$file = Get-Content C:\Users\AJ\Desktop\gdocs.txt 
    for ($i = 0; $i -le $file.length - 1; $i+=3) 
    { 
     $copyCommand = "C:\Users\" + $file[$i+1] + "\" + $file[$i] 
     $copyCommand = $copyCommand + " C:\Users\AJ\Desktop\gdocs\" 
     $copyCommand 
     Copy-Item $copyCommand 

    } 

回答

5

您可以閱讀的三行塊的文件,加入了前兩個元素,以形成通道,並使用複製項目要複製的文件。

$to = "C:\Users\AJ\Desktop\gdocs\" 

Get-Content C:\Users\AJ\Desktop\gdocs.txt -ReadCount 3 | foreach-object{ 
    $from = "C:\Users\" + (join-path $_[1] $_[0]) 
    Copy-Item -Path $from -Destination $to 
} 
1

試試這個(週期內):

$from = "C:\Users\" + $file[$i+1] + "\" + $file[$i] 
$to = "C:\Users\AJ\Desktop\gdocs\" 
Copy-Item $from $to 

$from$toCopy-Item cmdlet的參數。它們綁定到參數-路徑-Destinattion。您可以通過此代碼檢查:

Trace-Command -pshost -name parameterbinding { 
    Copy-Item $from $to 
} 
相關問題