2015-07-20 155 views
0

我有關於MS PowerShell的Split-PathJoin-Path cmdlet的問題。我想將整個目錄從文件夾(包括其中的所有文件夾和文件)C:\Testfolder複製到文件夾C:\TestfolderToReceive拆分路徑+加入路徑功能

對於這個任務,我用下面的代碼:它

$sourcelist = Get-ChildItem $source -Recurse | % { 
    $childpath = split-path "$_*" -leaf -resolve 
    $totalpath = join-path -path C:\TestfolderToReceive -childpath $childpath 
    Copy-Item -Path $_.FullName -Destination $totalpath 
} 

的問題,這直接不在C:\Testfolder文件出現,但在子文件夾(例如:C:\Testfolder\TestSubfolder1\Testsub1txt1.txt)。所有這些不是直接在C:\Testfolder中的文件都通過$childpath變量返回「null」。

例如對於文件C:\Testfolder\TestSubfolder1\Testsub1txt1.txt,我希望它返回TestSubfolder1\Testsub1txt1.txt,以便通過Join-Path功能創建一個名爲C:\TestfolderToReceive的新路徑。

有人能解釋我做錯了什麼,並解釋我解決這個問題的正確方法嗎?

回答

1

我認爲你是在反思這一點。 Copy-Item可以自行爲你做這個:

Copy-Item C:\Testfolder\* C:\TestfolderToReceive\ -Recurse 

\*部分是這裏的關鍵,否則Copy-Item將重新TestFolderC:\TestfolderToReceive

在這種情況下,你可以使用Join-Path*正確定位:

$SourceDir  = 'C:\Testfolder' 
$DestinationDir = 'C:\TestfolderToReceive' 

$SourceItems = Join-Path -Path $SourceDir -ChildPath '*' 
Copy-Item -Path $SourceItems -Destination $DestinationDir -Recurse 

如果您想要複製文件的列表,可以使用-PassThru參數和Copy-Item

$NewFiles = Copy-Item -Path $SourceItems -Destination $DestinationDir -Recurse -PassThru