我正在尝试自己更新脚本,然后重新启动。
当脚本尝试将参数传递给自身时会出现问题,显然使用 param
清除 $args
.我有一个想法来定制 $args
-处理程序,类似于 param
,但有更好的方法吗?我确实需要命名参数,所以需要进行一些处理,我不能只使用 $args
.
param(
$a = "abc",
$b,
$c
)
Write-Host $a
Write-Host $b
Write-Host $c
Write-Host $args
这导致以下结果:
.\a.ps1 -a 1 -b 2 3
1
2
3
写
$args
到主机不返回任何内容。
最佳答案
接受你的问题陈述:
I'm trying to have a script update itself, and then relaunch itself.
这就是
$PSBoundParameters
的目的自动变量:.\myscript.ps1 @PSBoundParameters
还有你的另一个问题:
when the script tries to pass parameters to itself, as apparently using param clears $args
这是不真实的。您的示例中的问题是位置绑定(bind)参数绑定(bind)在起作用。实际发生的是
3
绑定(bind)到 $c
. $args
将捕获未绑定(bind)的参数,除非您有一个带有 ValueFromRemainingArguments
的参数属性。您可以使用 CmdletBinding
阻止此绑定(bind)发生。属性:function Verb-Noun {
[CmdletBinding(PositionalBinding = $false)]
param(
如
@mklement0
指出,您不能使用 $args
在高级功能中,您正在使用 CmdletBinding
或 Parameter
属性,就像我上面的例子。文件:
about_Automatic_Variables#args
about_Functions_CmdletBindingAttribute
about_Functions_Advanced_Parameters
关于powershell - 使用参数但在 powershell 中保存 $args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57674703/