Powershell 有条件地排除null或空的cmdlet参数
我编写了一个脚本,用于调用New Service cmdlet来创建Windows服务:Powershell 有条件地排除null或空的cmdlet参数,powershell,cmdlet,Powershell,Cmdlet,我编写了一个脚本,用于调用New Service cmdlet来创建Windows服务: New-Service -Name $Name -BinaryPathName $ExecutablePath ` -Credential $Credential -DisplayName $DisplayName ` -Description $Description -StartupType $StartupType 我对描述有问题。如果$Description是空字符串或$null,
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时,是否有任何方法可以让Powershell cmdlet忽略null或空的参数
大致如下:
New-Service -Name $Name -BinaryPathName $ExecutablePath `
-Credential $Credential -DisplayName $DisplayName `
-Description [IgnoreIfNullOrEmpty]$Description -StartupType $StartupType
概念帮助主题中记录的参数设置方法,[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] 还建议介绍splatting。@TessellingHeckler:我刚刚尝试过,谢谢,但仍然会出现同样的错误。我想这是因为它在检查空字符串和$nulls。@TessellatingHeckler:我想我会使用splatting,因为它只不过是将参数直接传递给新服务,没有多少代码。谢谢。谢谢,@chribonn-我已经修复了断开的链接,并将你的博客链接添加到了答案中。