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

powershell

I would like to write a powershell script that gets the following parameters as input:
Folder to copy from, extensions allows, folder to copy to and a boolean indicating if the change should restart IIS, username and password.
What cmdlets should I be looking at considering that I am copying to a remote server?
How do I read the parameters into variables?
How do I restart IIS?

Cosidering that I might want to copy multiple folders, how do I write a powershell script that invokes a powershell script?

Best Answer

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.)