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

时间:2014-02-19 04:21:59

标签: powershell

假设我有一个像这样的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一样?

希望每次有脚本时都写下以下内容:

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

注意:

  • $ args似乎只包含未绑定参数,而不是默认参数 参数
  • $ MyInvocation似乎只包含在命令行上传递的命令编辑:MyInvocation有成员变量MyCommand.Parameters,它似乎具有所有参数,而不仅仅是那些在命令行上传递的参数。 。见下面接受的答案。
  • Get-Variable似乎在结果列表中包含可选变量,但我不知道如何将它们与其他变量区分开来

2 个答案:

答案 0 :(得分: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 :(得分: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