带有空格的文件路径在批处理文件中不起作用

File path with spaces not working in batch file

提问人:TommyMaes 提问时间:12/19/2022 最后编辑:TommyMaes 更新时间:12/20/2022 访问量:117

问:

我正在尝试将包含 PowerShell 脚本的文本文件从 .bat 文件放入在命令行中运行的 PowerShell。

这是一种解决方法,可以在没有系统权限的情况下启动 PowerShell 脚本。

在我尝试带空格的路径之前,它工作得很好。有人知道如何做到这一点吗?

我搜索并尝试了许多解决方案(见 3、4、5、6),但要么这是一个非常特殊的情况,要么我做错了什么。总的来说,我对剧本的了解有所欠缺,但我正在尽力而为。请在您的回答中使用简单的语言。

  1. 这行得通

    @echo off
    powershell "cat -raw C:\examplenospace\test.txt | invoke-expression"
    
  2. 这行得通

    @echo off
    set "file=C:\examplenospace\test.txt"
    powershell "cat -raw %file% | invoke-expression"
    
  3. 不工作

    @echo off
    set "file=C:\example with space\test.txt"
    powershell "cat -raw %file% | invoke-expression"
    
  4. 当然,这也行不通

    @echo off
    powershell "cat -raw "C:\example with space\test.txt" | invoke-expression"
    
  5. 也不起作用

    @echo off
    powershell ""cat -raw "C:\example with space\test.txt" | invoke-expression"
    
  6. 我尝试了很多变化,似乎没有任何效果

    @echo off
    powershell "cat -raw \"\"C:\example with space\test.txt" | invoke-expression"
    

我怎样才能让它工作?

PowerShell 批处理文件 路径 引用 空格

评论

1赞 Compo 12/19/2022
或。。。甚至@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath 'C:\example with space\test.txt' -Raw | Invoke-Expression"@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath \"C:\example with space\test.txt\" -Raw | Invoke-Expression"
0赞 js2010 12/19/2022
也许是时候去所有 powershell,没有 invoke-expression。
1赞 Leptonator 12/19/2022
请阅读以下帖子(最后一篇)。我也会再读一遍——说真的。这将对你有所帮助 - 我会保证的。stackoverflow.com/a/180749/175063
1赞 JosefZ 12/19/2022
powershell "cat -raw '%file%' | invoke-expression"powershell "cat -raw """"%file%"""" | invoke-expression"
0赞 TommyMaes 12/20/2022
谢谢大家的回答,并非所有的答案都对我有用(只有 Compo 的回答有用),但我从你们的所有评论中学到了新东西!

答:

0赞 TommyMaes 12/20/2022 #1

@Compo谢谢你的回答,这马上就起作用了,他们俩!

@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -命令“Get-Content -LiteralPath 'C:\example with space\test.txt' -Raw |调用表达式”

@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -命令“Get-Content -LiteralPath ”C:\example with space\test.txt“ -Raw |调用表达式”