Skip to main content

PowerShell Rename-Item: Complete Guide for Files & Folders [2024]

6 min read
powershell files rename-item rename file operations batch operations folders

Master PowerShell Rename-Item—the essential cmdlet for renaming files, folders, and registry items. This comprehensive guide covers single operations, batch renaming, pattern matching, and real-world automation scenarios.

Table of Contents

  1. What is Rename-Item?
  2. Why Rename Files Programmatically?
  3. Rename-Item Syntax
  4. Rename Single File
  5. Rename Multiple Files
  6. Pattern-Based Renaming
  7. Batch Renaming with Regex
  8. Date-Based Naming
  9. Add Prefix or Suffix
  10. Change File Extensions
  11. Rename Folders
  12. Hidden and Read-Only Files
  13. Error Handling
  14. Force Renaming
  15. Undo Renaming
  16. Common Patterns
  17. Common Mistakes
  18. Best Practices
  19. Troubleshooting
  20. Real-World Examples
  21. Conclusion

What is Rename-Item? {#what-is-rename-item}

Rename-Item is a PowerShell cmdlet that changes the name of files, folders, and other items in the file system or registry. It’s non-destructive—the file content remains unchanged, only the name changes.

Key Features:

  • ✅ Rename files, folders, registry keys
  • ✅ Batch rename multiple items
  • ✅ Pattern-based renaming with regex
  • ✅ Add prefixes/suffixes
  • ✅ Change file extensions
  • ✅ Force rename read-only/hidden items
  • ✅ Error handling and confirmation

Why Rename Files Programmatically? {#why-rename}

Common Scenarios:

  • Organizing files by date or project
  • Standardizing naming conventions
  • Adding prefixes/suffixes (archive_, backup_, etc.)
  • Removing spaces from filenames
  • Batch renaming hundreds of files
  • Extracting year/month from created date

Rename-Item Syntax {#syntax}

Basic Syntax

Rename-Item -Path <original-path> -NewName <new-name>

Parameters

ParameterPurposeRequiredExample
-PathCurrent file/folder pathYes"C:\Temp\file.txt"
-NewNameNew name (name only, no path)Yes"newname.txt"
-ForceOverwrite/rename read-onlyNo$true
-PassThruReturn renamed objectNo$true
-ConfirmPrompt before renamingNo$true
-WhatIfShow what would happenNo$true

Rename Single File {#rename-single}

Example 1: Basic Rename

Rename-Item -Path "C:\Temp\log.txt" -NewName "log_backup.txt"

Example 2: Using Full Path

$oldPath = "C:\Temp\report.xlsx"
$newName = "report_2024.xlsx"

Rename-Item -Path $oldPath -NewName $newName
Get-Item -Path "C:\Temp\report_2024.xlsx"  # Verify

Output:

Directory: C:\Temp
Mode   Name
----   ----
-a---  report_2024.xlsx

Example 3: With PassThru (Return Renamed Item)

$result = Rename-Item -Path "C:\Temp\old.txt" -NewName "new.txt" -PassThru
Write-Output "Renamed to: $($result.Name)"

Output:

Renamed to: new.txt

Example 4: Rename and Get Properties

Rename-Item -Path "C:\Temp\file.txt" -NewName "archive.txt" -PassThru |
    Select-Object Name, FullName, CreationTime, LastWriteTime

Rename Multiple Files {#rename-multiple}

Example 1: Rename by Extension

# Rename all .bak files to .old
Get-ChildItem -Path "C:\Logs\*.bak" |
    Rename-Item -NewName {$_.Name -replace '.bak$', '.old'}

# Verify
Get-ChildItem -Path "C:\Logs\*.old"

Example 2: Rename All in Directory

# Change all .txt files to .log
Get-ChildItem -Path "C:\Temp" -Filter "*.txt" -File |
    Rename-Item -NewName {$_.Name -replace '.txt$', '.log'}

Example 3: Batch Rename with Counter

$counter = 1
Get-ChildItem -Path "C:\Backup" -File |
    Sort-Object -Property Name |
    ForEach-Object {
        $newName = "backup_$counter.bak"
        Rename-Item -Path $_.FullName -NewName $newName
        $counter++
    }

Result:

backup_1.bak
backup_2.bak
backup_3.bak
...

Example 4: Remove Spaces from Filenames

# Replace spaces with underscores
Get-ChildItem -Path "C:\Documents" -File |
    Where-Object { $_.Name -match ' ' } |  # Only files with spaces
    Rename-Item -NewName {$_.Name -replace ' ', '_'}

Before: My Report 2024.docx After: My_Report_2024.docx


Pattern-Based Renaming {#pattern-renaming}

Example 1: Rename Based on Pattern

# Rename files matching a pattern
Get-ChildItem -Path "C:\Reports" -Filter "Report_*.xlsx" |
    Rename-Item -NewName {$_.Name -replace "Report_", "Archive_"}

Example 2: Extract and Rename

# Extract date from filename and reorganize
# Before: 20240205_monthly_report.xlsx
# After: Report_Feb_2024.xlsx

Get-ChildItem -Path "C:\Reports" -Filter "202402*.xlsx" |
    Rename-Item -NewName { $_.Name -replace '20240205_monthly_', 'Report_Feb_2024_' }

Example 3: Prefix Common Pattern

# Add "FINAL_" prefix to all PDFs
Get-ChildItem -Path "C:\Documents" -Filter "*.pdf" |
    Rename-Item -NewName {"FINAL_" + $_.Name}

Batch Renaming with Regex {#regex-renaming}

Example 1: Extract Numbers

# Rename logs: app_log_12345.txt → log_12345.txt
Get-ChildItem -Path "C:\Logs" -Filter "app_log_*.txt" |
    Rename-Item -NewName {$_.Name -replace '^app_', ''}

Example 2: Normalize Naming Convention

# Convert camelCase to snake_case
# Before: myFileName.txt
# After: my_file_name.txt

function Convert-CamelToSnake {
    param([string]$Input)
    $Input -replace '(?<!^)(?=[A-Z])', '_' -replace '([A-Z])', {$_.Value.ToLower()}
}

$files = Get-ChildItem -Path "C:\Files" -File
foreach ($file in $files) {
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.Name)
    $extension = $file.Extension
    $newBaseName = Convert-CamelToSnake -Input $baseName
    Rename-Item -Path $file.FullName -NewName "$newBaseName$extension"
}

Example 3: Complex Pattern Matching

# Rename with complex rules
# Before: data_backup_2024_02_05.zip
# After: backup-2024-02-05.zip

Get-ChildItem -Path "C:\Backups" -Filter "*.zip" |
    Rename-Item -NewName {
        $name = $_.Name
        # Remove 'data_' prefix and 'backup_' part, change underscores to hyphens
        $name -replace '^data_backup_', '' -replace '(.+)\.zip$', 'backup-$1.zip'
    }

Date-Based Naming {#date-naming}

Example 1: Add Current Date to Filename

$date = Get-Date -Format "yyyyMMdd"
Get-ChildItem -Path "C:\Reports\report.xlsx" |
    Rename-Item -NewName {"report_$date.xlsx"}

# Result: report_20240205.xlsx

Example 2: Use File Creation Date

Get-ChildItem -Path "C:\Documents" -Filter "*.docx" |
    Rename-Item -NewName {
        $createdDate = $_.CreationTime.ToString("yyyyMMdd")
        "$createdDate`_$($_.Name)"
    }

Result:

20240103_mydocument.docx
20240205_report.docx

Example 3: Rename by Last Modified Date

# Rename with last modified date
Get-ChildItem -Path "C:\Logs" -Filter "*.log" |
    Rename-Item -NewName {
        $modDate = $_.LastWriteTime.ToString("yyyy-MM-dd")
        "$modDate`_$($_.Name)"
    }

Add Prefix or Suffix {#prefix-suffix}

Example 1: Add Prefix

# Add "archive_" prefix to old files
Get-ChildItem -Path "C:\OldFiles" -File |
    Rename-Item -NewName {"archive_" + $_.Name}

Example 2: Add Suffix Before Extension

# Add "_backup" before file extension
Get-ChildItem -Path "C:\Data" -Filter "*.txt" |
    Rename-Item -NewName {
        $baseName = [System.IO.Path]::GetFileNameWithoutExtension($_)
        $extension = $_.Extension
        "$baseName`_backup$extension"
    }

Result:

report_backup.txt
data_backup.csv

Example 3: Add Suffix for Backup

# Common pattern: Add .bak extension
Get-ChildItem -Path "C:\Config" -Filter "*.ini" |
    Rename-Item -NewName {$_.Name + ".bak"}

Change File Extensions {#change-extension}

Example 1: Single Extension Change

# Change .bmp to .jpg
Get-ChildItem -Path "C:\Images\photo.bmp" |
    Rename-Item -NewName {$_.Name -replace '\.bmp$', '.jpg'}

Example 2: Batch Extension Change

# Convert all .doc to .docx
Get-ChildItem -Path "C:\Documents" -Filter "*.doc" |
    Rename-Item -NewName {$_.Name -replace '\.doc$', '.docx'}

Example 3: Capitalize Extension

# Change .txt to .TXT (for compatibility with legacy systems)
Get-ChildItem -Path "C:\Data" -Filter "*.txt" |
    Rename-Item -NewName {$_.Name -replace '\.txt$', '.TXT'}

Rename Folders {#rename-folders}

Example 1: Rename Single Folder

Rename-Item -Path "C:\Users\OldName" -NewName "NewName"

Example 2: Rename Multiple Folders

# Add "archive_" prefix to folders
Get-ChildItem -Path "C:\Projects" -Directory |
    Rename-Item -NewName {"archive_" + $_.Name}

Example 3: Rename with Date

$year = (Get-Date).Year
Get-ChildItem -Path "C:\Projects" -Directory |
    Rename-Item -NewName {$_.Name + "_$year"}

Hidden and Read-Only Files {#hidden-readonly}

Example 1: Use -Force Parameter

# Rename read-only file
Rename-Item -Path "C:\Protected\config.txt" -NewName "config_new.txt" -Force

Example 2: Batch Rename Read-Only Files

# Get all read-only files and rename
Get-ChildItem -Path "C:\System32" -Attributes ReadOnly -ErrorAction SilentlyContinue |
    Rename-Item -NewName {"readonly_" + $_.Name} -Force

Example 3: Remove Read-Only Attribute First

# Remove read-only, then rename
$file = Get-ChildItem -Path "C:\Temp\locked.txt" -ErrorAction SilentlyContinue
if ($file.Attributes -band [IO.FileAttributes]::ReadOnly) {
    $file.Attributes = $file.Attributes -band -bnot [IO.FileAttributes]::ReadOnly
}
Rename-Item -Path $file.FullName -NewName "unlocked.txt"

Error Handling {#error-handling}

Example 1: Try-Catch

try {
    Rename-Item -Path "C:\Temp\file.txt" -NewName "newfile.txt" -ErrorAction Stop
    Write-Output "Successfully renamed"
} catch {
    Write-Error "Failed to rename: $_"
}

Example 2: Check Before Renaming

$sourcePath = "C:\Temp\file.txt"
$newName = "newfile.txt"

if (Test-Path -Path $sourcePath) {
    Rename-Item -Path $sourcePath -NewName $newName
    Write-Output "Renamed successfully"
} else {
    Write-Error "Source file not found: $sourcePath"
}

Example 3: Avoid Duplicates

$targetPath = "C:\Temp\newname.txt"

if (Test-Path -Path $targetPath) {
    Write-Error "Target name already exists: $targetPath"
} else {
    Rename-Item -Path "C:\Temp\file.txt" -NewName "newname.txt"
}

Force Renaming {#force-rename}

Example 1: Overwrite Existing

# Force rename even if target exists
Rename-Item -Path "C:\Temp\old.txt" -NewName "new.txt" -Force

Example 2: WhatIf (Preview)

# See what would happen without making changes
Get-ChildItem -Path "C:\Logs\*.txt" |
    Rename-Item -NewName {$_.Name -replace '.txt$', '.log'} -WhatIf

Output:

What if: Performing the operation "Rename File" on target "Item: C:\Logs\app.txt Destination: app.log".

Example 3: Confirm Prompt

# Prompt before each rename
Get-ChildItem -Path "C:\Temp" -Filter "*.txt" |
    Rename-Item -NewName {$_.Name -replace '.txt$', '.log'} -Confirm

Undo Renaming {#undo-rename}

Example 1: Rename Back

# If you need to undo, rename back to original
Rename-Item -Path "C:\Temp\newname.txt" -NewName "oldname.txt"

Example 2: Backup Before Renaming

# Create list of original names before batch rename
$files = Get-ChildItem -Path "C:\Data" -File
$renameMap = @{}

foreach ($file in $files) {
    $newName = $file.Name -replace ' ', '_'
    $renameMap[$newName] = $file.Name  # Map: new -> old
    Rename-Item -Path $file.FullName -NewName $newName
}

# Save map for recovery
$renameMap | Export-Clixml -Path "C:\rename_map.xml"

# Later: reverse the renaming if needed
$renameMap = Import-Clixml -Path "C:\rename_map.xml"
foreach ($newName in $renameMap.Keys) {
    Rename-Item -Path "C:\Data\$newName" -NewName $renameMap[$newName]
}

Common Patterns {#common-patterns}

Pattern 1: Remove Spaces

$_.Name -replace ' ', '_'      # Spaces to underscores
$_.Name -replace ' ', ''       # Remove spaces

Pattern 2: Change Extension

$_.Name -replace '\.old$', '.new'
$_.Name -replace '\.[^.]*$', '.log'  # Replace any extension with .log

Pattern 3: Add Prefix/Suffix

"PREFIX_$($_.Name)"                  # Add prefix
"$($_.BaseName)_SUFFIX$($_.Extension)"  # Add suffix before extension

Pattern 4: Date-Based

"$(Get-Date -Format 'yyyyMMdd')_$($_.Name)"  # Add today's date
"$($_.CreationTime.ToString('yyyy-MM-dd'))_$($_.Name)"  # Add creation date

Common Mistakes {#common-mistakes}

❌ Mistake 1: Including Path in NewName

# WRONG: NewName should be just the filename
Rename-Item -Path "C:\Temp\file.txt" -NewName "C:\Temp\newfile.txt"

# RIGHT: Only filename
Rename-Item -Path "C:\Temp\file.txt" -NewName "newfile.txt"

❌ Mistake 2: Not Escaping Special Characters

# WRONG: Dollar sign interpreted as variable
Rename-Item -Path "C:\Temp\file.txt" -NewName "file$new.txt"

# RIGHT: Escape with backtick
Rename-Item -Path "C:\Temp\file.txt" -NewName "file`$new.txt"

❌ Mistake 3: Forgetting File Extension

# WRONG: Removes extension
Rename-Item -Path "C:\Temp\file.txt" -NewName "newfile"

# RIGHT: Include extension
Rename-Item -Path "C:\Temp\file.txt" -NewName "newfile.txt"

❌ Mistake 4: Target Name Already Exists

# WRONG: Will fail if target exists
Rename-Item -Path "C:\Temp\file1.txt" -NewName "file2.txt"  # If file2.txt exists

# RIGHT: Check first
if (-not (Test-Path "C:\Temp\file2.txt")) {
    Rename-Item -Path "C:\Temp\file1.txt" -NewName "file2.txt"
}

Best Practices {#best-practices}

Before Batch Renaming:

  • Use -WhatIf to preview changes
  • Test with small batch first
  • Backup important files
  • Log the renaming operations

Code Quality:

  • Use descriptive variable names
  • Add error handling with try-catch
  • Check if file/folder exists first
  • Use -PassThru to verify results

Performance:

  • Filter files using -Filter (faster than pipe to Where-Object)
  • Use -Recurse carefully (can be slow on large directories)
  • Sort before renaming if order matters

Maintenance:

  • Document renaming rules
  • Keep rename mappings for recovery
  • Test on copies before production
  • Implement logging for audit trail

Troubleshooting {#troubleshooting}

Issue: “Cannot rename to target—already exists”

  • Cause: File with new name already exists
  • Solution: Use -Force or check/delete existing file first

Issue: “Access denied”

  • Cause: File is read-only or locked
  • Solution: Use -Force or close file in other applications

Issue: “Cannot find path”

  • Cause: File doesn’t exist
  • Solution: Use Test-Path to verify before renaming

Real-World Examples {#real-world-examples}

Example 1: Organize Downloads by Date

# Rename downloads: file.zip → 2024-02-05_file.zip
Get-ChildItem -Path "$env:USERPROFILE\Downloads" -File |
    Rename-Item -NewName {
        $date = $_.CreationTime.ToString("yyyy-MM-dd")
        "$date`_$($_.Name)"
    }

Example 2: Archive Old Log Files

$archivePath = "C:\Logs\Archive"
if (-not (Test-Path $archivePath)) { New-Item -ItemType Directory $archivePath | Out-Null }

Get-ChildItem -Path "C:\Logs" -Filter "*.log" -File |
    Where-Object { (Get-Date) - $_.LastWriteTime | Select-Object -ExpandProperty Days -gt 30 } |
    Rename-Item -NewName {
        $newName = "archive_$(Get-Date -Format 'yyyyMMdd')_$($_.Name)"
        Move-Item -Path $_.FullName -Destination "$archivePath\$newName"
        $newName
    } -PassThru

Example 3: Batch Convert Document Names

# Convert Word docs to naming standard: CamelCase → snake_case
Get-ChildItem -Path "C:\Documents" -Filter "*.docx" |
    Where-Object { $_.Name -match '[A-Z]' } |  # Has capital letters
    Rename-Item -NewName {
        $baseName = [System.IO.Path]::GetFileNameWithoutExtension($_)
        $extension = $_.Extension
        # Convert CamelCase to snake_case
        ($baseName -replace '(?<!^)(?=[A-Z])', '_' -replace '([A-Z])', {$_.Value.ToLower()}) + $extension
    }

Conclusion

Rename-Item is a powerful tool for organizing and managing files programmatically. Whether renaming a single file or orchestrating complex batch operations with pattern matching, PowerShell provides the flexibility needed for any renaming scenario.

Key Takeaways:

  • Use -NewName with scriptblock {...} for dynamic renaming
  • Always use -WhatIf before batch operations
  • Include error handling and validation
  • Document complex renaming patterns for maintenance
  • Use -PassThru to verify successful renames

File Management Operations

Directory Operations

File Information & Properties

Date & Time Operations

Data Selection & Filtering

String & Pattern Operations

Display & Formatting

Control Flow & Logic

Variables & Collections

Output & Export

File Content Operations

Functions & Automation

  • PowerShell Functions - Create reusable functions
  • PowerShell Measure-Object - Calculate statistics
  • PowerShell Group-Object - Group files

Comprehensive Guides