空间导致PowerShell分离路径

jaf*_*ffa 48 powershell

当在包含空格的路径上调用exe时,我遇到了PowerShell的问题.

PS C:\ Windows服务> invoke-expression"C:\ Windows Services\MyService.exe"

术语"C:\ Windows"未被识别为cmdlet,函数,脚本文件或可操作程序的名称.检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试.

它似乎在"Windows"和"服务"之间的空间上分裂.知道怎么解决这个问题吗?

Adi*_*tan 65

这会做你想要的吗?:

& "C:\Windows Services\MyService.exe"
Run Code Online (Sandbox Code Playgroud)


Ant*_*ace 20

您可以在空格前使用单引号和反引号来逃避空间:

$path = 'C:\Windows Services\MyService.exe'
$path -replace ' ', '` '
invoke-expression $path
Run Code Online (Sandbox Code Playgroud)

  • 虽然这回答了所提出的问题,但值得指出的是,“Invoke-Expression”不仅是用于 OP 用例的错误工具,[通常应该避免](https://blogs.msdn.microsoft. com/powershell/2011/06/03/invoke-expression-considered-harmful/)。 (2认同)

小智 9

对我有用的(我需要创建 MySQL 转储的路径)是将目录放在 6 个双引号之间,如下所示:

$path = """C:\Path\To\File"""
Run Code Online (Sandbox Code Playgroud)


小智 8

不确定是否有人仍然需要它...我需要在powershell中调用msbuild并且以下工作正常:

$MSBuild = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"

& $MSBuild $PathToSolution /p:OutDir=$OutDirVar /t:Rebuild /p:Configuration=Release
Run Code Online (Sandbox Code Playgroud)


jkd*_*dba 7

可以使用.点运算符。

. "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"
Run Code Online (Sandbox Code Playgroud)

Start-Process命令

Start-Process -PSPath "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"
Run Code Online (Sandbox Code Playgroud)

或使用ProcessStartInfoProcess

$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo
$ProcessInfo.FileName = 'C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe'
if($Admin){ $ProcessInfo.Verb = 'runas' }
$ProcessInfo.UseShellExecute = $false

$CommandParameters = '-noexit -noprofile -command Set-Location -LiteralPath c:\; $host.ui.RawUI.WindowTitle = ''[{0}] PS''; Set-PSReadlineOption -HistorySaveStyle SaveNothing;' -f $Cred.UserName
$ProcessInfo.Arguments = $CommandParameters
$ProcessInfo.Domain = ($Cred.UserName -split '\\')[0]
$ProcessInfo.UserName = ($Cred.UserName -split '\\')[1]
$ProcessInfo.Password = $Cred.Password

$ProcessObject = New-Object -TypeName System.Diagnostics.Process
$ProcessObject.StartInfo = $ProcessInfo
$ProcessObject.Start() | Out-Null
Run Code Online (Sandbox Code Playgroud)


Cat*_*ian 6

对于任何带有空格的文件路径,只需将它们放在双引号中即可在 Windows Powershell 中工作。例如,如果你想进入 Program Files 目录,而不是使用

PS C:\> cd Program Files
Run Code Online (Sandbox Code Playgroud)

这会导致错误,只需使用以下内容即可解决问题:

PS C:\> cd "Program Files"
Run Code Online (Sandbox Code Playgroud)

  • 对我不起作用。使用 PowerShell v`7.3.0` (2认同)

小智 6

这对我有用:

$scanresults = Invoke-Expression "& 'C:\Program Files (x86)\Nmap\nmap.exe' -vv -sn 192.168.1.1-150 --open"
Run Code Online (Sandbox Code Playgroud)


sei*_*cle 5

2018 年在 Windows10 上使用 Powershell,对我有用的只是用简单的引号替换双"引号'。正如答案中所建议的那样,在空格前添加反引号破坏了路径。