Making the windows terminal great again

Once again my employeer forces me to work from an inferior platform, so what are my options to get the best possible working environment? Heres some tips to what I’ve done so far.

The windows terminal is one of the better things produced by Microsoft the last couple of years. I have already written a bit about it before, so search for windows terminal, and you will get the other articles. Even though the terminal is nice, there are some minor annoyances, when you are used to work in a bash environment.

  1. No nice “inline” editor
  2. Does not obey ctrl-d to exit the session
  3. Does not have tab completion on entries in the ssh config file

To fix these three annoyances, we need to download vim from www.vim.org, install it and the rest is done creating and configuring a powershell profile, lets dive into it.

Not only do I have to work from a windows machine (my department does primarily FOSS solutions) I also don’t have any elevated permissions on my machine. IT proffesionlas are treated just the same as office workers 🙁

This means I cannot install any software, besides whats picked by the Windows admins. Luckily vim is not picky, and you can install it in your own home folder. So lauch the installer and change the install path accordingly.

When vim is installed, all we need to do is to create a powershell profile file. The file has to be named Microsoft.PowerShell_Profile.ps1 and has to be placed under $home\Documents\PowerShell\
When placed here it will be a user specific profile, you can also do system-wide profiles, take a look at $pshome.

The profile file I have created looks like this:

using namespace System.Management.Automation

# Set aliases

Set-Alias -name vim $home\Vim\vim90\vim.exe
Set-Alias -name vi $home\Vim\vim90\vim.exe

# Obey ctrl-d

Set-PSReadlineKeyHandler -Key ctrl+d -Function ViExit

# Enable ssh tab completion
# Credits to backerman and contributers at github for creating the code

Register-ArgumentCompleter -CommandName ssh,scp,sftp -Native -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)

function Get-SSHHostList($sshConfigPath) {
    Get-Content -Path $sshConfigPath `
    | Select-String -Pattern '^Host ' `
    | ForEach-Object { $_ -replace 'Host ', '' } `
    | ForEach-Object { $_ -split ' ' } `
    | Sort-Object -Unique `
    | Select-String -Pattern '^.*[*!?].*$' -NotMatch
}

function Get-SSHConfigFileList ($sshConfigFilePath) {
    $sshConfigDir = Split-Path -Path $sshConfigFilePath -Resolve -Parent

    $sshConfigFilePaths = @()
    $sshConfigFilePaths += $sshConfigFilePath

    $pathsPatterns = @()
    Get-Content -Path $sshConfigFilePath `
    | Select-String -Pattern '^Include ' `
    | ForEach-Object { $_ -replace 'Include ', '' }  `
    | ForEach-Object { $_ -replace '~', $Env:USERPROFILE } `
    | ForEach-Object { $_ -replace '\$Env:USERPROFILE', $Env:USERPROFILE } `
    | ForEach-Object { $_ -replace '\$Env:HOMEPATH', $Env:USERPROFILE } `
    | ForEach-Object { 
    $sshConfigFilePaths += $(Get-ChildItem -Path $sshConfigDir\$_ -File -ErrorAction SilentlyContinue -Force).FullName `
    | ForEach-Object { Get-SSHConfigFileList $_ } 
    }

    if (($sshConfigFilePaths.Length -eq 1) -and ($sshConfigFilePaths.item(0) -eq $sshConfigFilePath) ) {
        return $sshConfigFilePath
    }

    return $sshConfigFilePaths | Sort-Object -Unique
}

$sshPath = "$Env:USERPROFILE\.ssh"
$hosts = Get-SSHConfigFileList "$sshPath\config" `
| ForEach-Object { Get-SSHHostList $_ } `

# 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
    }
}

$hosts `
| Where-Object { $_ -like "${textToComplete}*" } `
| ForEach-Object { [CompletionResult]::new((&$generateCompletionText($_)), $_, [CompletionResultType]::ParameterValue, $_) }}

Exit your terminal and lauch it again, hopefully you can be a bit more productive with the new “features”

Find and unmount CD drives with PowerCLI

Sometimes someone forgets to unmount the CD drive of a VM. This will interfere with operation tasks like setting a host in maintenance mode or using Update Manager.

I recently had this issue, and the “update manager compliance check” told me that several VM’s where connected to a CD drive, which may interrupt the update process. I quickly found my favorite tool for vcenter management, the powerCLI. The quick and dirty oneliner ended up like this:

get-cluster %clustername% | get-vm | where {(($_ | Get-CDDrive).isopath) -gt ""} | %{$_ | Get-CDDrive | Set-CDDrive -NoMedia -Confirm:$false}

Replace %clustername% with your cluster name, and all your troubles will be over 🙂

I have always loved oneliners. I have spent the part time of my time working in bash terminals, where the history has always been persistent. Luckily Microsoft has also seen the light, and history is now persistent (and searchable) in powershell. Search for a phrase using ctrl+r, search further back by pressing ctrl+r again. I’m sure you will learn to love it, if you don’t already do.

Balance your VMs across ESXi hosts in a vSphere cluster with local storage

The Citrix guys in my company has a bad habbit of using local storage, probably because they have had some bad performance experiences in the past. Local storage is not good for the vSphere admin, as vMotion is set out of play, and I need to move things around manually when doing maintenance. Furthermore the Citrix provisioning tool is not very good at launching/deploying VM’s on hosts that has a lot of free resources, so pretty often we end up with clusters where 50% of the hosts is utilizing 90% of the resources (mainly memory) and 50 % is doing nothing 🙁

To mitigate this I have written a script to “balance” the VM’s equally across the clusters. The script takes a parameter with the cluster name, and you are able to exclude specific hosts by editing the file.

# Script to balance VMs across ESXi hosts in cluster using local storage.
# Created by kasper@nordal-lund.dk
# Execute with cluster name as parameter
param(
[string]$cluster
)

#Make sure the vmware modules are loaded
Get-Module -name vmware* -ListAvailable | Import-Module

#Connect to the viserver
connect-viserver hostname.vcenter -alllinked -Credential (Get-Credential)

#$cluster = "xxx" # Manually define the cluster value. For testing purposes.

# Exclude hosts from the operation, use * as wildcard and seperate with |
$excluded = "" 

#Check if the cluster parameter is set.
if ($cluster -eq "") {
    write-host "You forgot to specify a cluster, please try again..."
    exit
}

# Fire up the main loop
while ($true) {

# Pull out the target hosts
$hosttargetsRaw =  get-cluster $cluster | get-vmhost | where {($_.connectionstate -eq "Connected")} | select name,@{N="VMCount";E={(get-vm -location $_.name).count}} | Sort-Object VMCount -Descending

# Trim the list for exclusions 
$hosttargetstrimmed = $hosttargetsRaw -notmatch $excluded

# Calculate the difference between the most and least populated hosts
$diff = ($hosttargetstrimmed | select -First 1).VMCount - ($hosttargetstrimmed | select -Last 1).VMCount

if ($diff -gt 4) {

# Define the source and destination hosts
$sourcehosts = $hosttargetstrimmed | select -First 2
$desthosts = $hosttargetstrimmed | select -last 2

# Check if we have only one hosts doing nothing
$bottomdiff = ($desthosts | select -first 1).VMcount - ($desthosts | select -Last 1).VMCount

$i = 0

foreach ($sourcehost in $sourcehosts.name){
	if ($bottomdiff -gt 4) {
        $curdesthost = $desthosts[1].name
    }else {
        $curdesthost = $desthosts[$i].name
	    $i++
    }
# Get the destination datastore		
$destds = (get-datastore -vmhost $curdesthost local*).name

# get the VM's we want to move
$targets = get-vmhost $sourcehost | get-vm | select -first 2

# Move the VM's 2 from each hosts = 4 VM's pr. loop
foreach ($target in $targets) {
    echo "move-vm -vm $target -Destination $curdesthost -Datastore $destds -RunAsync"
   }
}
# Wait for the VM's to be moved before looping again.  
sleep -Seconds 90
}else {
    write-host "Balancing of cluster $cluster is finished, difference between most and least populated host is $diff VMs..."
exit
}
}

I hope you are able to use this, at least as inspiration for getting on with your own.
And remember, this script can of course be combined with my powershell menu script found here: https://www.nordal-lund.dk/?p=574

Enjoy…

Powershell menu script

Do you ever need to give some input to a script? Maybe its a long filename or some other long and complex string, or maybe you’re just lazy like me? I wrote a script for handling the input, it’s a bit like the curses based menus you see in some network equipment, and in Linux systems. The eaxmple below is for getting the firmware baseline for a HP OneView system, but the menu is usable almost everywhere you need to specify something.

Lets stop talking, and take a look at the actual script:

param(
[string]$selection
)

if ((get-module hpone*).count -lt 1){
Get-Module -name hpone* -ListAvailable | Import-Module -WarningAction SilentlyContinue
}

if ($Global:connectedSessions){
    echo "Already connected..."
    } else {
    Connect-HPOVMgmt -Appliance ADDRESS -Credential (Get-Credential)
}

$global:MenuOptions = get-hpovbaseline

if ($Selection -eq ""){

    Clear-Host
    Write-Host "================Select Firmware Version================"
    
    $MenuNumber = 1
    foreach ($Option in $MenuOptions.version){

    Write-Host "$MenuNumber : $Option"
    $MenuNumber++
    }
    Write-Host -ForegroundColor red "Quit: Press 'ctrl-c' to quit."

    [int]$Selection = Read-Host "Please select firmware by number"
    
}

$baseline = $MenuOptions[$Selection -1]

The above code has some checks in the beginning to see if we have the right modules loaded, and if we are connected to the OneView server. This is not needed for the menu, but maybe it can be useful for you anyway.
In this example I’m listing the firmware included in the baselines from an HP OneView system, and the $baseline variable will have the selection I made.
This is usable for all kinds of interactions with other systems, e.g. its also very usable for vmware vCenter.
The selection parameter is there if you run this task often and already know what to select, then you can add it as an attribute to the script.

Please enjoy using the script.

Test network connection with powershell

Sometimes you need to test the network connection for a range of IP addresses. Normally I would use ping from a commandline, but it could be a hugh task to test more than 20-30 addresses.
Utilizing a bit of powershell and the test-connection command will help us overcome the task in an easy way:

[code language=”powershell”]1..100 | %{write-host -nonewline "Testing 10.0.0.$_ : "; Test-Connection 10.0.0.$_ -quiet -Count 1}[/code]

The above one-liner will test the connection to all hosts in a range from 10.0.0.1 to 10.0.0.100 and giva a False or True status.
Remember that % is a short way of using the foreach loop, so you could use “foreach” instead of %.

Using Vim as editor in PowerShell

If you are used to using Vim or Vi as your editor, you might miss it when using powershell. Good news is, theres a way to get it. Download and install Vim for windows, create a profile.ps1 file in this path: (for me at least) c:\users\%username%\documents\WindowsPowerShell\ and type in the following:

$VIMPATH    = “C:\Program Files (x86)\Vim\vim74\vim.exe”

Set-Alias vi   $VIMPATH
Set-Alias vim  $VIMPATH

# for editing your PowerShell profile
Function Edit-Profile
{
vim $profile
}

# for editing your Vim settings
Function Edit-Vimrc
{
vim $home\_vimrc
}

Remember to change the $VIMPATH to your installation.

Now you have a fully functional vim from powershell.

/Kasper