【问题标题】:powershell run cmd with spaces in argumentpowershell 运行 cmd,参数中有空格
【发布时间】:2020-06-18 09:19:18
【问题描述】:

我正在尝试为文件夹添加观察程序,创建文件后,启动程序

$script= "C:\test.py"
$watcher.Path ="e:\my folder\test folder\dropbox"    

Start-Process cmd -Argument "/k python $script $path" 

问题是,这总是让我说 e:\my no such file

我知道这是空间的问题,但我尝试了以下,仍然得到同样的错误

Start-Process cmd -Argument "/k python $script '$path'" 

有谁知道如何解决这个问题?

非常感谢

【问题讨论】:

    标签: powershell batch-file powershell-2.0 powershell-3.0


    【解决方案1】:

    你需要使用 escaped embedded 双引号和Start-Process:

    $script= "C:\test.py"
    $path = "e:\my folder\test folder\dropbox"    
    
    Start-Process cmd -Argument "/k python $script `"$path`"" 
    

    否则,$path 值中的空格会在cmd 接收参数时将路径分成多个 个参数。

    `""..." 字符串中逐字嵌入"

    顺便说一句:

    • 如果您的意图是在 新窗口(在 Windows 上)中异步运行命令,正如您的命令所建议的,Start-Process 确实正确的工具。

    • 相比之下,不要使用Start-Process,如果你想运行其他控制台应用程序(例如cmd同步,在同一窗口;在这种情况下,只需直接调用控制台应用程序 - 请参阅this answer 了解更多信息。

    【讨论】:

      【解决方案2】:

      我试图运行一个 powershell cmd 来解析输入,特别是为了获取在服务器上运行的 chrome 版本。

           String version = null;
           String command = "powershell.exe (Get-Item \"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\").VersionInfo";
           Process process = Runtime.getRuntime().exec(command);
           process.getOutputStream().close();
           BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));       
           String line = reader.readLine();
           while(line!=null){
               if(line.matches("[0-9]{2,3}\\.[0-9]{1,2}\\..*")){
                   version = line.substring(0, line.indexOf("."));
               }             
               line = reader.readLine();                
           }       
      

      这失败了,错误指示命令在路径中的空格处被分割。

      我用单引号替换了转义的双引号,它起作用了:

      String command = "powershell.exe (Get-Item 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe').VersionInfo";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-16
        • 2019-02-25
        • 1970-01-01
        • 2018-08-14
        • 2021-12-04
        相关资源
        最近更新 更多