Author Posts

November 16, 2017 at 7:31 pm

Can someone please explain how this works? I noticed that if I remove the count method, no result is returned at all, so that's really what I'm most curious about.

$excluded = @(
'C:\temp\Test folder',
'C:\temp\Test Folder2',
'*test*'
)
Get-ChildItem c:\temp -Recurse| Where {$name = $_.Fullname; ($excluded | Where 
{$name -like $_}).count -eq 0}|remove-item -force -Recurse

November 16, 2017 at 8:13 pm

If I got it right you could make your life easier ...

Get-ChildItem -Path c:\temp -Recurse -Exclude $excluded

... should do the trick either

November 17, 2017 at 12:06 am

Exclude omits child objects based on the Name not the FullName. That would be great if I didn't need to use the fullname.

November 17, 2017 at 12:47 am

Here's how it breaks down.

#First an array is created of the paths to exclude
$excluded = @(
'D:\tmp\Test folder',
'D:\tmp\Test Folder2',
'*test*'
)

# Get-ChildItem is used to get the complete directory listing of D:\tmp
# Then each result is piped to Where-Object
Get-ChildItem D:\tmp -Recurse | 

# One at a time, Where-Object tests for a True or False result based on
# the code within its curly braces
Where-Object {
    # The first thing that is done is Fullname for the current object
    # is assigned to the variable $name
    $name = $_.Fullname
    
    # Then the $exclude array values are piped into another Where-object
    # and checked to see if the $name of the current directory object's
    # Fullname is like each of the Exclude array's elements
    #
    # If, for example the current Fullname is "D:\tmp\PoSh"
    # it does:
    #  "D:\tmp\PoSh" -like 'D:\tmp\Test folder'
    #  "D:\tmp\PoSh" -like 'D:\tmp\Test Folder2'
    #  "D:\tmp\PoSh" -like '*test*'
    # Of course all of those would result False so none of them
    # would be returned and the count would equal 0.
    # The count equaling 0 would return True, so the intial
    # Where-Object would evalutate True and "D:\tmp\PoSh" would
    # be sent down the pipeline to the next step
    #
    # If, for example the current Fullname is "D:\tmp\Test Folder2"
    # it does:
    #  "D:\tmp\Test Folder2" -like 'D:\tmp\Test folder'
    #  "D:\tmp\Test Folder2" -like 'D:\tmp\Test Folder2'
    #  "D:\tmp\Test Folder2" -like '*test*'
    # In this case the second and third would evaluate True and
    # would be returned and the count would equal 2.
    # The count equaling 2 would return False on the
    # .count -eq 0 part, so the intial Where-Object would evalutate
    # False and "D:\tmp\Test Folder2" would not be sent down the
    # pipeline to the next step
    ($excluded | Where {$name -like $_}).count -eq 0
} |

# For all of the items sent to the pipeline by the previous step
# remove them forcefully and recursively
remove-item -force -Recurse