【问题标题】:Execute batch file with spaces in path执行路径中有空格的批处理文件
【发布时间】:2026-01-04 08:25:01
【问题描述】:

我无法通过 PowerShell 在远程服务器上执行批处理文件。用户可以在弹出窗口中选择多个意见,如Servernamestartingkilling 进程和Servicename。选择的项目将保存在变量中。

如果选择了所有项目,我想将字符串合并为一个字符串并执行命名为这个结果字符串的批处理脚本。 我尝试按照this post 中的说明进行操作,但不会执行批处理脚本。

例子:

[String]$scriptpath="C:\tmp\"
[String]$Servername = "xx040"
[String]$actionprefix = "kill_process"
[String]$action = $($actionprefix) + "-"
[String]$Servicename = "service1"
[String]$ServiceFullname = $($action) + $($Servicename) + ".bat"
$batchPath = $("`"$scriptpath + $ServiceFullname `"")
Invoke-Command -ComputerName $Servername -ScriptBlock {
  cmd.exe /c "`"$batchPath`""
}

【问题讨论】:

    标签: windows powershell batch-file cmd


    【解决方案1】:

    在您的代码中,您没有将任何内容传递给您的调用命令,因此当它远程运行时,它不知道$batchPath 是什么。看看这个 SO 答案How do I pass named parameters with Invoke-Command?

    Invoke-Command -ComputerName $Servername -ScriptBlock {param($batchPath) cmd.exe /c "`"$batchPath`"" } -ArgumentList $batchPath
    

    是您想要拨打电话的方式。

    【讨论】:

    • 你是对的!现在批处理脚本运行成功。我在我的代码中发现了一个错误:将 $batchPath = $(""$scriptpath + $ServiceFullname "") 更改为 $batchPath = $(""$scriptpath\$ServiceFullname "")
    【解决方案2】:

    只需使用call operator (&) 并将带有批处理文件路径的变量放在双引号中。

    & "$batchPath"
    

    您还需要通过 using: 范围修饰符在脚本块内使变量 $batchPath 为已知,否则脚本块内的 $batchPath 将是与脚本块外的 $batchPath 不同的(空)变量。

    Invoke-Command -Computer $Servername -ScriptBlock {
      & "$using:batchPath"
    }
    

    另一种方法是将变量作为参数传递到脚本块中:

    Invoke-Command -Computer $Servername -ScriptBlock {
      Param($BatchPath)
      & "$BatchPath"
    } -ArgumentList $batchPath
    

    使用Join-Path 构建路径,因此您无需自己处理前导/尾随路径分隔符。此外,PowerShell 扩展双引号字符串中的变量,允许您避免过多的串联。在单引号字符串中,变量不会被扩展,所以我通常使用双引号来表示有变量的字符串,而单引号表示没有变量的字符串。

    修改代码:

    $Servername   = 'xx040'
    $scriptpath   = 'C:\tmp'
    $actionprefix = 'kill_process'
    $Servicename  = 'service1'
    
    $batchPath = Join-Path $scriptpath "$actionprefix-$Servicename.bat"
    
    Invoke-Command -ComputerName $Servername -ScriptBlock {
       & "$using:batchPath"
    }
    

    【讨论】:

      【解决方案3】:

      避免路径中包含空格的另一种方法是使用 8.3 短符号。

      在 Windows 中打开命令行并使用 dir 的 /x 参数。要查找程序文件目录的短名称,您可以使用dir C:\prog* /x。结果如下:

      21.10.2015  14:46    <DIR>          PROGRA~1     Program Files
      21.10.2015  12:47    <DIR>          PROGRA~2     Program Files (x86)
      04.09.2014  18:25    <DIR>          PR6AFF~1     Programs16Bit
      

      如果你要写C:\Program Files,你也可以写C:\PROGRA~1

      【讨论】: