8
votes

Comment supprimer les accents dans PowerShell?

J'ai un script qui crée des utilisateurs dans Microsoft Exchange Server et Active Directory. Donc, bien que ce soit common que les noms d'utilisateur ont des accents ou ± en Espagne, je souhaite les éviter pour le nom d'utilisateur de ne pas causer d'incompatibilités dans les anciens systèmes.

Alors, comment puis-je nettoyer une chaîne comme celle-ci? xxx

comme ça? : xxx


0 commentaires

7 Réponses :


8
votes

Eh bien, je peux vous aider avec une partie du code .....

J'ai utilisé ceci récemment dans le projet AC # pour dépouiller des adresses électroniques: p>

    static string RemoveDiacritics(string input)
    {
        string inputFormD = (input ?? string.Empty).Normalize(NormalizationForm.FormD);
        StringBuilder sb = new StringBuilder();

        for (var i = 0; i < inputFormD.Length; i++)
        {
            UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(inputFormD[i]);
            if (uc != UnicodeCategory.NonSpacingMark)
            {
                sb.Append(inputFormD[i]);
            }
        }

        return (sb.ToString().Normalize(NormalizationForm.FormC));
    }


2 commentaires

+1 Smart Snippet, je l'ai converti sur PowerShell, cela fonctionne comme prévu merci.


Cela fonctionne assez bien dans PowerShell. Vraiment merci pour le partage: D



21
votes

Selon la réponse de la propriété intellectuelle, voici la version PowerShell.

Rhone
Basil
Abo

Grasantorma


0 commentaires

7
votes

Une autre traduction PowerShell de @ip pour les codeurs non C #; O)

function Remove-Diacritics 
{
  param ([String]$sToModify = [String]::Empty)

  foreach ($s in $sToModify) # Param may be a string or a list of strings
  {
    if ($sToModify -eq $null) {return [string]::Empty}

    $sNormalized = $sToModify.Normalize("FormD")

    foreach ($c in [Char[]]$sNormalized)
    {
      $uCategory = [System.Globalization.CharUnicodeInfo]::GetUnicodeCategory($c)
      if ($uCategory -ne "NonSpacingMark") {$res += $c}
    }

    return $res
  }
}

Clear-Host
$name = "Un été de Raphaël"
Write-Host (Remove-Diacritics $name )
$test = ("äâûê", "éèà", "ùçä")
$test | % {Remove-Diacritics $_}
Remove-Diacritics $test


0 commentaires

2
votes

Une autre solution ... rapidement "réutiliser" votre c # dans PowerShell (C # Code Crédits perdue quelque part sur le net).

Add-Type -TypeDefinition @"
    using System.Text;
    using System.Globalization;

    public class Utils
    {
        public static string RemoveDiacritics(string stIn)
        {
            string stFormD = stIn.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();

            for (int ich = 0; ich < stFormD.Length; ich++)
            {
                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
                if (uc != UnicodeCategory.NonSpacingMark)
                {
                    sb.Append(stFormD[ich]);
                }
            }
            return (sb.ToString().Normalize(NormalizationForm.FormC));
        }
    }
"@ | Out-Null

[Utils]::RemoveDiacritics("ABC-abc-ČŠŽ-čšž")


0 commentaires

3
votes
PS> [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding(1251).GetBytes("Ramón"))
Ramon
PS>

1 commentaires

Échoue pour certains personnages, par exemple æ × þ ° ± ß ... . Un vrai ancien anglais Exemple : retour avant ?? Re M? R? E? E? Si appliqué à avant ðære mærðe ...



1
votes

Au lieu de créer un StringBuilder et une boucle sur des caractères, vous pouvez simplement utiliser -replace sur la chaîne NFD pour supprimer les marques de combinaison:

function Remove-Diacritics {
param ([String]$src = [String]::Empty)
  $normalized = $src.Normalize( [Text.NormalizationForm]::FormD )
  ($normalized -replace '\p{M}', '')
}


0 commentaires

5
votes

Avec l'aide des exemples ci-dessus, j'utilise cette "one-liner:" dans tuyau (testé uniquement dans Win10): xxx

résultat: xxx < / pré>


0 commentaires