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.
#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