Kai
Kai

Reputation: 790

Split-Path + Join-Path functionality

I have a problem concerning the Split-Path and Join-Path cmdlets of MS PowerShell. I want to copy an entire directory from the folder (including all folder and files therein) C:\Testfolder to the folder C:\TestfolderToReceive.

For this task I use the following coding:

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

The problem arises with files which aren't directly in C:\Testfolder, but in subfolders of it (EXAMPLE: C:\Testfolder\TestSubfolder1\Testsub1txt1.txt). All these files which are not directly in C:\Testfolder return "null" via the $childpath variable.

For example for the file C:\Testfolder\TestSubfolder1\Testsub1txt1.txt I would like it to return TestSubfolder1\Testsub1txt1.txt so that a new path called C:\TestfolderToReceive will be created by the Join-Path functionality.

Could someone explain me what I am doing wrong and explain me the correct way for tackling such a problem?

Upvotes: 0

Views: 1008

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174730

I think you're overthinking this. Copy-Item can do this for you on its own:

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

The \* part is crucial here, otherwise Copy-Item will recreate TestFolder inside C:\TestfolderToReceive

In this scenario, you could use Join-Path to position the * correctly:

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

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

If you want a list of files copied, you can use the -PassThru parameter with Copy-Item:

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

Upvotes: 1

Related Questions