Author Posts

August 3, 2017 at 8:58 am


I have a folder with +2500 projekt folders like this:




And so on.

I am looking for a PS script to help me copy certain folders and sub folders, to another network share. I am not that good at PS, so I've found a script, but it does not include empty folders. And I really need all folders, because every projekt folder is auto generated from a template, so a lot of folders is empty to begin with.

The script looks like this and find the folder named "2_ STXP Tegninger", then copy it to the set target including the folder structure:

$source = 'C:\Temp\STXP\Projekter'
$target = 'C:\Temp\STXP\Test'
$source_regex = [regex]::escape($source)
(gci $source -recurse | where {-not ($_.psiscontainer)} | select -expand fullname) -match '\\2_ STXP Tegninger\\' |
foreach {

$file_dest = ($_ | split-path -parent) -replace $source_regex,$target

if (-not (test-path $file_dest)){mkdir $file_dest}
copy-item $_ -Destination $file_dest

Can somebody please help getting every folder copied, empty or not?

Thank you.

August 4, 2017 at 4:01 am

Not this?

$source = 'C:\Temp\STXP\Projekter'
$target = 'C:\Temp\STXP\Test'
ls -r $source | where { $_ -match '2_ STXP Tegninger' } | cp -r -destination $target -whatif

August 4, 2017 at 8:53 am

Hi thanks for the reply.

I just googled for something to help me solve the problem. I have a very very limited knowledge about PS.

So this is me learning 🙂

I understand what you are writting, but is does not keep the parent folder and the the script can only copy the first folder it finds, the rest just error out with "allready exist".

August 4, 2017 at 2:21 pm

robocopy source destination /E

August 5, 2017 at 11:20 am


I tried to go through every step in the script I allready provided, and I found out, that this:

where {-not ($_.psiscontainer)}

Mean it does not include the empty folders. I removed that part, and now it works as it should 🙂

August 5, 2017 at 12:12 pm

Actually that excludes folders at all – not only empty ones. But again – what you're about to create with your code is actually all build in in robocopy. You don't have to invent the wheel again. It's already there. 😉

August 5, 2017 at 4:02 pm

I agree with Olaf. This is one of those right tool for the job things. Robocopy will do exactly what you are describing.