代码之家  ›  专栏  ›  技术社区  ›  MyDaftQuestions

如何在PowerShell中将参数作为-file的一部分传递

  •  2
  • MyDaftQuestions  · 技术社区  · 7 年前

    如果我在PowerShell窗口中运行这一行,它将完美执行

    .\buildTestAndPublish.ps1 -buildPath 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0' -testPath 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TestWindow'
    

    现在我需要把它自动化,但我做不到

    $pth = 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0'
    $testPth = 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow' 
    start-process powershell -Verb runAs -ArgumentList "-file $PSScriptRoot\AutomationScripts\buildTestAndPublish.ps1 -buildPath $pth -testPath $testPth"
    

    找不到接受参数文件的位置参数

    我需要做什么?

    1 回复  |  直到 7 年前
        1
  •  3
  •   mklement0    7 年前

    使用 嵌入双引号 在可能包含空格的参数周围;在 "..." 嵌入转义 " 作为 `" ` ,和 性格 [一]

    "-file $PSScriptRoot\buildTestAndPublish.ps1 -buildPath `"$pth`" -testPath `"$testPth`""
    

    注: *.ps1 为了可读性而缩短了路径。

    注意 :嵌入式 -引用( '...' 在这种情况下工作 -File 无法将单引号识别为字符串分隔符 ;相比之下,它们被认为是 -Command . [二]


    注意你可以 与生俱来 ,作为 阵列 -ArgumentList .
    但是,由于 a known bug 仍然 应用嵌入双引号 :

    Start-Process powershell -Verb runAs -ArgumentList '-file',
      $PSScriptRoot\AutomationScripts\buildTestAndPublish.ps1,
      '-buildPath',
      "`"$pth`"",
      '-testPath',
      "`"$testPth`""
    

    [1] 正式名称为 GRAVE ACCENT, Unicode code point U+0060 .

    -命令 而不是 ,然后将启用以下解决方案:
    "-Command $PSScriptRoot\buildTestAndPublish.ps1 -buildPath '$pth' -testPath '$testPth'" ' 是文件名中的合法字符(而 " 不是)和 在文件名中会中断命令;和(b) 将参数视为PowerShell代码,这会导致额外的不需要的解释(相比之下, -文件 把它的论点当作 字面量

    推荐文章