Home > Back-end >  How to exclude folders from a directory using power shell script
How to exclude folders from a directory using power shell script

Time:12-02

I have directory which contains few folders, I wanted to exclude folder names which contains a string. I tried with following command using wild card option (in the exclude variable) which is not working in exclude section.

$dirName = "C:\Users\xyz\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
Get-ChildItem "C:\Users\xyz\Desktop\powershellScripts\monitors\*" -Directory | Where-Object{$_.Name -notin $excludes} | Copy-Item -Destination $dirName -Recurse -Force

Example:- Let say I have folders in monitors directory like SQLMonitor, CSTK123_SQLMonitor, TEST_SQLMonitor , SQLMonitor_abc ... now I wanted to exclude these folders using wildcards

How to achieve this in PowerShell.

CodePudding user response:

$dirName = "C:\Users\sj01856\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
Get-ChildItem "C:\Users\sj01856\Desktop\powershellScripts\monitors\*" -Directory | Where-Object{$_.Name -notmatch ($excludes -join "|")} | Copy-Item -Destination $dirName -Recurse -Force

You need to match against the array and not take the asterisks literally.

CodePudding user response:

You should be able to do all of this within the Get-ChildItem call, with an -Excludes parameter, which takes an array of patterns to exclude:

$dirName = "C:\Users\xyz\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
Get-ChildItem "C:\Users\xyz\Desktop\powershellScripts\monitors" -Directory -Exclude $excludes | 
  Copy-Item -Destination $dirName -Recurse -Force
  • Related