我编写了一个调用New-Service cmdlet来创建Windows服务的脚本:
New-Service -Name $Name -BinaryPathName $ExecutablePath `
-Credential $Credential -DisplayName $DisplayName `
-Description $Description -StartupType $StartupType
Run Code Online (Sandbox Code Playgroud)
我的描述有问题.如果$ 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.
Run Code Online (Sandbox Code Playgroud)
如果我完全省略-Description参数,那么命令运行时没有错误:
New-Service -Name $Name -BinaryPathName $ExecutablePath `
-Credential $Credential -DisplayName $DisplayName `
-StartupType $StartupType
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方法解决此问题:
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
}
Run Code Online (Sandbox Code Playgroud)
然而,这似乎冗长而笨重.有没有办法告诉Powershell cmdlet在调用cmdlet时忽略null或空的参数?
有点像:
New-Service -Name $Name -BinaryPathName $ExecutablePath `
-Credential $Credential -DisplayName $DisplayName `
-Description [IgnoreIfNullOrEmpty]$Description -StartupType $StartupType
Run Code Online (Sandbox Code Playgroud)
在这种情况下,参数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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1753 次 |
| 最近记录: |