Powershell 默认参数集不起作用。错误

标签 powershell default-parameters parameter-sets

我正在尝试使用参数集并使用默认参数集。但是默认参数集似乎对我不起作用。任何帮助深表感谢。我可以轻松地使用带有默认操作的验证集,但我想知道我在这里做错了什么。

Param([cmdletbinding(DefaultParametersetname="Directory")] 
      [Parameter(Mandatory=$false,ParameterSetName="File")]
      [switch]$file, 
      [Parameter(Mandatory=$false,ParameterSetName="Directory")]  
      [switch]$directory,

[Parameter(Mandatory=$false,ParameterSetName="File")] 
[Parameter(Mandatory=$false,ParameterSetName="Directory")] 
[string]$Source,
[Parameter(Mandatory=$true,ParameterSetName="File")]  
[Parameter(Mandatory=$true,ParameterSetName="Directory")] 
[string]$DestinationPath, 
[Parameter(Mandatory=$false,ParameterSetName="Directory")] 
[Parameter(Mandatory=$false,ParameterSetName="File")]
[array]$Servers

PS C:\> Test-Script -Source "c:\somedirectory" -DestinationPath "c:\someotherdirectory"

error as shown below in the image

Test-Script : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ Test-Script -Source "c:\somedirectory" -DestinationPath "c:\someotherdirectory"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Test-Script], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Test-Script

最佳答案

CmdletBinding() attribute需要在 param block 之外,紧接在 param 关键字之前,否则它将被简单地忽略:

[CmdletBinding(DefaultParametersetname="Directory")]
Param(
    [Parameter(Mandatory=$false,ParameterSetName="File")]
    [switch]$file, 

    [Parameter(Mandatory=$false,ParameterSetName="Directory")]
    [switch]$directory,

    [Parameter(Mandatory=$false,ParameterSetName="File")]
    [Parameter(Mandatory=$false,ParameterSetName="Directory")]
    [string]$Source,

    [Parameter(Mandatory=$true,ParameterSetName="File")]
    [Parameter(Mandatory=$true,ParameterSetName="Directory")]
    [string]$DestinationPath,

    [Parameter(Mandatory=$false,ParameterSetName="Directory")]
    [Parameter(Mandatory=$false,ParameterSetName="File")] 
    [array]$Servers
)

关于Powershell 默认参数集不起作用。错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384019/

相关文章:

powershell - 如何在powershell中使用system.tuple?

c#-6.0 - 如何在符合 CLS 的程序集中使用 CallerMemberName

Powershell 参数集和可选参数

powershell - 有没有办法定义一个无参数的powershell参数集?

powershell - 如何支持多个互斥的参数?

azure - Powershell - Get-AzureADAuditSignInLogs 多个筛选器

PowerShell:什么是 System.IO.StreamWriter 和 System.Diagnostics.ProcessStartInfo?

iis - 用于在 IIS 中查找当前绑定(bind)的过期证书的 Powershell 脚本

python - 在python函数中传递带有varargs的默认参数

c# - 用户定义的结构转换作为函数的默认参数