如何在PowerShell中添加引号?

问题描述 投票:0回答:1

我想创建一个命令来安装适用于 WindowsScoop

包管理器

它应该从 cygwin shell 运行 它的工作原理如下:

  1. 请求管理员权限
  2. 打开 PowerShell 窗口
  3. 运行Scoop安装命令

我做了这个命令,它看起来像这样:
powershell -NoProfile -ExecutionPolicy Bypass -Command 'Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -NoExit -Command iex ""& {$(irm get.scoop.sh)} -RunAsAdmin""" -Verb RunAs -Wait'

此命令运行,但有一个问题 - “&”符号旁边没有引号

Error photo

错误文字:

At line:1 char:5 + iex & {# Issue Tracker: https://github.com/ScoopInstaller/Install/iss ... + ~ The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quot ation marks ("&") to pass it as part of a string. At line:339 char:30 + set args=%args:(=``(%, + ~ Missing argument in parameter list. At line:689 char:31 + $ErrorActionPreference = 'Stop' + ~ The string is missing the terminator: '. At line:241 char:30 + if ($retries -eq 10) { + ~ Missing closing '}' in statement block or type definition. At line:240 char:29 + while ($retries -le 10) { + ~ Missing closing '}' in statement block or type definition. At line:108 char:33 + function Test-ValidateParameter { + ~ Missing closing '}' in statement block or type definition. At line:1 char:7 + iex & {# Issue Tracker: https://github.com/ScoopInstaller/Install/iss ... + ~ Missing closing '}' in statement block or type definition. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : AmpersandNotAllowed


如您所见,脚本已加载并用大括号括起来,但仍然

未执行,因为“&”字符旁边没有引号

现在解释如下:

iex & {<scoop installation script>} -RunAsAdmin
它应该是这样的:

iex "& {<scoop installation script>} -RunAsAdmin"
我从官方 

Scoop 安装文档中获取了脚本本身 - https://github.com/ScoopInstaller/Install#for-admin

所以请帮我在安装命令中加上引号🙏


提前谢谢您!

windows bash powershell cygwin quotes
1个回答
-1
投票
前言:

    此答案的早期版本存在缺陷。
  • 注意 Cygwin 上下文,这意味着 POSIX 兼容 shell 的语法规则(例如
  • bash
    )最初适用;值得注意的是,这意味着 
    "
    \"
     进程命令行上自动转义为 
    powershell.exe

  • 将嵌入的

    ""

     替换为 
    \`"
    (原文如此):

    • `

      转义
      "
      以包含在封闭的
      "..."
      字符串内。

    • 然后,

      \

      转义生成的
      "
      ,以便与嵌套的
      powershell.exe -Command
       CLI 调用一起使用(CLI 在命令行解析期间剥离 
      未转义的 "
      )。

  • `

    -逃避
    $
    中的
    $(irm get.scoop.sh)

      因为外部
    • powershell.exe
       使用 
      "..."
       引用其 
      -ArgumentList
       值,所以 
      $
       必须进行 
      `
       转义,以防止 
      过早 扩展(插值),因为其目的是为了 内部 - 然后提升 - powershell.exe
       调用以解释 
      $(...)
       子表达式。
powershell -NoProfile -ExecutionPolicy Bypass -Command 'Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -NoExit -Command iex \`"& {`$(irm get.scoop.sh)} -RunAsAdmin\`"" -Verb RunAs -Wait'
    
© www.soinside.com 2019 - 2024. All rights reserved.