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.
Solution 3:
The only solution that worked for me is
Copy-Item -path 'c:\SourceFolder\*.foo' -destination 'c:\DestFolder'
Other solutions that use -Include
parameter didn't work.
Solution 4:
As some people mentioned here -Include doesn't work.
To make it work with nested folders I used two steps approach: 'filter' + delete empty folders
#copy with folder structure
Copy-Item -path $source -Recurse -Filter "*.foo" -Destination $destination -Container
#remove empty folders
dir $destination -Directory -Recurse |
%{ $_.FullName} |
sort -Descending |
where { !@(ls -force $_) } |
rm