gpt4 book ai didi

powershell - 连字符/破折号参数对PowerShell意味着什么?

转载 作者:行者123 更新时间:2023-12-04 04:32:50 25 4
gpt4 key购买 nike

我发现,如果仅在Windows 10上将破折号传递给PowerShell 5.1脚本的参数,例如:

powershell.exe -File Test.ps1 -

我收到一条奇怪的错误消息,说:

C:\path\Test.ps1 : Cannot process argument because the value of argument "name" is not valid. Change the value o f the "name" argument and run the operation again.

  • CategoryInfo : InvalidArgument: (:) [Test.ps1], PSArgumentException
  • FullyQualifiedErrorId : Argument,Test.ps1

Test.ps1仅是:
echo "foo"

我遇到的实际问题是,当脚本声明任何强制性参数时:
param (
[Parameter(Mandatory)]
$value
)

echo "foo"

然后以相同的方式执行脚本(使用 -参数)完全没有任何作用。无输出。没有错误讯息。它只是挂了几秒钟。然后控件返回到命令提示符。

C:\path>powershell.exe -File Test.ps1 -

C:\path>_

-对PowerShell(5.1)意味着什么?

相反,在Windows 7上使用PowerShell 2.0,在这种情况下,我可以使用脚本:

C:\path>powershell.exe -File Test.ps1 -
Test.ps1 [-value] <Object> [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningAction <ActionPreference>] [-ErrorVariable <String>] [-WarningVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>]


C:\path>_

有什么意义(缺少必需的参数)。

在没有强制性参数声明的情况下,脚本可以工作(将其打印输出):

C:\path>powershell.exe -File Test.ps1 -
foo

C:\path>_

最佳答案

行为应该被视为错误-以-开头但不是有效的参数名称的事物应作为位置参数传递,而不是报告错误。

该错误影响:

  • Windows PowerShell(从v5.1.18362.145起)-尚不清楚是否会进行修复。
  • 如您所述,是否(a)收到错误消息(... the value of argument "name" is not valid ...)或(b)悄悄地忽略-取决于您的参数是否具有诸如[Parameter(Mandatory)] [1]之类的参数属性和/或您的param()块具有[CmdletBinding()]属性(如果适用,则(b)适用)。
  • PowerShell Core 6.x-即问题将在v7 中得到解决(撰写本文时为最新版本:v7.0.0-preview.3);我不知道6.2.2(即撰写本文时的最新稳定版本)是否将得到修复-我们将看看您提交的bug report on GitHub发生了什么。


  • 至于 解决方法(类似地在PowerShell Core中工作):

    使用 -Command而不是 -File

    尽管这改变了命令行解析的语义[2],但在诸如此类的简单情况下,区别并不重要:
    C:\> powershell -Command ./Test.ps1 -  # note the "./"

    请注意 ./,因为使用 -Command( -c)使PowerShell像解析PowerShell代码一样解析参数,并且仅按文件名重新执行脚本的通常限制才适用(为防止意外执行当前目录中的文件,您需要一个路径组件以明确表示该意图,因此需要前缀 ./.\)。

    如果脚本文件路径需要加引号,则必须使用引号并在调用操作符 &前面加上;例如。:
    C:\> powershell -Command "& \"./Test.ps1\" -"

    [1]在声明的参数上添加 [Parameter()]属性会隐式使封闭的脚本/函数成为 advanced,在这种情况下,将应用不同的解析规则。整个应用到 [CmdletBinding[]块的 param(...)属性将脚本/函数显式标记为高级脚本/函数。

    [2]有关 -File-Command参数的解析方式之间的差异,请参见 this answer

    关于powershell - 连字符/破折号参数对PowerShell意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57199565/

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