PowerShell: Rename Files, Replace No-Break Space 📜

By Xah Lee. Date: . Last updated: .

Command to rename file, change no-break space to space, etc.

function xah-rename-badchars {
    # .DESCRIPTION
    # Rename each piped dir/file by replacing non-breaking space and other chars.
    # Must get arg from pipe.
    # .EXAMPLE
    # dir | xah-rename-badchars
    # .NOTES
    # Created: 2024-01-05
    # Version: 2025-04-03
    # .LINK
    # http://xahlee.info/powershell/powershell_rename_file_bad_chars.html
    process {
        if ($_ ) {
            # NARROW NO-BREAK SPACE , NO-BREAK SPACE, COMMA, RIGHT SINGLE QUOTATION MARK
            $regex = "[ , ’]"
            if ($_.name -cmatch $regex ) {
                $newname = $_.name -replace $regex, "_"
                Write-Host ($_.name , " →`n$newname")
                Rename-Item $_ $newname
            }
        }
        else { Write-Host 'no input. pipe file to me.' }
    }
}