Friday, December 18, 2020

Exploring Powershell... Getting My Mojo Back


So I've been out of the scripting game for a while, left uninspired and unappreciated I did other things, until recently.

I was finally inspired to work on a script that found the disk usage (consumed) and the n give me my top x consumers.

The Script is fairly simple, but I'm still learning so I had to figure things out a bit.

# =================================================================
#
# Calculates Disk Space Consumed and Top x consumers in path
#
# (C)opyright 2020 - Cameron Stevens - Please share freely
# =================================================================

if($args.Length -eq 2){
    $pathspec = $args[0]
    $listLimit = $args[1]
} else {
    write-host "Syntax: diskusage path topXcount`n`n$($args.Length)"`
         -ForegroundColor "Red"
    exit
}    

$largest = @()

# ------------------------------------------------------ Main()
function main {
    $largest = @()
    $count   = 0
    foreach($item in $(Get-ChildItem -Path $pathspec -recurse)){
        $count ++
        $total = $total + $item.Length
        $FSize = $item.Length/1024
        $FSize = $FSize -as [int64]
        $largest += @([pscustomobject]@{`
               FileSpec = $item.FullName `
             ; FileName = $item.Name `
             ; FileSize = $item.Length `
             ; FileSizef = "$($FSize.ToString('N0').PadLeft(10)) Mb"})
    }
    $totalMb = $total/1024
    $totalMb = $totalMb -as [int64]
    write-host "DiskUsage: $count files totaling $($totalMb.ToString('N0').PadLeft(10)) Megabytes (Mb).`n`n"
    $largest | Sort-Object -Property FileSize -Descending | `
        Select-Object -Property FileName, FileSize, FileSizef | `
        Select-Object -First $listLimit}


# ======================================================

    Main # ----- Let's get this started.

# ====================================================== EOF

So, I cannot promise it's amazing, or even well written, but it's cool. I wrote and tested in using Powershell on Linux, but I'm certain it'll work on Windows too.

Oh, and if you'd prefer a full path to the files change this:

    $largest | Sort-Object -Property FileSize -Descending | `
        Select-Object -Property FileName, FileSize, FileSizef | `
        Select-Object -First $listLimit}

 To:

    $largest | Sort-Object -Property FileSize -Descending | `
        Select-Object -Property FileSpec, FileSize, FileSizef | `
        Select-Object -First $listLimit}

Giving you this:

    

Now, you can make this better, perhaps adding command-line parameters, to offer more choices, but let this be inspiration. It was for me.


There is no individual ownership when you are part of a team, it's the sum of the parts that makes you the RESILIENT team you need to be.