Reputation: 141462
When I run the following command:
Rename-Item some\long\path\fileName.txt some\long\path\newName.txt
I receive the following error message:
Cannot rename the specified target, because it represents a path or device name.
I've tried wrapping the paths in quotes and that doesn't succeed either.
Upvotes: 22
Views: 25238
Reputation: 2478
In case you came across this question after trying to batch rename files as follows:
Get-ChildItem | Rename-Item -NewName {$_ -replace 'Old','New'} # MAY FAIL!
You might get the following error:
Rename-Item: Cannot rename the specified target, because it represents a path or device name
As an example, assume you have a file C:\MyFullPath\MyFile.txt
and run the following commands:
cd C:\MyFullPath
ls | ren -NewName {$_ -replace 'My','Your'}
The command is using $_
as content on which to operate. $_
provides the full path of the file, not only its name. The command now tries to find the pattern My
in C:\MyFullPath\MyFile.txt
.
The file matches the specified pattern My
and so does the parent path of the file. Hence, the command tries to rename the full file name to C:\YourFullPath\YourFile.txt
. That is, it also tries to rename the parent path of the file. That is what causes the error.
The solution is to use $_.Name
instead of $_
.
Here's the proper way to rename files:
Get-ChildItem | Rename-Item -NewName {$_.Name -replace 'Old','New'}
# or short (don't use this in scripts):
ls | ren -n {$_.Name -replace 'Old','New'}
Upvotes: 0
Reputation: 4769
For me the issue was different
The file name was the issue:
I have tried to put the following file name:
Old_2016-02-17T13:52:28_Stage1.txt
But only After changing it to:
Old_17022016_0154_Stage1.txt
it worked
Upvotes: 7
Reputation: 141462
For the second argument, just use the new name not the full path. That is, do this:
Rename-Item some\long\path\fileName.txt newName.txt
From the docs, it says of -NewName<String>
Enter only a name, not a path and name. If you enter a path that is different from the path that is specified in the Path parameter, Rename-Item generates an error.
Upvotes: 45