首页 文章

显示所有Powershell脚本参数默认变量

提问于
浏览
2

假设我有一个像这样的Powershell脚本TestParameters.ps1,带有两个强制命名参数和两个可选参数:

[CmdletBinding()]
Param (
[Parameter(Mandatory=$True)]
[string] $AFile = "C:\A\Path",

[Parameter(Mandatory=$True)]
[ValidateSet("A","B","C", "D")]
[string] $ALetter = "A",

[Parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]
[string] $Optional1 = "Foo",

[Parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]
[string] $Optional2 = "Bar"
)

echo "Hello World!"
$psboundparameters.keys | ForEach {
    Write-Output "($_)=($($PSBoundParameters.$_))"
}

假设我像这样调用脚本:

.\TestParameters.ps1 `
    -AFile                 "C:\Another\Path" `
    -ALetter               "B"

产生输出:

Hello World!
(AFile)=(C:\Another\Path)
(ALetter)=(B)

Powershell设置变量$ Optional1和$ Optional2 ...但是我如何轻松地将它们显示在屏幕上,就像我使用$ PSBoundParameters一样?

我做 not 只想在每次有脚本时写下面的内容:

Write-Host $AFile
Write-Host $ALetter
Write-Host $Optional1
Write-Host $Optional2

笔记:

  • $ args似乎只包含未绑定的参数,而不是默认参数

  • $ MyInvocation似乎只包含在命令行上传递的命令行EDIT:MyInvocation具有成员变量MyCommand.Parameters,它似乎具有所有参数,而不仅仅是在命令行上传递的参数...请参阅下面接受的答案 .

  • Get-Variable似乎在结果列表中包含可选变量,但我不知道如何将它们与其他变量区分开来

2 回答

  • 2

    以下似乎在我的盒子上工作...可能不是最好的方法,但它似乎在这种情况下工作,至少...

    [cmdletbinding()]
    
    param([Parameter(Mandatory=$True)]
    [string] $AFile = "C:\A\Path",
    
    [Parameter(Mandatory=$True)]
    [ValidateSet("A","B","C", "D")]
    [string] $ALetter = "A",
    
    [Parameter(Mandatory=$False)]
    [ValidateNotNullOrEmpty()]
    [string] $Optional1 = "Foo",
    
    [Parameter(Mandatory=$False)]
    [ValidateNotNullOrEmpty()]
    [string] $Optional2 = "Bar"
    )
    
    echo "Hello World!"
    
    ($MyInvocation.MyCommand.Parameters ).Keys | %{
        $val = (Get-Variable -Name $_ -EA SilentlyContinue).Value
        if( $val.length -gt 0 ) {
            "($($_)) = ($($val))"
        }
    }
    

    保存为allparams.ps1,运行它看起来像:

    .\allparams.ps1 -ALetter A -AFile "C:\Another\Path" 
    Hello World!
    (AFile) = (C:\Another\Path)
    (ALetter) = (A)
    (Optional1) = (Foo)
    (Optional2) = (Bar)
    
  • 1

    使用AST:

    [CmdletBinding()]
    Param (
     [Parameter(Mandatory=$True)]
     [string] $AFile = "C:\A\Path",
    
     [Parameter(Mandatory=$True)]
     [ValidateSet("A","B","C", "D")]
     [string] $ALetter = "A",
    
     [Parameter(Mandatory=$False)]
     [ValidateNotNullOrEmpty()]
     [string] $Optional1 = "Foo",
    
     [Parameter(Mandatory=$False)]
     [ValidateNotNullOrEmpty()]
     [string] $Optional2 = "Bar"
    )
    
    echo "Hello World!"
    $psboundparameters.keys | ForEach {
        Write-Output "($_)=($($PSBoundParameters.$_))"
    }
    
    
    $ast = [System.Management.Automation.Language.Parser]::
       ParseFile($MyInvocation.InvocationName,[ref]$null,[ref]$Null) 
    
    $ast.ParamBlock.Parameters | select Name,DefaultValue
    

相关问题