powershellfile-renamerename-item-cmdlet

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

Solution

  • Your script works fine. (At least the first variation.) You can't run it but once because you rename the file it is working with (i.e. "Data-Test"). I just created a Data-Test file on my E: drive and ran your script without issue once. Then, on second attempt, it couldn't work because it worked the first time.

    If you are working with the contents of a directory named "Data-Test," you need to append your $_ with .FullName. (EX: Rename-Item $_.FullName -NewName ...)

    See image:
    See image

    If it still doesn't work, ensure that you have a file/folder named "Data-Test" in the CWD of your E: drive. Placing a backslash in the location will guarantee you are working in the root. (EX: E:\Data-Test)