How to rename a file using PowerShell


We can make use of the Rename-Item cmdlet to rename files in PowerShell. You can find this cmdlet under Microsoft.PowerShell.Management module.

Syntax:

Rename-Item
      -LiteralPath <String>
      [-NewName] <String>
      [-Force]
      [-PassThru]
      [-Credential <PSCredential>]
      [-WhatIf]
      [-Confirm] 
      [<CommonParameters>]

Let's take a look at a few examples,


Example 1: One-Liner

PS> Rename-Item ./data_2023_draft.csv -NewName ./data_2023.csv 

Rename with Path

PS> Rename-Item -Path D:/files/data_2023_draft.csv -NewName D:/files/data_2023.csv

Example 2: Rename a file using Script

<# 

   Code2care.org PowerShell Examples

   Script to rename a file. 

#>

$oldFileName = Read-Host "Enter File Name with Absolute Path To Rename "

$newFileName = Read-Host "Enter a new name for the file "

Rename-Item -Path $oldFileName -NewName $newFileName
PS> Enter File Name with Absolute Path To Rename: /Users/c2ctechtv/Desktop/file1.txt

Enter a new name for the file: data.txt

Rename a file using PowerShell Script

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap