Powershell script to find a folder and copy to another folder

Viewed 545

I have a long directory path. The nested folder values keep changing as per project name. but last directory PackageTmp does not change, Looking forward to copy files from PackageTmp to another directory. I want to copy all subfolder and files from C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp to C:\deploy. My code is copying to C:\deploy\PackageTmp.

Source Dir :- C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp
Inconsistent Path :- \D_C\a\1\s\src\prj\obj\Release\Package\
Target Dir :- C:\deploy\
Non working code :- Get-ChildItem C:\unzip\ -Filter PackageTmp -Recurse | where {($_.psiscontainer)}| Copy-Item -Destination C:\deploy\ -Recurse -filter * -Force
1 Answers

Analysis

Looks like you're almost there. Your script is just finding the PackageTmp directory and then passing it down the pipeline where it's eventually copied to the destination, directory and contents all included. The trick is, once you find the PackageTmp directory, you then can use a wildcard to get everything that's IN the PackageTmp directory and copy that to your destination.

Code

I tweaked your non-working code, so hopefully this works for you.

# Get the PackageTmp directory
$PackageTmp = Get-ChildItem C:\unzip\ -Filter PackageTmp -Recurse | Where-Object {($_.psiscontainer)}

# Print the FullName of the PackageTmp directory
Write-Host "PackageTmp: $($PackageTmp.FullName)"

# Recursively copy everything in the PackageTmp directory to our destination directory
Copy-Item -Path "$($PackageTmp.FullName)\*" -Destination C:\deploy\ -Recurse -filter * -Force 

Explanation

I store the PackageTmp location in a variable. I can then specify that I want to copy everything INSIDE the PackageTmp directory by using the -Path "$($PackageTmp.FullName)\*" parameter, note the use of the wildcard \*. This doesn't copy the PackageTmp directory, like you requested.

So effectively instead of doing this:

Copy C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp -> C:\deploy\

We're just doing this:

Copy C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp\* to C:\deploy\
Related