【问题标题】:Powershell Start-Process with variable FilePath带有变量 FilePath 的 Powershell 启动进程
【发布时间】:2018-09-09 13:42:14
【问题描述】:

您好,我需要使用 powershell 运行一个提升的变量进程。 以下代码不起作用,因为由于某种原因 Powershell 不扩展变量:

$exe = "C:\$var.exe"
Start-Process $exe -Verb runas

但是我得到了这个错误

Start-Process : 此命令无法运行,因为错误:系统找不到指定的文件

+Start-Process $exe -Verb runas;

【问题讨论】:

  • 如果您在运行Start-Process 之前输出$var$exe,它们是否具有预期值?
  • @Vittorio Vaselli 缺少一些代码,只需粘贴所有与不同变量相关的代码,否则无法理解

标签: powershell


【解决方案1】:

我喜欢使用数组和-join 组合字符串:

$exe = 'C:\',$var,'.exe' -join ''

接下来我会测试可执行文件是否存在并运行它或写一个错误

if(Test-Path -LiteralPath $exe) {
    Start-Process $exe -Verb runas
} else {
    Write-Error "the executable could not be found"
}

【讨论】:

    【解决方案2】:

    $var-变量在您声明 $exe-string 时扩展,只要您使用问题中的双引号即可。但是,单引号 $exe = 'c:\$var.exe' 不起作用,因为单引号是一个文字字符串。

    输出$exe 来验证路径。您的 $var 值可能是错误的。

    错误只是说明它运行了哪一行,而不是它实际使用的路径,除了它存储在$exe-变量中。

    $var = "nonexistingfile"
    $exe = "c:\$var.exe"
    $exe
    c:\nonexistingfile.exe
    
    Start-Process $exe
    Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
    At line:1 char:1
    + Start-Process $exe
    + ~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
        + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
    

    但是路径有效:

    $var = "windows\system32\notepad"
    $exe = "c:\$var.exe"
    $exe
    c:\windows\system32\notepad.exe
    
    Start-Process $exe
    #Starts notepad
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-27
      • 2015-02-20
      • 1970-01-01
      • 2019-10-30
      • 2021-03-01
      • 2015-01-03
      相关资源
      最近更新 更多