powershell - 使用参数但在 powershell 中保存 $args

标签 powershell parameters

我正在尝试自己更新脚本,然后重新启动。

当脚本尝试将参数传递给自身时会出现问题,显然使用 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在高级功能中,您正在使用 CmdletBindingParameter属性,就像我上面的例子。

文件:

about_Automatic_Variables#args

about_Functions_CmdletBindingAttribute

about_Functions_Advanced_Parameters

关于powershell - 使用参数但在 powershell 中保存 $args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57674703/

相关文章:

jenkins - 使用 Jenkins 管道多行/多行字符串参数

objective-c - Objective-C 中的方法名称是相同的。

JavaScript 闭包问题

windows - 使用 PowerShell 将空文件夹列表从一个卷移动到另一个卷

powershell - 如何在Powershell中使用DotNetZip仅压缩文件而不压缩完整路径层次结构?

powershell - 无法在更新模块上找到存储库

javascript - 有人可以向我解释这个 JS 函数吗?

powershell - 如何在powershell中为windows进程重新启动docker?

powershell - 向自定义 Powershell cmdlet 提供配置信息的传统方式是什么

performance - 参数变量导致查询慢,但为什么呢?