Home > Software engineering >  PowerShell - Using portuguese characters in the name of folders
PowerShell - Using portuguese characters in the name of folders

Time:06-27

I'm writing a script that moves a lot of folders from a source to destination path. The thing is that not every folder should go to the same directory. So I have .txt files with a list of folder names and move them to the appropriate destination based on the .txt file.

The issue here is when the folder's name has special charaters like [á, à, ã, â, Ç, ç, etc...] it crashes and says that the folder that contains those characters does not exist

I'm building the path and moving them with the following code:

foreach ($folderName in $file_list)
{   
    try{
        if( $folderName.StartsWith("#")){
            $pastaMae = $folderName.substring(1)
            Write-Host "A criar pasta '$pastaMae'"
            New-Item -Path $Destination -Name $pastaMae -ItemType "directory" -ErrorAction Stop | Out-Null
            $newDestination = $Destination $pastaMae "\"
            Write-Host "Pasta Mae: $newDestination"
        }else {
            Write-Host "A mover a pasta: $folderName"
            Move-Item -Path [System.IO.DirectoryInfo]$Path$folderName -Destination $newDestination -ErrorAction Stop
            Write-Host "Pasta movida com sucesso!!" -ForegroundColor Green 
        }
    }catch {
        Write-Host "Ocorreu um erro ao mover a pasta '$folderName'" -ForegroundColor Red
        $erro = 1
        $msgErro  = " $folderName ||"
    }

}

This is what shows in the terminal. (Those folders are named 'Ação Social' and 'Educação')

enter image description here

Is there a way to work arround this problem?

CodePudding user response:

Your output suggests that the text file you're reading the folder paths from is a UTF-8 file without a BOM, which Windows PowerShell assumes to be ANSI-encoded instead, resulting in mis-decoded strings.
(PowerShell (Core) 7 now fortunately defaults to (BOM-less) UTF-8, consistently).

To avoid this problem, read your file explicitly as a UTF-8 file; e.g.:

Get-Content -Encoding utf8 -LiteralPath folder_list.txt

For more information about default character encodings in both PowerShell editions, see this answer.

  • Related