The Ops Community ⚙️

Cover image for Start WSL or Remote VS Code with from PowerShell
Kai Walter
Kai Walter

Posted on

Start WSL or Remote VS Code with from PowerShell

Today I want to share the script I use to VS Code remote into WSL or SSH environments.

Sample calls

coderemote wsl ~/src/message-distribution
coderemote my-dev-vm ~/src/message-distribution
Enter fullscreen mode Exit fullscreen mode

Assumptions

  1. ~/ in Path is translated to /home/{user name}/ where ...
    • for WSL I assume that Windows user name is the WSL's user name
    • for SSH I use my SSH configuration module to determine target user name
  2. for SSH FQDN, that the SSH config file maps from a potentially abbreviated hostname to the full FQDN like
Host my-dev-vm
  User kai
  HostName my-dev-vm.germanywestcentral.cloudapp.azure.com
  IdentityFile ~/.ssh/devvmprivkey
Enter fullscreen mode Exit fullscreen mode

The Script

[CmdletBinding()]
param (
    [Parameter(Position = 1, Mandatory = $true)]
    [string]
    $HostName,
    [Parameter(Position = 2, Mandatory = $true)]
    [string]
    $Path,
    [Parameter(Position = 3, Mandatory = $false)]
    [string]
    $DistroName = "Ubuntu"
)

if ($HostName.ToLowerInvariant() -eq "wsl") {

    $extendedPath = $Path -replace "~/", $("/home/" + $env:USERNAME + "/")
    if ($extendedPath -notmatch "^\/") {
        throw "path $Path needs to be absolute or start with ~/"
    }

    $remotePath = "vscode-remote://wsl+$DistroName$extendedPath"

}
else {

    Import-Module $(Join-Path $PSScriptRoot "MyModules" "manageSshConfig.psm1")

    $hl = Get-ConfigHostList

    $h = $hl | Get-ConfigHostFromList -HostName $HostName 

    if ($h) {
        $extendedPath = $Path -replace "~/", $("/home/" + $h["User"] + "/")
        if ($extendedPath -notmatch "^\/") {
            throw "path $Path needs to be absolute or start with ~/"
        }
        $remotePath = "vscode-remote://ssh-remote+$HostName$extendedPath"
    }

}

if ($remotePath) {
    Write-Host "opening" $remotePath
    code --folder-uri $remotePath
}
else {
    Write-Error "could not determine a remote path"
}
Enter fullscreen mode Exit fullscreen mode

related content

Latest comments (1)

Collapse
 
patrick_londa profile image
Patrick Londa

Thanks for sharing, @kaiwalter!