Last active
August 5, 2025 16:32
-
-
Save backerman/2c91d31d7a805460f93fe10bdfa0ffb0 to your computer and use it in GitHub Desktop.
Enable tab completion for ssh hostnames in PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Management.Automation | |
Register-ArgumentCompleter -CommandName ssh,scp,sftp -Native -ScriptBlock { | |
param($wordToComplete, $commandAst, $cursorPosition) | |
$knownHosts = Get-Content ${Env:HOMEPATH}\.ssh\known_hosts ` | |
| ForEach-Object { ([string]$_).Split(' ')[0] } ` | |
| ForEach-Object { $_.Split(',') } ` | |
| Sort-Object -Unique | |
# For now just assume it's a hostname. | |
$textToComplete = $wordToComplete | |
$generateCompletionText = { | |
param($x) | |
$x | |
} | |
if ($wordToComplete -match "^(?<user>[-\w/\\]+)@(?<host>[-.\w]+)$") { | |
$textToComplete = $Matches["host"] | |
$generateCompletionText = { | |
param($hostname) | |
$Matches["user"] + "@" + $hostname | |
} | |
} | |
$knownHosts ` | |
| Where-Object { $_ -like "${textToComplete}*" } ` | |
| ForEach-Object { [CompletionResult]::new((&$generateCompletionText($_)), $_, [CompletionResultType]::ParameterValue, $_) } | |
} |
If you want to simplify the script and just want to use the host-aliases without the user@
part in your ssh command, you can use the following script:
using namespace System.Management.Automation
$script = {
param($wordToComplete)
Get-Content ${Env:HOMEPATH}\.ssh\config `
| Select-String -Pattern "^Host " `
| ForEach-Object { $_ -replace "host ", "" -split " " } `
| Sort-Object -Unique `
| Where-Object { $_ -like "$wordToComplete*" } `
| ForEach-Object { "$_" }
}
Register-ArgumentCompleter -CommandName ssh,scp,sftp -ScriptBlock $script
This autocompletes for example ssh du⭾
to ssh dummy
which will internally calls ssh [email protected]
, given the following ~\.ssh\config
:
Host dummy
Hostname dummy.com
User admin
To state the "obvious" but for new users (and for educational purposes) note that this script should be placed in your profile file e.g:
C:\Users\Bob\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
If you have VS code installed you could run code $PROFILE
and it should look like:
using namespace System.Management.Automation
# Any other imports you had before
Import-Module posh-sshell
# Then the SSH completion script
Register-ArgumentCompleter -CommandName ssh,scp,sftp -Native -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
# ... rest of the script
}
# Any other stuff you had in your profile
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! It works perfectly! Thanks you! This reminds me to renew my Shell scripting