问题描述
我正在尝试找到一种从Powershell脚本获取所有参数信息的方法.前脚本:
I'm trying to find a way to get all parameter information from a powershell script. Ex script:
function test()
{
Param(
[string]$foo,
[string]$bar,
[string]$baz = "baz"
)
foreach ($key in $MyInvocation.BoundParameters.keys)
{
write-host "Parameter: $($key) -> $($MyInvocation.BoundParameters[$key])"
}
}
test -foo "foo!"
我想以动态方式获取$bar
和$baz
的值,而无需提前知道参数的名称.
I'd like to get the values of $bar
and $baz
in a dynamic way without knowing the names of the parameters ahead of time.
我已经浏览过$MyInvocation
属性和方法,但是除了已设置/传递的参数外,我什么也看不到.
I've looked through $MyInvocation
properties and methods but I don't see anything besides parameters that are set/passed.
更新1:
我即将获得它:
function test()
{
Param(
[string]$foo,
[string]$bar,
[string]$baz = "baz"
)
foreach($var in (get-variable -scope private))
{
write-host "$($var.name) -> $($var.value)"
}
}
test -foo "foo!"
如果我可以过滤掉脚本参数和默认参数,那我就很好了.
If i could filter out the script parameters vs the default parameters I would be good to go.
更新2:最终的工作解决方案如下所示:
Update 2:The final working solution looks like this:
function test {
param (
[string] $Bar = 'test'
, [string] $Baz
, [string] $Asdf
)
$ParameterList = (Get-Command -Name $MyInvocation.InvocationName).Parameters;
foreach ($key in $ParameterList.keys)
{
$var = Get-Variable -Name $key -ErrorAction SilentlyContinue;
if($var)
{
write-host "$($var.name) > $($var.value)"
}
}
}
test -asdf blah;
推荐答案
签出此解决方案.这使用了CmdletBinding()
属性,该属性通过使用$PSCmdlet
内置变量提供了一些其他元数据.您可以:
Check this solution out. This uses the CmdletBinding()
attribute, which provides some additional metadata through the use of the $PSCmdlet
built-in variable. You can:
- 使用
$PSCmdlet
动态检索命令的名称 - 使用
Get-Command
获取命令的参数列表 - 使用
Get-Variable
cmdlet 检查每个参数的值
- Dynamically retrieve the command's name, using
$PSCmdlet
- Get a list of the parameter for the command, using
Get-Command
- Examine the value of each parameter, using the
Get-Variable
cmdlet
代码:
function test {
[CmdletBinding()]
param (
[string] $Bar = 'test'
, [string] $Baz
, [string] $Asdf
)
# Get the command name
$CommandName = $PSCmdlet.MyInvocation.InvocationName;
# Get the list of parameters for the command
$ParameterList = (Get-Command -Name $CommandName).Parameters;
# Grab each parameter value, using Get-Variable
foreach ($Parameter in $ParameterList) {
Get-Variable -Name $Parameter.Values.Name -ErrorAction SilentlyContinue;
#Get-Variable -Name $ParameterList;
}
}
test -asdf blah;
输出
命令的输出如下:
Output
The output from the command looks like this:
Name Value
---- -----
Bar test
Baz
Asdf blah
这篇关于从Powershell获取所有命名参数,包括空参数和设置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!