Rename Item - PowerShell
Overview
Rename-Item is a versatile PowerShell command used to rename files, folders, and other items in the Windows file system. It allows you to easily change the names of items, move them to different locations, and perform other operations related to file management.
Syntax
Rename-Item -Path <Path> -NewName <NewName> [-Force] [-WhatIf] [-PassThru]
Parameters
- -Path: Specifies the full path to the item you want to rename. This can be a file, folder, or any other item in the file system.
- -NewName: Specifies the new name you want to give the item.
- -Force: Overwrites the existing item if it already exists with the new name.
- -WhatIf: Reports what would happen if the command were executed without actually making any changes.
- -PassThru: Returns the renamed item as an object.
Options/Flags
There are no additional options or flags available for Rename-Item.
Examples
Simple Rename
Rename-Item -Path "C:\Users\JohnDoe\Documents\myfile.txt" -NewName "newfile.txt"
Rename with Overwrite
Rename-Item -Path "C:\Users\JohnDoe\Documents\myfile.txt" -NewName "newfile.txt" -Force
Rename and Move
Rename-Item -Path "C:\Users\JohnDoe\Documents\myfile.txt" -NewName "newfile.txt" -NewLocation "C:\Users\JohnDoe\Desktop"
Common Issues
Item Already Exists
If the new name you specify already exists in the same location, you will get an error unless you use the -Force option.
Insufficient Permissions
If you do not have sufficient permissions to rename the item, you will get an access denied error.
Invalid Path
If the path you specify is invalid or does not exist, you will get a path not found error.
Integration
Rename-Item can be used in conjunction with other PowerShell commands to perform complex file management tasks. For example, you can use it in a ForEach-Object loop to rename multiple items in a directory:
Get-ChildItem -Path "C:\Users\JohnDoe\Documents" | ForEach-Object { Rename-Item -Path $_.FullName -NewName "newname_$_.Extension" }
Related Commands
- Get-ChildItem: Gets a list of items in a directory.
- Move-Item: Moves an item to a new location.
- New-Item: Creates a new item in the file system.