首页 > 解决方案 > start-process powershell 运行另一个 powershell 来运行另一个带参数的程序。不适用于 args,但适用于 args

问题描述

抱歉,如果标题看起来很奇怪,我不知道如何表述。

我正在尝试在新的 PowerShell 实例中运行我的脚本以在后台运行 OpenVPN,但是当从启动进程调用时,我无法将任何参数传递给 OpenVPN。

function ConnectOpenVPN{

  [Parameter(Mandatory=$true, Position=0)]
  [string] $ip,
  [Parameter(Mandatory=$true, Position=1)]
  [string] $user
  [Parameter(Mandatory=$true, Position=2)]
  [string] $pass
  [Parameter(Mandatory=$true, Position=2)]
  [string] $id    

  $temp = New-TemporaryFile
  $credentials =  $user + "`n"  + $pass
  $credentials| Set-Content $temp  
  $config = "C:\Program Files (x86)\OpenVPN\config\" + $id + ".ovpn"
  $file = $temp.FullName


  Start-Process powershell -args "& C:\'Program Files'\OpenVPN\bin\openvpn.exe --config $config --auth-user-pass $file"

  #delete temp file
}

当我使用它运行脚本时,--config $config --auth-user-pass $file它不起作用,但是当我在没有这些参数的情况下运行相同的脚本时,一切正常。

有没有办法改变这种行为?

标签: powershell

解决方案


这应该可以解决问题。请注意如何将带有参数的命令传递给Start-Process函数&

function ConnectOpenVPN{

  [Parameter(Mandatory=$true, Position=0)]
  [string] $ip,
  [Parameter(Mandatory=$true, Position=1)]
  [string] $user
  [Parameter(Mandatory=$true, Position=2)]
  [string] $pass
  [Parameter(Mandatory=$true, Position=2)]
  [string] $id    

  $temp = New-TemporaryFile
  $credentials =  $user + "`n"  + $pass
  $credentials| Set-Content $temp  
  $config = "C:\Program Files (x86)\OpenVPN\config\" + $id + ".ovpn"
  $file = $temp.FullName

  Start-Process -FilePath powershell -ArgumentList @("-command", "& 'C:\Program Files\OpenVPN\bin\openvpn.exe' '--config' $config '--auth-user-pass' $file")

  #delete temp file
}

推荐阅读