Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming and Moving Files Powershell

Tags:

powershell

I want to rename .rpt files from dr_network to dr_network_10yr. Then create the folder Output (if it does not exist) and move the files to the folder.

The renaming of the files works however cannot move the files. Note the files should be relative pathing.

Thank you for your assistance.

New-Item .\Output -force
Get-ChildItem *.rpt | 
    ForEach-Object{
        Rename-Item $_ ($_.Name -replace 'dr_network_','dr_network_10yr')
        Move-Item $_($_.Fullname -destination ".\Output")
}
like image 299
tfitzhardinge Avatar asked Mar 08 '26 15:03

tfitzhardinge


1 Answers

Your example does not work for several reasons. You need to specify a type on New-Item

New-Item .\Output -force -ItemType Directory

You then get all *.rpt files and iterate through them. The rename syntax is correct but you have issues with the move syntax. Powershell has no idea what you are trying to do. You are also renaming a file and then attempting to move a file that no longer exists as you have renamed it. The following should help:

#Tell powershell its a directory
New-Item .\Output -force -ItemType Directory
Get-ChildItem *.rpt | 
    ForEach-Object{
        #store the new name as a variable
        $newName = $_.FullName -replace 'dr_network_','dr_network_10yr'
        #rename the file
        Rename-Item $_ $newName
        #move the newly renamed file to the Output folder
        Move-Item $newName -destination ".\Output"
}
like image 55
StephenP Avatar answered Mar 10 '26 07:03

StephenP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!