Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename-item: Cannot rename because item at ... does not exist

I am lost with simple rename-item. Need to change names of folders to "01", "02", "03"... Tried everything but at the end I get this "Item doesn't exist". Sorry for dumb question but I am looking for a solution all day.

PS C:\Users\admin> 
$nr = 1

Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}

Rename-Item : Cannot rename because item at 'ert' does not exist.
At line:3 char:23
+ Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
 
Rename-Item : Cannot rename because item at 'ukh' does not exist.
At line:3 char:23
+ Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
 
Rename-Item : Cannot rename because item at 'yph' does not exist.
At line:3 char:23
+ Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
like image 279
Drone_Drone Avatar asked Sep 06 '25 15:09

Drone_Drone


1 Answers

user14915444's helpful answer has provided the crucial pointer:

The problem is that Windows PowerShell situationally stringifies Get-ChildItem (dir) output objects by file name rather than by full path, necessitating the use of $_.FullName rather than just $_; the problem has been fixed in PowerShell [Core] v6.1+ - see this answer for details.

However, in your case the problem can be avoided altogether, by piping the Get-ChildItem output directly to Rename-Item, using a delay-bind script block, which also speeds up the operation:

[ref] $nr = 1
Get-ChildItem E:Data-test | Rename-Item -NewName { '{0}' -f $nr.Value++ } -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

Note the use of a [ref] variable, which enables incrementing the sequence number across input objects from inside the delay-bind script block. This is necessary, because delay-bind script blocks run in a child scope of the caller's scope - unlike the script blocks passed to ForEach-Object (%) and Where-Object (?).
See GitHub issue #7157 for a discussion of this discrepancy.

like image 87
mklement0 Avatar answered Sep 09 '25 19:09

mklement0