PowerShell で文字列が NULL または空でないかを確認する方法

  1. PowerShell で文字列変数が null または空でないかを確認するための条件文を使用する
  2. PowerShell で文字列変数が null または空でないかを確認するための IsNullorEmpty メソッドを使用する
  3. PowerShell で文字列変数が null または空でないかを確認するための IsNullOrWhiteSpace メソッドを使用する
  4. PowerShell で文字列変数が null または空でないかを確認するために $null 変数を使用する
PowerShell で文字列が NULL または空でないかを確認する方法

文字列は、テキストを表現するために使用される文字のシーケンスです。PowerShell では、文字列を単一引用符または二重引用符で定義できます。

PowerShell で文字列変数を操作しているとき、文字列変数が null か空かを確認する必要がある場合があります。このチュートリアルでは、PowerShell で文字列変数が null または空でないかを確認するためのさまざまな方法を紹介します。

PowerShell で文字列変数が null または空でないかを確認するための条件文を使用する

私たちは文字列変数 $string を作成しました。

$string = "Hello World"

以下の例では、PowerShell で $string 変数が null であるかどうかをチェックします。変数が null または空でない場合は最初の文を返し、変数が null または空の場合は二番目の文を返します。

if ($string) {
    Write-Host "The variable is not null."
}
else {
    Write-Host "The variable is null."
}

出力:

The variable is not null.

空の文字列値を変数に割り当てて再度確認しましょう。変数が割り当てられていない場合、それもまた null 値を持ちます。

$string = ""
if ($string) {
    Write-Host "The variable is not null."
}
else {
    Write-Host "The variable is null."
}

出力:

The variable is null.

空白文字は null の文字列値とは見なされません。

PowerShell で文字列変数が null または空でないかを確認するための IsNullorEmpty メソッドを使用する

.NET クラス System.String を使用して、PowerShell で文字列変数が null または空であるかを確認できます。IsNullorEmpty() メソッドは、指定された文字列が空または null であるかどうかを示します。

文字列が空であれば True を返し、空でなければ False を返します。

[string]::IsNullOrEmpty($new)

出力:

True

では、変数に文字列値を割り当てましょう。

$new = "asdf"
[string]::IsNullOrEmpty($new)

出力:

False

PowerShell で文字列変数が null または空でないかを確認するための IsNullOrWhiteSpace メソッドを使用する

PowerShell では、文字列変数が null または空でないかを確認するために IsNullOrWhiteSpace メソッドも使用できます。このメソッドは PowerShell 3.0 以降でのみ機能します。

変数が null または空であるか、空白文字を含んでいる場合は True を返します。そうでない場合、出力に False を表示します。

[string]::IsNullOrWhiteSpace($str)

出力:

True

文字列値を変数に割り当てます。

$str = "Have a nice day."
[string]::IsNullOrWhiteSpace($str)

出力:

False

PowerShell で文字列変数が null または空でないかを確認するために $null 変数を使用する

$null は PowerShell の自動変数の 1つで、NULL を表します。-eq パラメータを使用して、文字列変数が $null と等しいかどうかを確認できます。

変数が $null と等しい場合は True を返し、変数が $null と等しくない場合は False を返します。

$str -eq $null

出力:

False

上記のいずれかの方法を使用して、PowerShell で文字列変数が null または空でないかを簡単に判断できます。

チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
著者: Rohan Timalsina
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

関連記事 - PowerShell String