Rename multiple files with a script not working.

Thomas Mahoney 1 Reputation point
2021-12-27T17:33:15.16+00:00

I'm trying to trim down the names of files in a specific folder using a script I wrote, using all of the proper syntax. My code:

    set-location "C:\Users\TMahoney1979\Desktop\Test"

    foreach ($fn in get-childitem -name)
    {
        $fn
        $splitname = @($fn -split " - ",2)
        $splitname
        $newname = $splitname[1]
        $newname
        rename-item $newname -path ".\$oldname"
    }

This script should turn:

Testfile - Doc1
Testfile - Doc2
Testfile - Doc3

Into:

Doc1
Doc2
Doc3

Instead, I get this error for each file:

Rename-Item : Cannot rename the item at '.\' because it is in use.
At C:\Users\TMahoney1979\Documents\PowerShell\TrimFileName.ps1:10 char:16

  • rename-item <<<< $newname -path ".\$oldname"
  • CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOp
    erationException
  • FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.R
    enameItemCommand

Does anyone know how to fix this? Thanks in advance.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Thomas Mahoney 1 Reputation point
    2021-12-27T23:59:48.25+00:00

    Ha, Ha! Sorry guys! I just realized I tried to reference a variable in my script that wasn't there, and that was why it wasn't working. It was just a rookie screw-up, and I'm sorry I bothered you with it. Anyway this is how the code is supposed to look:

    set-location "C:\Users\TMahoney1979\Desktop\Test"
    
    foreach ($fn in get-childitem -name)
    {
        $splitname = @($fn -split " - ",2)
        $newname = $splitname[1]
        rename-item -path "C:\Users\TMahoney1979\Desktop\Test\$fn" -newname $newname -force
        # Notice the variable $fn in the previous line, instead of $oldname, which was incorrect.
    }
    
    0 comments No comments

  2. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2021-12-28T00:13:01.107+00:00

    Hi @

    even if you fixed it yourself .... this should work as well ;-)

    Set-Location "C:\Junk\d"
    Get-ChildItem -File | ForEach-Object {
        Rename-Item -Path $_.FullName -NewName ($_.Name).split(" - ")[1] -WhatIf
        }
    

    Just remove the -Whatif


    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.