2

In my profile I've got the following function:

function Start-VS {  
  param ([string]$sln, [switch]$UseNineteen )

  if ($UseNineteen) {
    $vs = "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe"
    $vsWorkDir = "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\"
  }
  else {
    $vs = "C:\Program Files\Microsoft Visual Studio\2022\Preview\Common7\IDE\devenv.exe"
    $vsWorkDir = "C:\Program Files\Microsoft Visual Studio\2022\Preview\Common7\IDE\"  
  }
  
  if (-Not ([string]::IsNullOrEmpty($sln))) {
    $TestP = (Test-Path $sln)
    if ( $TestP -eq $True) {
      $FullPath = Convert-Path $sln
      Start-Process $vs -WorkingDirectory $vsWorkDir -ArgumentList $FullPath  
    }
    else {
      Write-Output $FullPath
      Write-Output "Please use a correct pathway to a solution file" 
    }
  }
  else {
    Start-Process $vs -WorkingDirectory $vsWorkDir 
  }
}

To call it from the PS prompt I'm doing the following:

start-vs -sln "C:\demos\m02 arrays\Example.sln"

Visual studio opens but complains that it cannot find the files - I understand it is because of the space in m02 arrays - how do I alter the function so that it can handle spaces?

whytheq
  • 34,466
  • 65
  • 172
  • 267
  • You could `Push-Location` to parent path of `$sln` and call the file relatively. Then `Pop-Location` once done and want to go back to previous working directory. – codaamok Apr 24 '22 at 22:49
  • @codaamok thanks for the comment - I'm imagining there is a simpler method than this? – whytheq Apr 24 '22 at 23:12
  • 1
    A [long-standing bug](https://github.com/PowerShell/PowerShell/issues/5576) unfortunately requires use of _embedded_ quoting around arguments that contain spaces, e.g. `-ArgumentList '-foo', '"bar baz"'`. It is generally better to encode all arguments in a _single string_, e.g. `-ArgumentList '-foo "bar baz"`. See the linked duplicate for details. – mklement0 Apr 25 '22 at 03:16

1 Answers1

4

Change

Start-Process $vs -WorkingDirectory $vsWorkDir -ArgumentList $FullPath

to

Start-Process $vs -WorkingDirectory $vsWorkDir -ArgumentList "`"$FullPath`""

Notice the escaped "s surrounding $FullPath. This will include the surrounding quotes to be sent as part of the argument which is needed for paths (or other strings) that include spaces

Daniel
  • 4,792
  • 2
  • 7
  • 20
  • 2
    This replicates the official answer from https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.2 "If parameters or parameter values contain a space or quotes, they need to be surrounded with escaped double quotes." – Robert Cotterman Apr 25 '22 at 02:04