Home > Software engineering >  Powershell Get-ChildItem Exclude Default Windows Folders
Powershell Get-ChildItem Exclude Default Windows Folders

Time:11-15

I want to search for files with .2fa extension on remote computers. I can find the files I want, but it takes a long time to get to the second computer because it scans all windows files.

I tried the -exclude and where arguments but they do not work.

Could you please help me? Thanks.

$ServerList = Import-Csv 'C:\PC.CSV'

$result = foreach ($pc in $ServerList.barkod) {
$exclude = '*ProgramData*','*Program Files*','*Program Files (x86)*','*Windows*'.'*winupdate*'
$sourcepath = 'c$'

Get-ChildItem -Path \\$pc\$sourcepath -Recurse | Where-Object { $_.Name -like "*.2fa" } |
where {$_.name -notin $Exclude}

}

$result

I tried

-Exclude $exclude -where {$_.name -notin $Exclude}

CodePudding user response:

-exclude doesn't work with subdirectories or -filter:

Get-ChildItem -Path \\$pc\$sourcepath\ -exclude $exclude | 
  get-childitem -recurse -filter *.2fa

CodePudding user response:

Since you are looking for files with a certain extension, use the -Filter parameter. This will be the fastest option to search for only .2fa files, disregarding all others. (Filter works on the Name property)

If you want to search the C: drive, you are bound to hit Access Denied exceptions and because to exclude a list of foldernames using post-process with a Where-Object clause, Get-ChildItem will try and search in these folders you need to apend -ErrorAction SilentlyContinue to the command

$exclude = 'ProgramData','Program Files','Program Files (x86)','Windows'.'winupdate'
# create a regex string you can use with the `-notmatch` operator
# each item will be Regex Escaped and joined together with the OR symbol '|'
$excludeThese = ($exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'

$ServerList = (Import-Csv 'C:\PC.CSV').barkod
$sourcepath = 'c$'

$result = foreach ($pc in $ServerList) {
    Get-ChildItem -Path "\\$pc\$sourcepath" -Filter '*.2fa' -File -Recurse -ErrorAction SilentlyContinue | 
    Where-Object {$_.DirectoryName -notmatch $excludeThese}
}

$result
  • Related