gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:28:58 29 4
gpt4 key购买 nike

假设我有一个像这样的 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 似乎只包含未绑定(bind)参数,而不是默认参数参数
  • $MyInitation 似乎只包含在命令行上传递的命令 编辑:MyInvocau 有成员变量 MyCommand.Parameters,它似乎拥有所有参数,而不仅仅是在命令行上传递的参数。 .请参阅下面已接受的答案。
  • Get-Variable 似乎在结果列表中包含了可选变量,但我不知道如何将它们与其他变量区分开来

最佳答案

以下内容似乎适用于我的盒子...可能不是最好的方法,但至少在这种情况下似乎有效...

[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)

关于powershell - 显示所有 Powershell 脚本参数默认变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870977/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com