¿Cómo puedo comprobar si una cadena es nula o está vacía en PowerShell?

Resuelto pencilCake asked hace 11 años • 16 respuestas

¿Existe una función similar incorporada IsNullOrEmptypara verificar si una cadena es nula o está vacía en PowerShell?

No pude encontrarlo hasta ahora y si hay una forma integrada, no quiero escribir una función para esto.

pencilCake avatar Dec 06 '12 14:12 pencilCake
Aceptado

Ustedes están haciendo esto demasiado difícil. PowerShell maneja esto de manera bastante elegante, por ejemplo:

> $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

> 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
Keith Hill avatar Dec 06 '2012 16:12 Keith Hill

Puedes utilizar el IsNullOrEmptymétodo estático:

[string]::IsNullOrEmpty(...)
Shay Levy avatar Dec 06 '2012 07:12 Shay Levy

Además, [string]::IsNullOrEmptypara verificar si hay valores nulos o vacíos, puede convertir una cadena a un booleano explícitamente o en expresiones booleanas:

$string = $null
[bool]$string
if (!$string) { "string is null or empty" }

$string = ''
[bool]$string
if (!$string) { "string is null or empty" }

$string = 'something'
[bool]$string
if ($string) { "string is not null or empty" }

Producción:

False
string is null or empty

False
string is null or empty

True
string is not null or empty
Roman Kuzmin avatar Dec 06 '2012 08:12 Roman Kuzmin

Si es un parámetro en una función, puedes validarlo ValidateNotNullOrEmptycomo puedes ver en este ejemplo:

Function Test-Something
{
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$UserName
    )

    #stuff todo
}
MonkeyDreamzzz avatar Mar 30 '2015 12:03 MonkeyDreamzzz