为什么从 powershell 传递 args 在从内部脚本本身工作时会出错

Why passing args from powershell gives error while working from inside script itself

为什么从 Powershell 调用 .\MyScript.ps1 -Uninstall 会报错

+ Super-Function $Args
+                ~~~~~
    + CategoryInfo          : InvalidData : (:) [Super-Function], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Super-Function

在使用 Super-Function -Uninstall 从脚本本身调用 "Super-Function" 时,用开关替换 $Args 有效吗? 为什么在 Powershell 上复制粘贴该函数然后使用 Super-Function -Uninstall 也能正常工作?

这是MyScript的内容。ps1

function Super-Function([parameter(Mandatory=$False)][ValidateScript({Test-Path _$})][String]$var1 = ".\MyFile.ext",
                        [parameter(Mandatory=$False)][ValidateScript({Test-Path _$})][String]$var2 = "HKLM:\SOFTWARE\Wow6432Node\Publisher\SoftwareName",
                        [parameter(Mandatory=$False)][ValidateScript({([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")})][Switch]$Uninstall,
                        [parameter(Mandatory=$False)][ValidateScript({([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")})][Switch]$Install
                        )
{
}



Super-Function $Args

我看到你有一些问题。您的每个参数的 ValidateScript 都有问题。首先,可能只是一个错字,当前管道项目的字符倒退了。应该是 $_ 而不是 _$。接下来,我发现您根据几个布尔开关测试管理员角色的存在令人困惑。让我们把它移到函数内部(如果你的工作很好。确实很有意义)

最后,也是最重要的,您尝试使用 $args 进行的操作称为展开。使用 @args 将从脚本传入的参数哈希表与函数相对应。

function Super-Function{

    param(
        [parameter(Mandatory=$False)][ValidateScript({Test-Path $_})][String]$var1 = ".\MyFile.ext",
        [parameter(Mandatory=$False)][ValidateScript({Test-Path $_})][String]$var2 = "HKLM:\SOFTWARE\Wow6432Node\Publisher\SoftwareName",
        [parameter(Mandatory=$False)][Switch]$Uninstall,
        [parameter(Mandatory=$False)][Switch]$Install
    )

    # Use this to verify what has been assinged to your parameters. Will not show default values. 
    #$PSBoundParameters

    If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
        "Sure"
    } Else {
        Throw "Nope"
    }
}

Super-Function @args