Writing a powershell script to copy files with certain extension from one folder to another

Solution 1:

Get-ChildItem allows you to list files and directories, including recursively with filename filters. Copy-Item allows you to copy a file.

There is a lot of overlap in terms of selecting the files, often Copy-Item on its own is sufficient depending on the details of what you need (eg. do you want to retain the folder structure?)

To copy all *.foo and *.bar from StartFolder to DestFolder:

Copy-Item -path "StartFolder" -include "*.foo","*.bar" -Destination "DestFolder"

If you need to preserve the folder structure things get harder because you need to build the destination folder name, something like:

$sourcePath = 'C:\StartFolder'
$destPath = 'C:\DestFolder'

Get-ChildItem $sourcePath -Recurse -Include '*.foo', '*.bar' | Foreach-Object `
    {
        $destDir = Split-Path ($_.FullName -Replace [regex]::Escape($sourcePath), $destPath)
        if (!(Test-Path $destDir))
        {
            New-Item -ItemType directory $destDir | Out-Null
        }
        Copy-Item $_ -Destination $destDir
    }

But robocopy is likely to be easier:

robocopy StartFolder DestFolder *.foo *.bar /s

In the end the way to choose will depend on the details of what's needed.

(In the above I've avoided aliases (e.g. Copy-Item rather than copy) and explicitly use parameter names even if they are positional.)

Solution 2:

I can't address the IIS portion, but the file copy while preserving the directory structure can be a lot simpler than shown in the other answers:

Copy-Item -path "StartFolder" -Recurse -Include "*.foo","*.bar" -Destination "DestFolder" -Container

The -Container argument is the magic part that will replicate the structure in the destination as it is in the source.

Tags:

Powershell