tech.guitarrapc.cóm

Technical updates

PowerShellでパラメータ入力を必須にしたい

自作関数のパラメーターを必須入力にしたいとき、いくつかやり方はあります。 しかしPowerShel 1.0の情報が、何故かいまだに見受けられるので記事にしておきます。

PowerShell 1.0では

デフォルトで例外をはきます。

function hoge{
    Param (
        [string]$sample = $(throw "-sample is required.")
    )

    return $sample
}

PowerShell 2.0 以降

PowerShell 2.0以降は[parameter()]madatory属性を付けるのが主流です。

function hoge{
    Param (
        [parameter(mandatory=$true)]
        [string]$sample
    )

    return $sample
}

正直$trueは邪魔。

PowerShell 3.0以降なら

同様ですが$trueを外せます。

function hoge{
    Param (
        [parameter(mandatory)]
        [string]$sample
    )

    return $sample
}

ほかのやり方

もしstringに変換出来るならIsNullOrEmptyもあります。

function hoge{
    Param (
        [string]$sample
    )

    if (-not([string]::IsNullOrEmpty($sample)))
    {
        return $sample
    }
}

あるいはIsNullOrWhiteSpaceもあります。

function hoge{
    Param (
        [string]$sample
    )

    if (-not([string]::IsNullOrWhiteSpace($sample)))
    {
        return $sample
    }
}

mandatory属性を付けると、パラメーター指定を忘れると関数が実行できません。 もし必須じゃないけど、パラメーターチェックしたいなら関数内部でnullや空文字チェックすることになります。

状況に応じて使い分けましょう。