Skip to content

Instantly share code, notes, and snippets.

@tniessen
Created May 14, 2022 18:10
Show Gist options
  • Save tniessen/89008c674e793caab2b023aa7292d021 to your computer and use it in GitHub Desktop.
Save tniessen/89008c674e793caab2b023aa7292d021 to your computer and use it in GitHub Desktop.
Updates the HostName property of SSH hosts that are Hyper-V virtual machines to the (dynamic) IPv4 addresses of their network interfaces
$ErrorActionPreference = "Inquire"
$SshConfigPath = "C:\Users\Tobias\.ssh\config"
$lines = Get-Content -Path $SshConfigPath
for ($i = 0; $i -le $lines.Count; $i++) {
if ($lines[$i] -notmatch '^# auto-fix: (?<VirtualMachineName>[^ ]+) (?<NetworkAdapterName>[^ ]+)$') {
continue
}
$VirtualMachineName = $Matches.VirtualMachineName
$NetworkAdapterName = $Matches.NetworkAdapterName
if ($lines[++$i] -notmatch '^Host (?<SshHost>.*)$') {
$offending_line = $lines[$i]
throw "Expected a 'Host' line after '# auto-fix', but found '$offending_line'"
}
$SshHost = $Matches.SshHost
if ($lines[++$i] -notmatch '^ HostName (?<OldHostName>.*)$') {
$offending_line = $lines[$i]
throw "Expected a 'HostName' line after '# auto-fix' and 'Host', but found '$offending_line'"
}
$OldHostName = $Matches.OldHostName
Write-Host "Fixing SSH config for host '$SshHost'."
Write-Host "The current host name is '$OldHostName'."
Write-Host "Determining IPv4 address of VM '$VirtualMachineName' using '$NetworkAdapterName'."
$ip = Get-VM -Name $VirtualMachineName | Select -ExpandProperty NetworkAdapters | Where-Object -Property Name -Value $NetworkAdapterName -eq | Select-Object -Property IPAddresses | foreach { $_.IPAddresses | Where { $_ -Match "\d+\.\d+\.\d+\.\d+" } }
if (!$ip) {
throw "No IPv4 address was found for virtual machine '$VirtualMachineName' and network adapter '$NetworkAdapterName'."
}
Write-Host "The new host name is '$ip'."
$lines[$i] = " HostName $ip"
}
Write-Host "Updating $SshConfigPath"
Set-Content -Path $SshConfigPath -Value $lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment