Paolo Rossi
Paolo Rossi

Reputation: 2510

Powershell copy directories and contents where name match with filter

I'm trying to use powershell to copy some directories where name match with filter.
First of all I delete all the directories that match in the destination path, alfter I try to copy source directories and contents but I've a problem because are copied only files inside directories and subdirectories and not the directories names and structures.

$source="F:\origin"
$destination="F:\dest"
$filter="@"

# Remove dirs @ 
Get-ChildItem -Path $destination -Recurse | 
Where-Object { $_.DirectoryName -match $filter } | 
remove-item -Recurse

# Copy dirs and all contents
Get-ChildItem -Path $source -Recurse | 
Where-Object { $_.DirectoryName -match $filter } | 
Copy-Item -Destination $destination

How can I do This ?
Thank you

EDIT

F:\origin\@test\index.php
F:\origin\@test1\index1.php
F:\origin\@test1\sub1\subindex1.php
F:\origin\no_consider\index1.php

Expected output

F:\dest\@test\index.php
F:\dest\@test1\index1.php
F:\dest\@test1\sub1\subindex1.php

Upvotes: 2

Views: 401

Answers (1)

moore1emu
moore1emu

Reputation: 496

a couple small tweaks seems to have done the trick. replaced some double quotes with single quotes, added a Recurse at the end of the one line and change DirectoryName to Name for the first one. LEt me know if this works:

$source='c:\origin'
$destination='c:\dest'
$filter="@"

# Remove dirs @ 
Get-ChildItem -Path $destination -Recurse | 
Where-Object { $_.Name -match $filter } | 
remove-item -Recurse


# Copy dirs and all contents
Get-ChildItem -Path $source | 
Where-Object { $_.Name -match $filter } | 
Copy-Item -Destination $destination -Recurse -Force

Upvotes: 2

Related Questions