2015-07-20 140 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