JKelley
JKelley

Reputation: 69

Renaming File in Powershell

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.

Upvotes: 1

Views: 1778

Answers (2)

henrycarteruk
henrycarteruk

Reputation: 13237

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"

Upvotes: 3

Joel
Joel

Reputation: 6211

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

Upvotes: 2

Related Questions