Split-Path + Join-Path功能

时间:2015-07-20 14:42:24

标签: powershell split

我遇到有关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,以便C:\TestfolderToReceive功能创建一个名为Join-Path的新路径。

有人可以解释一下我做错了什么并向我解释解决这个问题的正确方法吗?

1 个答案:

答案 0 :(得分:1)

我认为你过分思考这一点。 Copy-Item可以自己为您完成此任务:

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

此处\*部分至关重要,否则Copy-Item会在TestFolder

内重新创建C:\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
相关问题