Skip to content

Remove-Item -Recurse with an -Include or -Filter argument mistakenly tries to remove the directory itself #16153

Open

Description

Prerequisites

Steps to reproduce

Note:

When you combine Remove-Item -Recurse with either -Include or -Filter, only those items inside the target directory subtree that match the pattern(s) are removed, as intended.

However, if you invoke such a command with . as the input path, i.e. from inside the target directory, the command fails, as an attempt is seemingly made to delete the directory itself:

# Switch to a temporary directory.
Push-Location -ea Stop ($tmpDir = (New-Item -Type Directory -Force (Join-Path Temp:/ $PID)).FullName)

try {

$null = New-Item -Force 1.txt, sub/2.txt

Remove-Item . -Recurse -Filter *.txt

$null = New-Item -Force 1.txt, sub/2.txt

Remove-Item . -Recurse -Include *.txt

} finally {
  # Clean up.
  Pop-Location; Remove-Item $tmpDir -Recurse
}

Expected behavior

Both Remove-Item calls should succeed and delete all *.txt files from the current dir's subtree.

Actual behavior

Both commands fail.

Error details

Cannot remove the item at '<full-path-of-current-dir>' because it is in use.

Environment data

PowerShell Core 7.2.0-preview.9

The problem also affects Windows PowerShell.

Visuals

No response

Activity

  1. 237dmitry commented on Sep 24, 2021

    @237dmitry

    Both commands fail.

    Remove-Item -Path .\* -Filter *.txt -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -Path .\* -Include *.txt -Recurse
    

    Success for both commands. Try input path .\*
    7.1.4

  2. mklement0 commented on Sep 24, 2021

    @mklement0
    ContributorAuthor

    237dmitry, yes, that is a viable workaround (* will do) - but it shouldn't be necessary, and that's what this issue is about.

  3. mklement0 commented on Nov 7, 2023

    @mklement0
    ContributorAuthor

    237dmitry, I don't know whether things changed, but as of v7.3.10 / v7.4.0-rc.1, the workaround with * (or .\*) not only doesn't work, but blindly removes all items, i.e. ignores the filter - see:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-FileSystem-Providerspecific to the FileSystem providerIssue-BugIssue has been identified as a bug in the productNeeds-TriageThe issue is new and needs to be triaged by a work group.WG-Cmdletsgeneral cmdlet issues

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions