3. File System Management Tasks - Powershell
3.6 Renaming Files
the Rename-Item cmdlet renames a file or directory.
itโs not possible to move items with the
Rename-Itemcmdlet. use theMove-Itemcmdlet instead.
Rename-Item -Path "C:\Users\xle0x\test.txt" -NewName "new_temp.txt"
to rename multiple files at once, use a script like this:
# Define the folder containing the files
$FolderPath = "C:\FilesToRename"
# Fetch all files in the folder
$Files = Get-ChildItem -Path $FolderPath -File
# Loop through each file and rename it
foreach ($File in $Files) {
# Define the new file name (modify this logic as needed)
$NewName = "Renamed_" + $File.Name
# Rename the file
Rename-Item -Path $File.FullName -NewName $NewName
Write-Host "Renamed $($File.Name) to $NewName"
}
Example Output:
If the folder contains:
File1.doc
File2.doc
The script will rename them to:
Renamed_File1.doc
Renamed_File2.doc