profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Friday, August 5, 2016

SSH PowerShell tricks with plink.exe

Okay i know i know, i am re using the same title from alan renouf's [http://www.virtu-al.net/2013/01/07/ssh-powershell-tricks-with-plink-exe/ ] site but this is in actuality the same content too.
The original scriptlet from alan renouf served me well so far untill i realized it won't do the 2 things that I want
1. There is no time out for the plink download, if it is blocked in your environment then it will just hang there and you have to close your powershell/powercli/ise to restart the whole process.
2. It won't wait for the user to manually copy the plink in that folder.
I thus decided to go with
Invoke-RestMethod 
Instead of
net.webclient
Since the former offers a time out period.
I also did a small do loop to keep asking for plink if it is not present in the folder. Another good thing about
Invoke-RestMethod 
is, it will download it to the root directory of the script without you mentioning it. Nice han!
Here is how the function looks
$PlinkLocation = $PSScriptRoot + "\Plink.exe"
$presence = Test-Path $PlinkLocation
if (-not $presence)
    {
    Write-Host "Missing Plink.exe, trying to download...(10 seconds)" -BackgroundColor White -ForegroundColor Black
    Invoke-RestMethod "http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe" -TimeoutSec 10 -OutFile "plink.exe"
    if (-not $presence)
        {
            do
            {
            Write-Host "Unable to download plink.exe, please download and add it to the same folder as this script" -BackgroundColor Yellow -ForegroundColor Black
            Read-host "Hit Enter/Return once plink is present"
            $presence = Test-Path $PlinkLocation
            } while (-not $presence)
        }
    }

if ($presence) { Write-Host "Detected Plink.exe" -BackgroundColor White -ForegroundColor Black }
as you can see the line one is the location of the plink (root directory of the script).
2nd line creates a variable to check whether that plink’s path is true or not. The rest is pretty straight forward from then onwards.
You can always get it from my github page.
github.com/mrambig/vmware
 

No comments:

Post a Comment