Spaces cause split in path with PowerShell

前端 未结 12 833
广开言路
广开言路 2020-12-02 15:24

I\'m having an issue with powershell when invoking an exe at a path containing spaces.

PS C:\\Windows Services> invoke-expression \"C:\\Windows Services\\My

相关标签:
12条回答
  • 2020-12-02 15:34

    Can use the . dot operator.

    . "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"
    

    or the Start-Process command

    Start-Process -PSPath "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"
    

    or using ProcessStartInfo and Process

    $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
    
    0 讨论(0)
  • 2020-12-02 15:37

    Using Powershell on Windows10 in 2018, what worked for me was simply to replace double quotes " by simple quotes '. Adding the backtick before the space, as suggested in an answer, broke the path.

    0 讨论(0)
  • 2020-12-02 15:37

    Please use this simple one liner:

    Invoke-Expression "C:\'Program Files (x86)\Microsoft Office\root\Office16'\EXCEL.EXE"
    
    0 讨论(0)
  • 2020-12-02 15:39

    Just put ${yourpathtofile/folder}

    PowerShell does not count spaces; to tell PowerShell to consider the whole path including spaces, add your path in between ${ & }.

    0 讨论(0)
  • 2020-12-02 15:42

    There's a hack I've used since the Invoke-Expression works fine for me.

    You could set the current location to the path with spaces, invoke the expression, get back to your previous location and continue:

    $currLocation = Get-Location
    Set-Location = "C:\Windows Services\"
    Invoke-Expression ".\MyService.exe"
    Set-Location $currLocation
    

    This will only work if the exe doesn't have any spaces in its name.

    Hope this helps

    0 讨论(0)
  • 2020-12-02 15:46

    For any file path with space, simply put them in double quotations will work in Windows Powershell. For example, if you want to go to Program Files directory, instead of use

    PS C:\> cd Program Files
    

    which will induce error, simply use the following will solve the problem:

    PS C:\> cd "Program Files"
    
    0 讨论(0)
提交回复
热议问题