【问题标题】:In powershell, how do I specify path to an exe including $env:userprofile?在 powershell 中,如何指定 exe 的路径,包括 $env:userprofile?
【发布时间】:2020-04-15 19:58:42
【问题描述】:

我正在尝试创建一个脚本来运行位于userprofile 文件夹内的exe,但我似乎无法使该命令正常工作。知道如何让这个工作吗?

我试过了: $env:userprofile\es-cli\es.exe myParameter

我收到一条错误消息: Unexpected token '\es-cli\es.exe' in expression or statement.

也试过了:

($env:userprofile)\es-cli\es.exe myParameter 遇到错误unexpected token \es-cli\es.exe

`$($env:userprofile)\es-cli\es.exe myParameter` 遇到错误the term $ is not recognized as the name of a cmdlet...

$loc = "{0}\es-cli\es.exe" -f $env:userprofile $loc myParameter # cant do this because $loc is a string

【问题讨论】:

  • 如果用引号括起来,它会打印到正确的路径吗?
  • @OwainEsau,根据您的评论,我尝试了 `&"$env:userprofile\es-cli\es.exe" 并且成功了!谢谢!

标签: powershell


【解决方案1】:

找到了解决办法。感谢this SO 帖子。我最终做了以下事情:

& ("{0}\es-cli\es.exe" -f $env:userprofile) myParameter

根据下面 Mathias 的评论,我最终使用了:

&(Join-Path $env:USERPROFILE 'es-cli\es.exe') myParam

【讨论】:

  • 这行得通,但你可能想养成使用Join-Path的习惯:& (Join-Path $env:userprofile 'es-cli\es.exe') myParameter
  • 谢谢@MathiasR.Jessen!我更喜欢你的方式,肯定会使用,谢谢!
  • 既然你没有说明 $env:userprofile 实际评估的结果,大概是路径中有空格?
  • 就我而言,$env:userprofile 的计算结果为 c:\users\anish
【解决方案2】:

我知道这是更多的代码。但我喜欢它,因为它可以让您更好地控制已启动程序的行为、统计信息、获取返回码以及在需要时返回错误。这是执行 Startprocess 方法的漫长过程。

$Path = "$($env:userprofile)\es-cli\es.exe"
$Args = "myParameter"
$newProcess = new-object System.Diagnostics.ProcessStartInfo $Path;
$newProcess.Arguments = $Args
$RunPro2 = New-Object System.Diagnostics.Process
$RunPro2.StartInfo = $NewProcess
$RunPro2.Start()
$RunPro2.WaitForExit()
$ProcessExitCode = $RunPro2.ExitCode.ToString()

【讨论】:

  • 虽然ProcessStartInfo 提供了更多的自定义功能,但这个特定场景也可以写成$ProcessExitCode = (Start-Process -FilePath $Path -ArgumentList $Args -PassThru -Wait).ExitCode。这个问题的重点,当然是用"$($env:userprofile)\es-cli\es.exe"进行字符串插值。
【解决方案3】:

使用呼叫运算符应该可以:

& $env:userprofile\es-cli\es.exe myParameter

假设您不想只是将其添加到路径中:

$env:path += ";$env:userprofile\es-cli"
es myParameter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多