Copy folders excluding files in PowerShell

PowerShell Script Wallpaper

In this new post, I will give you a script to copy folders excluding files in PowerShell. First, I want to explain the scenario I’m facing.


So, I have some Microsoft Windows Servers on premise and on IIS I have configured applications for developer and production environments. Because the servers are in the company environment and they are not exposed to the internet, I can’t use CD/CI with Azure DevOps, for example. I have to do the deployment manually.

So, in the file system, I have one folder for each project and that contains:

  • one folder for the developer environment
  • another one for QA and Testers
  • another one for production
Folder structure for environment - Copy folders excluding files in PowerShell
Folder structure for environment

When the application in the development environment is ready, I want to copy all the files from the developer folder to the tester folder but I want to exclude some files or directory such as:

  • appsettings for each environment
  • web.config
  • the folder for imports under wwwroot\Uploads\Imports

In each folder, I want to have the specific appsettings.json and web.config for the environment and I don’t want to change.

Then, because copying files and folders manually can cause issues, I’m looking for a script in PowerShell for that.

The script

$binSolutionFolder = 'C:\Projects\Portal\Dev\'
$deployFolderDir = 'C:\Projects\Portal\Test\'
$excludeFiles = @('appsettings.json', 'appsettings.Development.json', 'appsettings.Release.json', 'web.config') 
$excludeFolders = @('wwwroot\\Uploads\\Imports')
$excludeFoldersRegex = $excludeFolders -join '|'

Get-ChildItem -Path $binSolutionFolder -Recurse -Exclude $excludeFiles | 
where { $_.FullName.Replace($binSolutionFolder, "") -notmatch $excludeFoldersRegex } |
Copy-Item -Destination {
    if ($_.PSIsContainer) {
        Join-Path $deployFolderDir $_.Parent.FullName.Substring($binSolutionFolder.length -1)
    else {
        Join-Path $deployFolderDir $_.FullName.Substring($binSolutionFolder.length -1)
} -Force


So, this is the end of how to copy folders excluding files in PowerShell that you can use it for deployment, for example.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.