Search code examples
powershellasciispecial-characters

How to replace all files NAME in A folder with character "_" if the character ASCII encoding is greater than 128 use powershell


The example file name is PO 2171 Cresco REVISED.pdf ..... Many of these files, the file name is not standard, the space position is not fixed. The middle space is characters ASCII code greater than 128, and I want to replace characters ASCII code greater than 128 with "_" one-time.

I haven't learned Powershell yet. Thank you very much.


Solution

  • For this you are going to need regex.

    Below I'm using the ASCII range 32 - 129 (in hex \x20-\x81) to also replace any control characters:

    (Get-ChildItem -Path 'X:\TheFolderWhereTheFilesAre' -File) | 
        Where-Object { $_.Name -match '[^\x20-\x81]' } | 
        Rename-Item -NewName { $_.Name -replace '[^\x20-\x81]+', '_' }
    

    Regex Details:

    [^\x20-\x81]     Match a single character NOT in the range between ASCII character 0x20 (32 decimal) and ASCII character 0x81 (129 decimal)
       +             Between one and unlimited times, as many times as possible, giving back as needed (greedy)