假设我有一个像这样的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
注意:
答案 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