1

I'm trying to rename a file so I can remove the brackets within the name:

Example: [Example] Test File (Servers).xls renamed to Example Test File (Servers).xls

My issue is that when I run this, it returns an error saying

Rename-Item -Path '.\'[Example'] Test File (Servers).xls' -NewName "Example Test File (Servers).xls"

Rename-Item : An object at the specified path C:\Users\Documents\PowerShell\[Example] Test File (Servers).xls does not exist

The other issue is that when I run:

C:\Users\Documents\PowerShell> Get-ChildItem -Path "[Example] Test File (Servers).xls" 

This runs successfully with no errors, so I know PowerShell is finding this file with no problems. At this point, I don't know why this isn't working because it can find the file with one command, and not with the other.

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
JKelley
  • 69
  • 1
  • 1
  • 7
  • Check out this question: https://stackoverflow.com/q/21008180/847990 You have to use double back-ticks in order to escape those brackets in the file name. –  Jun 21 '18 at 14:19

2 Answers2

3

You can use LiteralPath instead of Path if you're using a modern version of Powershell (v4+ iirc).

It can deal with special characters like [] without having to escape them.

Rename-Item -LiteralPath ".\[Example] Test File (Servers).xls" -NewName "Example Test File (Servers).xls"
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
2

Try:

For changing multiple-filenames in the same directory:

Dir | Rename-Item -NewName {$_.name -replace "[Example]","Example"}

Filename before:

[Example] Test File (Servers).xls

Filename after:

Example Test File (Servers).xls

Joel
  • 5,732
  • 4
  • 37
  • 65
  • Is there an explicit reason why you use the alias instead of the normal `Get-Childitem`? – Paxz Jun 21 '18 at 14:51
  • @Paxz get-childitem is just an alias for dir. see documentation. – Joel Jun 21 '18 at 14:56
  • 1
    The documentation states the opposite (https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-6) – Paxz Jun 21 '18 at 15:00
  • @Paxz potato potato, get-childitem is an alias for dir. And vise versa. They both do the same is what i meant. Dir is just the abbreviated version. Eg. `get-ChildItem - recursive` == `Dir -r` – Joel Jun 21 '18 at 17:18