Powershell PS独占参数设置开关-丢失参数的错误消息更好?
我编写了一个短函数来检索已安装vpn客户端上的信息/状态-它有4个开关来指定返回的信息:Powershell PS独占参数设置开关-丢失参数的错误消息更好?,powershell,parameters,Powershell,Parameters,我编写了一个短函数来检索已安装vpn客户端上的信息/状态-它有4个开关来指定返回的信息: Function Get-ConnectInfo() { [CmdletBinding()] Param( [Parameter(ParameterSetName='Binaries')][switch]$BinaryPaths, [Parameter(ParameterSetName='Status')][switch]$ConnectionStatus,
Function Get-ConnectInfo() {
[CmdletBinding()]
Param(
[Parameter(ParameterSetName='Binaries')][switch]$BinaryPaths,
[Parameter(ParameterSetName='Status')][switch]$ConnectionStatus,
[Parameter(ParameterSetName='Profiles')][switch]$Profiles,
[Parameter(ParameterSetName='Version')][switch]$Version
)
#
Begin {
# Some code here
}
#
Process {
Switch ($PSBoundParameters.Keys) {
BinaryPaths {
Write-Host "BinaryDetail"
}
Version {
Write-Host "VersionInfo"
}
Profiles {
Write-Host "Profile Info"
}
ConnectionStatus {
Write-Host "Connection Status"
}
}
}
}
问题是,如果您不传递任何参数,这是错误消息:
Get-ConnectInfo : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ Get-ConnectInfo
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ConnectInfo], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Get-ConnectInfo
是否有一种优雅的方法将此错误更改为“未指定参数”之类的信息量更大的错误?您可以:
- 设置默认参数集
- 如果在函数中设置了自定义错误,则抛出自定义错误并返回:
- 设置默认参数集
- 如果在函数中设置了自定义错误,则抛出自定义错误并返回:
显然,PowerShell Core 6支持自定义错误消息及其
Validate*
属性。不过,我没有看到任何关于这方面的官方文件。我确信这不能满足主观优雅的要求。显然,PowerShell Core 6支持带有Validate*
属性的自定义错误消息。不过,我没有看到任何关于这方面的官方文件。我相信这不符合主观优雅的要求。
function Get-ConnectInfo() {
[CmdletBinding(DefaultParameterSetName='noOptions')]
Param(
[Parameter(ParameterSetName='Binaries')][switch]$BinaryPaths,
[Parameter(ParameterSetName='Status')][switch]$ConnectionStatus,
[Parameter(ParameterSetName='Profiles')][switch]$Profiles,
[Parameter(ParameterSetName='Version')][switch]$Version
)
#
Begin {
if($PSCmdlet.ParameterSetName -eq 'noOptions'){
throw 'Please pass a switch argument of either "-Version", "-Profiles", "-ConnectionStatus", or "-BinaryPaths"'
return
}
}
#
Process {
Switch ($PSBoundParameters.Keys) {
BinaryPaths {
Write-Host "BinaryDetail"
}
Version {
Write-Host "VersionInfo"
}
Profiles {
Write-Host "Profile Info"
}
ConnectionStatus {
Write-Host "Connection Status"
}
}
}
}