有条件地排除空或空字符串的 cmdlet 参数

8
我已经编写了一个脚本,调用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   
}

然而,这种方法似乎冗长而且笨拙。在调用cmdlet时,是否有一种告诉Powershell忽略空值参数的方法呢?类似于以下代码:
New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description [IgnoreIfNullOrEmpty]$Description -StartupType $StartupType
1个回答

17

参数展开,在概念性的about_Splatting帮助主题中有所记录,[1]是这种情况下的最佳方法:

# 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

[1] chribonn也建议参考这篇博客文章来了解splattin.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接