Jak sprawdzić, czy łańcuch znaków jest pusty lub null w PowerShell?

Czy istnieje wbudowana funkcja podobna do IsNullOrEmpty do sprawdzania, czy łańcuch znaków jest null czy pusty, w PowerShell?

Do tej pory nie mogłem go znaleźć i jeśli istnieje wbudowany sposób, nie chcę pisać funkcji do tego.

Author: Peter Mortensen, 2012-12-06

11 answers

Możesz użyć metody statycznej IsNullOrEmpty:

[string]::IsNullOrEmpty(...)
 509
Author: Shay Levy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-06 08:00:36

Za bardzo to utrudniacie. PowerShell radzi sobie z tym dość elegancko np.:

> $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
 638
Author: Keith Hill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-18 21:44:50

Oprócz [string]::IsNullOrEmpty aby sprawdzić, czy nie ma null lub empty, możesz dodać łańcuch do wyrażenia logicznego jawnie lub w wyrażeniach logicznych:

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

Wyjście:

False
string is null or empty

False
string is null or empty

True
string is not null or empty
 45
Author: Roman Kuzmin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-06 08:30:54

Jeśli jest to parametr w funkcji, możesz go zweryfikować za pomocą ValidateNotNullOrEmpty, Jak widać w tym przykładzie:

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

    #stuff todo
}
 22
Author: Rubanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-30 12:50:43

Osobiście nie akceptuję białej spacji ($STR3) jako "nie pustej".

Gdy zmienna, która zawiera tylko spacje, jest przekazywana do parametru, często zdarza się, że wartość parametrów nie może być '$null', zamiast mówić, że może nie być spacją, niektóre polecenia Usuń mogą usunąć folder główny zamiast podfolderu, jeśli nazwa podfolderu jest "białą spacją", co jest powodem, aby nie akceptować łańcucha zawierającego spacje w wielu przypadkach.

I find this is the najlepszy sposób na to:

$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}

Empty

$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}

Empty

$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}

Pusty!! :-)

$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}

Nie pusty

 12
Author: Nico van der Stok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-18 19:26:52

Zamiennik PowerShell 2.0 dla [string]::IsNullOrWhiteSpace() to string -notmatch "\S"

("\S " = dowolny znak nie-Biały)

> $null  -notmatch "\S"
True
> "   "  -notmatch "\S"
True
> " x "  -notmatch "\S"
False

Wydajność jest bardzo bliska:

> Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace("   ")}}
TotalMilliseconds : 3641.2089

> Measure-Command {1..1000000 |% {"   " -notmatch "\S"}}
TotalMilliseconds : 4040.8453
 6
Author: Nikolay Polyagoshko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-21 12:39:05

Mam skrypt PowerShell, który muszę uruchomić na komputerze tak nieaktualnym, że nie ma [String]::IsNullOrWhiteSpace (), więc napisałem swój własny.

function IsNullOrWhitespace($str)
{
    if ($str)
    {
        return ($str -replace " ","" -replace "`t","").Length -eq 0
    }
    else
    {
        return $TRUE
    }
}
 5
Author: mhenry1384,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-30 22:00:51
# cases
$x = null
$x = ''
$x = ' '

# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}
 5
Author: Skatterbrainz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-05 02:45:59

Innym sposobem, aby to osiągnąć w czysty sposób PowerShell, byłoby zrobić coś takiego:

("" -eq ("{0}" -f $val).Trim())

To pomyślnie ocenia null, pusty łańcuch i białe znaki. Formatuję przekazaną wartość do pustego łańcucha znaków, aby obsłużyć null (w przeciwnym razie null spowoduje błąd podczas wywoływania Trim). Następnie po prostu oceń równość z pustym łańcuchem. Myślę, że nadal wolę IsNullOrWhiteSpace, ale jeśli szukasz innego sposobu, aby to zrobić, to zadziała.

$val = null    
("" -eq ("{0}" -f $val).Trim())
>True
$val = "      "
("" -eq ("{0}" -f $val).Trim())
>True
$val = ""
("" -eq ("{0}" -f $val).Trim())
>True
$val = "not null or empty or whitespace"
("" -eq ("{0}" -f $val).Trim())
>False

In z nudów, grałem z tym trochę i skróciłem (choć bardziej tajemniczo): {]}

!!(("$val").Trim())

Lub

!(("$val").Trim())
W zależności od tego, co próbujesz zrobić.
 1
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-24 23:51:14

Zauważ, że testy "if ($str)" i "IsNullOrEmpty" nie działają porównywalnie we wszystkich przypadkach: przypisanie $str=0 daje false dla obu, i w zależności od zamierzonej semantyki programu, może to spowodować zaskoczenie.

 1
Author: Steve Friedl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-11 22:36:34

Rozszerzenie odpowiedzi od Keitha Hilla (w celu uwzględnienia spacji):

$str = "     "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }

Zwraca "Empty" dla null, empty strings i strings with whitespace oraz "Not Empty" dla wszystkiego innego.

 0
Author: Zodman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-05 08:45:02