powershellpowershell-cmdlet

PowerShell - Remove-Item working weirdly when -Filter value passed


Can anyone please help me understand why "Remove-Item" cmdlet behaves weirdly when using -Filter option for removing specific list of files? Same if I passed in other cmdlets its working fine, but if use the -Filter option within the remove-item cmdlet it is not working. Please help me undersand this behavior? Thanks in advance.

get-childitem -path '.\mydir\*.txt' | remove-item  # working fine and able to understand
 
get-childitem -path '.\mydir' -Filter "*.txt" | remove-item # working fine and able to understand

remove-item -Path '.\mydir' -Filter '*.txt' # Trying to give warnng message to delete all contents within mydir folder, unable to understand, why?

Solution

  • Perhaps surprisingly, Remove-Item invariably tries to remove a targeted directory itself as well, irrespective of the presence of a -Filter argument.

    Thus, if the target directory is non-empty, you'll get the usual "The item at c:\path\to\dir has children and the Recurse parameter was not specified." confirmation prompt.

    However, adding -Recurse is best avoided, because you'll get an error message if, after removing the filter-matching files, the directory is still non-empty; conversely, if it is (then) empty, it will be removed as a whole.


    Solutions: