如何在 PowerShell 中将参数传递给调用表达式?

Pur*_*ome 6 powershell

我有以下(不工作)PowerShell 脚本:

$scriptPath = ((new-object net.webclient).DownloadString('https://gist.githubus
ercontent.com/AndrewSav/c4fb71ae1b379901ad90/raw/23f2d8d5fb8c9c50342ac431cc0360ce44465308/SO33205298')); $args = "`"aaa
bbb`"";  iex $scriptPath $args
Run Code Online (Sandbox Code Playgroud)

所以我:

  1. 下载要执行的脚本。
  2. 设置我的参数列表以发送到脚本中
  3. 执行脚本(对我来说,它现在在 cli 中)。

但它出错了:

Invoke-Expression : A positional parameter cannot be found that accepts argument '"aaa bbb"'.
At line:1 char:209
+ ... 44465308/SO33205298')); $args = "`"aaa bbb`"";  iex $scriptPath $args
+                                                     ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Expression], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Run Code Online (Sandbox Code Playgroud)

如何将参数传递给该脚本?

注意:这个问题引用/衍生自另一个SO问题

JPB*_*anc 3

你应该尝试这样的事情:

$scriptPath = ((new-object net.webclient).DownloadString('https://gist.githubusercontent.com/AndrewSav/c4fb71ae1b379901ad90/raw/23f2d8d5fb8c9c50342ac431cc0360ce44465308/SO33205298'))
Invoke-Command -ScriptBlock ([scriptblock]::Create($scriptPath)) -ArgumentList "coucou"
Run Code Online (Sandbox Code Playgroud)

在调用它之前,您必须从源代码创建一个 ScriptBlock。