有条件地排除null或空的cmdlet参数

时间:2017-03-29 01:46:36

标签: powershell cmdlet

我编写了一个调用New-Service cmdlet来创建Windows服务的脚本:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description $Description -StartupType $StartupType

我的说明有问题。如果$ Description是一个空字符串或$ null,我会收到一个错误:

Cannot validate argument on parameter 'Description'. 
The argument is null or empty. Provide an argument that is not null or empty, 
and then try the command again.

如果我完全省略-Description参数,那么命令运行时没有错误:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -StartupType $StartupType

我可以通过以下方法解决这个问题:

if ($Description)
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -Description $Description -StartupType $StartupType
}
else
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -StartupType $StartupType   
}

然而,这似乎冗长而笨重。有没有办法告诉Powershell cmdlet在调用cmdlet时忽略null或空的参数?

有些事情:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description [IgnoreIfNullOrEmpty]$Description -StartupType $StartupType

1 个答案:

答案 0 :(得分:6)

在这种情况下,

Parameter splatting是最好的方法:

# Create a hashtable with all parameters known to have values.
# Note that the keys are the parameter names without the "-" prefix.
$htParams = @{
  Name = $Name
  BinaryPathName = $ExecutablePath
  Credential = $Credential
  DisplayName = $DisplayName
  StartupType = $StartupType
}

# Only add a -Description argument if it is nonempty.
if ($Description) { $htParams.Description = $Description }

# Use the splatting operator, @, to pass the parameters hashtable.
New-Service @htParams