Home > Back-end >  Delete folder which has "[" and "'" using powershell
Delete folder which has "[" and "'" using powershell

Time:02-27

I want to delete folders using powershell. here is the foldername

C:\File\Coastal [new]
C:\File_new\Coastal.[new]
C:\File\Russia`s.Book
C:\File_new\Russia`s Book

It looks like ' and [] making the problem. I tried following command:

Get-ChildItem "C:\File\" | Where{$_.Name -Match "Coastal[\s\.][new]"} | Remove-Item -recurse -Force -Verbose
Get-ChildItem "C:\File_new\" | Where{$_.Name -Match "Coastal[\s\.][new]"} | Remove-Item -recurse -Force -Verbose

Get-ChildItem "C:\File\" | Where{$_.Name -Match "Russia`s[\s\.]Book"} | Remove-Item -recurse -Force -Verbose
Get-ChildItem "C:\File_new\" | Where{$_.Name -Match "Russia`s[\s\.]Book"} | Remove-Item -recurse -Force -Verbose

CodePudding user response:

In a regex, which is what the -match operator operates on as its RHS, [ is a metacharacter, as evidenced by your use of character set [\s\.] to match either a single whitespace character (\s) or a literal \. (as an aside: . doesn't need escaping inside [...]).

Therefore, you must use \[ to escape those [ instances you want to be treated as literals, notably in the [new] substring.

Alternatively - though less readably - you could use a character set to represent a literal [: [[]

  • Related