get files from subfolders but exclude some folders.

Hi,

trying to exclude all directories and sub-directories in c:\users that contain corp.

for example exclude searching c:\users\corp-1; c:\users\corp-a and many other random names with corp.

i have this but unable to tune it to exclude those folders.

$Extensions=".cmd",".bat",".vbs",".js"
Get-ChildItem -Path C:\Users -Recurse -Include $Extensions | Where-Object {$_.FullName -inotcontains “CORP”}

tried $_.directory / directoryname / parent.

thanks for any assistance.

 

Get-ChildItem has -Exclude parameter. That will help you here.

Get-Help Get-ChildItem -Parameter Exclude

[pre]

Get-ChildItem -Path C:\Users -Recurse -Include $Extensions | Where-Object FullName -notmatch CORP

or

Get-ChildItem -Path C:\Users -Recurse -Include $Extensions -Exclude CORP

[/pre]

Both the commands above meet your requirements.

And it will exclude the complete directory itself if it contains CORP in it.

Also, the contains comparison operator is to check against a collection (array):

PS C:\Users\rasim> 'red','white','blue' -contains 'white'

True

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6

-match is regular expression and -like is a wildcard search (e.g. ‘CORP’)

thank you for the replies.

the exclude does not solve what I am working on.

I need to exclude all directories and sub directories where the parent is c:\users\corp-a ; corp-<random> [so do not scan parent folder and sub directories under it. ]

I should have clarified better.

Thanks.

Hi

I can get my list of user directories but unable to get it into the last get-childitem to only do it on that output.

Any thoughts?

 

$UserDirExtensions=".cmd",".bat",".vbs",".js"
$pn=(Get-ChildItem -Path C:\Users | Select-Object fullname | Where-Object -Property fullname -NotLike corp)

return $pn

Get-ChildItem -path $pn -Recurse -Include $UserDirExtensions <-- this fails :frowning:

 

Thanks.

You have to look at what type of object is being passed through the pipeline. $PM returns as object type (directory) and get-childitem parameter “-path” only accept object type “String” ByValue or ByPropertName. An easy trick to convert the object is to use the -expandproperty parameter which will change your object type to a “String”:

$UserDirExtensions=".cmd",".bat",".vbs",".js"
$pn=(Get-ChildItem -Path C:\Users | Select-Object -expand fullname | Where-Object -Property fullname -NotLike corp)

return $pn

Get-ChildItem -path $pn -Recurse -Include $UserDirExtension

You can verify the object type by running:
PS> $pn | gm

TypeName: System.String

Unfortunately, .contains() and -contains are different things.

$Extensions="*.cmd","*.bat","*.vbs","*.js"
Get-ChildItem -Path C:\Users -Recurse -Include $Extensions | 
  Where-Object { -not $_.FullName.contains("CORP","OrdinalIgnoreCase") }  # case insensitive