why does Powershell tell me that my file represents a path when I try to rename it?

0

I have a filename "+1.txt" that I wish to rename to "+2.txt"

My Powershell script is:

$old = "\+1"
$new = "\+2"
Get-ChildItem | Rename-Item -NewName {$_.name -replace $old, $new }

This returns:

powershell : Rename-Item : Cannot rename the specified target, because it represents a path

How can I correct this?

user

Posted 2017-03-18T07:17:11.423

Reputation: 53

The backslash in the string is the problem on Windows that's a character found in a path and it's not possible to have it in the name of a filename – Ramhound – 2017-03-18T07:42:13.740

Answers

3

The correct escape character in PowerShell is ` (the back tick).

E.g. you would write the following to get a string with a newline:

$newline = "`n" 

In addition, at least in a test, I didn't need to escape it. So just Rename-Item "+1.txt" "+2.txt" worked. A try using -replace required the backslash in the first argument but not the second. So $new = "+2" should work. The reason is that the first argument for -replace might be a regular expression. So the term needs a literal + that isn't handled specially. The second term is handeled as a literal string so you don't need any special escaping or similar.

Seth

Posted 2017-03-18T07:17:11.423

Reputation: 7 657

0

-replace uses regular expressions, but you don't need to manually escape chars.
Get-ChildItem iterates all items in the current path, you've to specify a name

$old = "+1.txt"
$new = "+2.txt"
Get-ChildItem $old -file| 
  Rename-Item -NewName {$_.FullName -replace [regex]::escape($old), $new }

or use a where to -match only pattern.

$old = "+1.txt"
$new = "+2.txt"
Get-ChildItem | 
  where Name -match [regex]::escape($old)|
    Rename-Item -NewName $new 

LotPings

Posted 2017-03-18T07:17:11.423

Reputation: 6 150

What would be the advantage of using [regex]::escape instead of escaping it by hand? For more complex expression that might be quite useful. In your second example you could just change -NewName to $new as you''re doing the match to find the file beforehand. – Seth – 2017-03-18T12:12:14.507

@Seth, the advantage of using [regex]::escape is that he doesn't violate the Don't Repeat Yourself Principle (DRY), which is a very important principle in creating quality software. – dangph – 2017-03-20T02:12:35.877