【问题标题】:Powershell - Start-Process ArgumentList accepts only single variable with spacesPowershell - Start-Process ArgumentList 仅接受带空格的单个变量
【发布时间】:2021-01-29 14:06:49
【问题描述】:

我正在尝试从 Explorer 启动我的脚本。我找到了解决方案,如果脚本没有任何参数,它就可以工作。

$file = [System.IO.Directory]::GetCurrentDirectory() + "\Trees.ps1"
Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -File `"$($file)`""

但是,如果我像第一个一样添加其他参数,它就会停止工作。 IE。此代码抛出“字符串缺少终止符:'。”错误。

$file = [System.IO.Directory]::GetCurrentDirectory() + "\Trees.ps1"
$Context = [System.IO.Directory]::GetCurrentDirectory()
Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -Context '"$($Context)'" -File `"$($file)`""

我正在使用这种期望变量的方式:

[Parameter(Mandatory=$True)]
[string]$Context,

如何在 ArgumentList 中传递多个带有空格的变量? 我怀疑我应该以其他方式传递文件内容的参数,而不是仅传递文件名,但找不到解决方案。

【问题讨论】:

  • 这些是 $context 周围的单引号,而不是反引号。

标签: windows powershell


【解决方案1】:

除了 Theo 指出的反引号问题之外,-context 应该跟在 -file 后面。

-File
    Runs the specified script in the local scope ("dot-sourced"), so that the
    functions and variables that the script creates are available in the
    current session. Enter the script file path and any parameters.
    File must be the last parameter in the command, because all characters
    typed after the File parameter name are interpreted
    as the script file path followed by the script parameters.

所以你的命令行应该是

Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -File `"$($file)`" -Context $($Context)"

【讨论】:

    【解决方案2】:

    由于您使用的是外部进程调用,因此您需要在内部使用双引号而不是单引号。您只需添加另一个双引号 ("") 即可转义双引号。

    Start-Process powershell -verb runas -ArgumentList "-ExecutionPolicy UnRestricted -File ""$file"" -Context ""$Context"""
    

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 2018-11-02
      • 2020-05-07
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多