I need to archive a folder without some subfolders and files using PowerShell. My file/folder exclusions can occur on any level of hierarchy. To explain, here is a simple example for a WinForms VS project. If we open it in VS and build, VS creates the bin/obj subfolders with executable contents, the hidden .vs folder with user settings, and maybe *.user files for the projects included into the solution. I want to archive such a VS solution folder without all those file and folder items that can be recreated the next time when we build the solution.
It is done very easily with 7-Zip using its -x! command line switch:
"C:\Program Files\7-Zip\7z.exe" a -tzip "D:\Temp\WindowsFormsApp1.zip" "D:\Temp\WindowsFormsApp1\" -r -x!bin -x!obj -x!.vs -x!*.suo -x!*.user
However, I couldn't build an equivalent PowerShell script. The best thing I got was something like this:
$exclude = "bin", "obj", ".vs", "*.suo", "*.user"
$files = Get-ChildItem -Path $path -Exclude $exclude -Force
Compress-Archive -Path $files -DestinationPath $dest -Force
If I execute this script, the exclusion list works only for the subfolders of the first hierarchy level. If I add the -Recurse switch to the Get-ChildItem cmdlet in my script or try to filter the files/folders using Where-Object, I lose the folder hierarchy in the archive.
Is there a solution to my problem? I need to solve the problem using solely PowerShell without any external tools.