Greg's Tech blog

Powershell on Linux

Monday 18 of September, 2017

I've been learning a lot about Microsoft's Linux initiatives over the past couple weeks.  I've started using Windows Services for Linux in lieu of putty for connecting to my Linux machines and recently started playing with their PowerShell implementation on Linux.  Last week I had a need to do some scripting on Linux and wanted to re-use some code I had on hand. 

PowerShell can be installed from the repository on most machines.  The PowerShell github page has the details on how to configure your package manager to draw directly from the repository.

For my challenge, I wanted to profile the download speed of a particular website I help manage.  I already have a PS script that does most of what I wanted.  It was a simple task of reconfguring it and testing to be sure all the features were available in the current Linux PS beta.  Here's the script.

$url = "http://files.myfakeco.com/downloads/filedownload/d3974543.zip"
$timer = measure-command {
    $req = system.Net.WebRequest::Create($url)
    try {
        $res = $req.GetResponse()
        $requestStream = $res.GetResponseStream()
        $readStream = New-Object System.IO.StreamReader $requestStream
    catch System.Net.WebException {
        $res = $_.Exception.Response
$sec =  $($timer.totalmilliseconds)/1000
$size = $res.Contentlength
$kbs =  "{0:N2}" -f ($size/$sec/1000)
$ssec =  "{0:N2}" -f $sec
echo "$size, $ssec, $kbs"
"$(get-date -f "MM-dd-yyyy hh:mm tt"), $($res.StatusCode), $size, $ssec, $kbs `r`n"|out-file -append /mnt/samba/Docs/dllog.txt
The script makes use of the .Net WebRequest API. The API downloads the file and reorts status and stats derived from timing the download using measure-command.

But the best part of this is that the exact code runs on Windows Powershell.  I only modified the code to meet my specific needs for this report.