4

I am new to powershell. I need to copy the whole folder structure from source to destination with filenames matching a pattern. I am doing the following. But it just copies the content in the root directory. For example

"E:\Workflow\mydirectory\file_3.30.xml"

does not get copied.

Here is my sequence of commands.

PS F:\Tools> $source="E:\Workflow"
PS F:\Tools> $destination="E:\3.30"
PS F:\Tools> $filter = [regex] "3.30.xml"
PS F:\Tools> $bin = Get-ChildItem -Path $source | Where-Object {$_.Name -match $filter}
PS F:\Tools> foreach ($item in $bin) {Copy-Item -Path $item.FullName -Destination $destination}
PS F:\Tools> foreach ($item in $bin) {Copy-Item -Path $item.FullName -Destination $destination -recurse}

1 Answer 1

7

You have a few problems. First of all, add -Recurse switch to Get-ChildItem so all files matching filter will be found no matter how deep. Then you need to recreate the original directory structure as you can't copy a file to a directory which doesn't exist. The -ea 0 switch on md will make sure errors are ignored when creating new dir - the following will do the trick:

$source="E:\Workflow"
$destination="E:\3.30"
$filter = [regex] "3.30.xml"
$bin = Get-ChildItem -Recurse -Path $source | Where-Object {$_.Name -match $filter}
foreach ($item in $bin) {
    $newDir = $item.DirectoryName.replace($source,$destination)
    md $newDir -ea 0
    Copy-Item -Path $item.FullName -Destination $newDir
}
Sign up to request clarification or add additional context in comments.

1 Comment

I know this is a long time after, but thank you very much for creating such a good tutorial on how to do this. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.