PowerShell : tester une chaîne vide ou nulle
Comportement des chaînes $null, vides et d'espaces dans une condition if et avec IsNullOrEmpty.
En PowerShell, une chaîne $null ou vide est évaluée à $false dans une condition, alors qu'une chaîne contenant seulement un espace est évaluée à $true.
Tester une chaîne vide
La méthode .NET dédiée :
[string]::IsNullOrEmpty($str)
Comportement dans une condition if
$str1 = $null
if ($str1) { 'not empty' } else { 'empty' } # empty
$str2 = ''
if ($str2) { 'not empty' } else { 'empty' } # empty
$str3 = ' '
if ($str3) { 'not empty' } else { 'empty' } # not empty
$str4 = 'asdf'
if ($str4) { 'not empty' } else { 'empty' } # not empty
Combiner avec -and
if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' } # one or both empty
if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' } # neither empty
Remarques
- Une chaîne d'espaces n'est ni
$nullni vide : pour la traiter comme vide, utiliser[string]::IsNullOrWhiteSpace($str).