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
    # Version: 2024-01-05

    Process {
        if (-not $MyInvocation.ExpectingInput) { Write-Host "No pipeline received."; return ; }
        # NARROW NO-BREAK SPACE , NO-BREAK SPACE, COMMA, RIGHT SINGLE QUOTATION MARK
        $regex = "[   ,’]"
        if ($_.name -cmatch $regex ) {
            $newName = $_.name
            $newName = $newName -replace $regex, "_"
            Write-Host ("$_ → $newName")
            Rename-Item $_ $newName
        }
    }
}