Created
August 14, 2018 07:50
-
-
Save tdewin/ab5e6e017fed65275ec5fbf65f6cfd57 to your computer and use it in GitHub Desktop.
vSphere CLI RDP Manager in $profile
This file contains 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
function Get-VSPLabConnection { | |
param( | |
$profilespath="HKCU:\Software\vSpshereConnections", | |
$address="" | |
) | |
$entries = @(Get-ItemProperty -Path $profilespath) | |
if ($entries.count -gt 0) { | |
$procentries = @() | |
foreach($entry in ($entries | Get-Member | ? { $_.name -match "@$address" } | % { $_.Name })) { | |
$item = Get-ItemPropertyValue -Path $profilespath -name $entry | |
$procentries += $item | ConvertFrom-Json | |
} | |
return $procentries | |
} else { | |
return @() | |
} | |
} | |
function Remove-VSPLabConnection { | |
[cmdletbinding()] | |
param( | |
[Parameter(ValueFromPipeline=$True)]$entry=$null, | |
[string]$address=$null, | |
[string]$username=$null, | |
$profilespath="HKCU:\Software\vSpshereConnections" | |
) | |
begin { | |
} | |
process { | |
$entryname = "" | |
if ($entry -eq $null) { | |
if($address -ne $null -and $username -ne $null) { | |
$entryname = "$username@$address" | |
} else { | |
write-error "If there is no entry, please supply address and username" | |
} | |
} else { | |
$entryname = ("{0}@{1}" -f $entry.user,$entry.address) | |
} | |
if ($entryname -ne "") { | |
Remove-ItemProperty -Path $profilespath -Name $entryname | |
Write-Verbose "Removed $entry" | |
} | |
} | |
} | |
function New-VSPLabConnection { | |
[cmdletbinding()] | |
param( | |
$address="127.0.0.1", | |
$user="root", | |
[System.Security.SecureString]$password=$null, | |
$profilespath="HKCU:\Software\vSpshereConnections" | |
) | |
if (-not (Test-Path $profilespath )) { | |
New-Item -Path $profilespath -ItemType Directory | Out-Null | |
Write-Verbose "Made $profilespath" | |
} | |
$keyname = "$user@$address" | |
$pwExport = "" | |
if($password -ne $null) { | |
$pwExport = ($password|Convertfrom-SecureString) | |
} | |
$profileExport = New-Object -TypeName psobject -Property @{user=$user;address=$address;password=$pwExport} | ConvertTo-Json | |
Write-Verbose $keyname | |
Write-Verbose $profileExport | |
$existingkey = Get-ItemProperty -Path $profilespath -Name $keyname -ErrorAction SilentlyContinue | |
if ($existingkey -eq $null) { | |
New-ItemProperty -Path $profilespath -PropertyType MultiString -name $keyname -Value $profileExport | Out-Null | |
Write-Verbose "New $keyname entry made" | |
} else { | |
Set-ItemProperty -Path $profilespath -name $keyname -Value $profileExport| Out-Null | |
Write-Verbose "$keyname exists, overwriting" | |
} | |
} | |
function Connect-Port { | |
[cmdletbinding()] | |
param($hostname,$port,$sleep=10,$retry=10) | |
$hammertime = { | |
param($hostname,$port) | |
try { | |
$r = ($s = [System.Net.Sockets.TcpClient]::new($hostname,$port)).Connected; | |
$s.Close(); | |
return $r | |
} | |
catch { return $false } | |
return $false | |
} | |
$res = $false | |
while ($retry -gt 0 -and (-not ($res = $hammertime.Invoke($hostname,$port)))) { | |
write-verbose "Retrying $retry" | |
$retry -= 1 | |
start-sleep $sleep | |
} | |
return $res | |
} | |
function Connect-VSPLab { | |
if ((Get-Module VMware.VimAutomation.Cored -ErrorAction SilentlyContinue) -eq $null) { | |
Import-Module VMware.VimAutomation.Core | |
} | |
$connections = @(Get-VSPLabConnection) | |
if ($connections.Count -eq 0 ) { | |
write-error "Make a connection first please" | |
} else { | |
$connection = $connections[0] | |
if($connections.count -gt 1) | |
{ | |
Write-host "To whome should we connect? (0 to exit)" | |
$choice = -1 | |
while ($choice -eq -1) { | |
$i = 0 | |
foreach ($c in $connections) { | |
$i++ | |
write-host ("{2,2} {0}@{1}" -f $c.user,$c.address,$i) | |
} | |
[int]$choice = Read-Host -Prompt "Number : " | |
if (-not ($choice -ge 0 -and $choice -le $connections.count)) { | |
$choice = -1 | |
} | |
} | |
if ($choice -eq 0) { | |
return | |
} else { | |
$connection = $connections[($choice-1)] | |
} | |
} | |
if((Connect-Port -hostname $connection.address -port 902)) { | |
$cred = [System.Management.Automation.PSCredential]::new($connection.user,($connection.password|convertto-securestring)) | |
connect-viserver -server $connection.address -credential $cred | |
} else { | |
write-error "Could not connect to port 902 so no vsp running on $server" | |
} | |
} | |
} | |
function wait-vmshutdown { | |
while(($l = (get-vm | ? { $_.PowerState -ne "PoweredOff" })) -ne $null) { | |
Clear-Host | |
write-host (get-date) | |
$l | % { write-host ("{0,-15} {1,-15}" -f $_.Name,$_.PowerState)} | |
start-sleep -seconds 3 | |
} | |
} | |
function shutdown-vsp { | |
Get-VMHost | Stop-VMHost -Force -confirm:$false | |
} | |
function shutdown-vm { | |
param($vm) | |
stop-vmguest -confirm:$false $vm | |
} | |
function shutdown-lab { | |
connect-vsplab | |
get-vm | ? { $_.powerstate -match "On" } | % { shutdown-vm $_ } | |
wait-vmshutdown | |
if ($(get-vm | ? { $_.powerstate -match "On" }) -eq $null) { | |
shutdown-vsp | |
} else { | |
write-host "Could not safely shutdown" | |
} | |
} | |
function connect-vmrdp { | |
param($vm,$linuxusername="root") | |
$rvms = @(get-vm | ? { $_.name -match $vm }) | |
if ($rvms.count -gt 0) { | |
$rvm = $rvms[0] | |
if ($rvms.count -gt 1) { | |
Write-host "To whome should we connect? (0 to exit)" | |
$choice = -1 | |
while ($choice -eq -1) { | |
$i = 0 | |
foreach ($c in $rvms) { | |
$i++ | |
write-host ("{0} {1}" -f $i,$c.name) | |
} | |
[int]$choice = Read-Host -Prompt "Number : " | |
if (-not ($choice -ge 0 -and $choice -le $rvms.count)) { | |
$choice = -1 | |
} | |
} | |
if ($choice -eq 0) { | |
return | |
} else { | |
$rvm = $rvms[($choice-1)] | |
} | |
} | |
$connected = $false | |
$ct = 10 | |
while (-not $connected -and $ct -gt 0) { | |
$vmguest = $rvm | Get-VMGuest | |
if($vmguest -ne $null -and $vmguest.IPAddress.count -gt 0) { | |
if ($vmguest.OSFullName -match "windows") { | |
Connect-Port -hostname $vmguest.IPAddress[0] -port 3389 | |
Start-Process -FilePath mstsc -ArgumentList ("/v:{0}" -f $vmguest.IPAddress[0]) | |
} else { | |
Connect-Port -hostname $vmguest.IPAddress[0] -port 22 | |
start-process -filepath ssh -argumentlist ("-l $linuxusername",$vmguest.IPAddress[0]) | |
} | |
$connected = $true | |
} else { | |
write-host ("Try {0}" -f $ct) | |
$ct = $ct -1 | |
start-sleep -seconds 5 | |
} | |
} | |
} else { | |
write-host "Can not find $vm" | |
} | |
} | |
function set-vmsnapshotlatest { | |
param($vm) | |
$rvm = get-vm $vm | |
if ($rvm -ne $null) { | |
$snaps = $rvm| Get-Snapshot | |
if ($snaps.count -gt 0) { | |
$snap = $snaps | Sort-Object -Property Created -Descending | select -first 1 | |
set-vm -vm $rvm -snapshot $snap | |
} | |
} else { | |
write-host "Can not find $vm" | |
} | |
} | |
function new-vmwindows { | |
new-vmlinuxmini -os "windows9Server64Guest" -disksize 40 -mem 4 | |
} | |
function new-vmlinuxmini { | |
param( | |
$vsp = (@(Get-VMHost)[0]), | |
$datastore = (Get-Datastore -name ssd256), | |
$network = (Get-VirtualPortGroup -name "vm network"), | |
$diskformat = "Thin", | |
$vmname = (read-host "Name"), | |
#https://www.vmware.com/support/developer/converter-sdk/conv61_apireference/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html | |
$os = "debian9_64Guest", | |
$disksize = 5, | |
$reserveall = $true, | |
$mem = 1, | |
$cpu = 1 | |
) | |
$newvm = New-VM -Name $vmname -ResourcePool $vsp -Datastore $datastore -NumCPU $cpu -MemoryGB $mem -DiskGB $disksize -portgroup $network -CD -DiskStorageFormat $diskformat -GuestID $os | |
if ($reserveall) { | |
$spec = New-Object VMware.Vim.VirtualMachineConfigSpec | |
$spec.memoryReservationLockedToMax = $true | |
($newvm).ExtensionData.ReconfigVM_Task($spec) | |
} | |
return $newvm | |
} | |
set-alias -Name vspcon -Value connect-vsplab | |
set-alias -name vspdis -value Disconnect-VIServer | |
set-alias -name vspstop -value shutdown-vsp | |
set-alias -name vsphalt -value shutdown-vsp | |
set-alias -name vmls -value get-vm | |
set-alias -name vmlist -value get-vm | |
set-alias -name vmstart -value start-vm | |
set-alias -name vmstop -value shutdown-vm | |
set-alias -name vmhalt -value shutdown-vm | |
set-alias -name vmwait -value wait-vmshutdown | |
set-alias -name vmrdp -value connect-vmrdp | |
set-alias -name vmrevert -value set-vmsnapshotlatest | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment