Tidy PowerShell Logs

Experimenting with tidy ways to log files and output into one function to keep scripts a little clearer
11/11/2019 @ 1645hrs | .pwsh

I've been trying different methods with my scripts to log things I want to a log file that is in a customer requested format and at the same time writing the output of said items to host. All without having lots of lines packing out the script.

Plus it means you can make one change in a function (e.g. the format) and not have to go back and adjust all the times you try and "write" it out and all the times you "log" it.

# Set a location for a Log File
$LogFile = "C:\folder\filename.txt

# Set a new function to call when needed - Input format for entering is Message, NoNewLine, Colour
Function New-LogEntry($Message,$NoNewLineFlag,$Colour) {

    # Format DTG for tracking
    $LogInternalDTG = (Get-Date).ToString("yyyy/MM/dd HH:mm:ss")

    # Format for entering is Message, NoNewLine, Colour
    # This presents the output to host
    if ($NoNewLineFlag -eq 0) {
        if ($Colour) {
            Write-Host "$Message" -ForegroundColor $Colour
        } else {
            Write-Host "$Message"
        }
    } elseif ($NoNewLineFlag -eq 1) {
        if ($Colour) {
            Write-Host "$Message" -ForegroundColor $Colour -NoNewline
        } else {
            Write-Host "$Message" -NoNewline
        }
    }

    # This adds to the logfile
    Add-Content -Path $LogFile -Value "$LogInternalDTG - $Message"

}

# Example execution for a single item
New-LogEntry "This thing was done here" 0 "Cyan"

# Example execution for a processing task and when it completes
New-LogEntry "This task is doing a thing... " 1 "White"
New-LogEntry "Done!" 1 "Green"

# Example execution for an important task
New-LogEntry "ERROR - Something went wrong!" 0 "Red"

Refreshing the brain a little

Getting back into the swing of things in the new job and learning some new stuff too
21/10/2019 @ 2321hrs | .txt

I have been getting settled in the new job over the last couple of weeks and so far it has been OK. I have managed to spend a bit of time refreshing some skills parked in the back of the grey matter, which has been nice.

So what is the focus at the moment? Well, a few different things to be honest. Whilst I'm waiting to join a project, I have been brushing up on:

  • PowerShell (Obviously)
  • Microsoft Azure
    • Specifically automation with PowerShell
    • Also with Azure's Cloud CLI
  • PowerCLI
  • OpenShift (as a user)

That led on to getting some time to learn new things and/or expanding knowledge on:

  • Microsoft Azure Stack
  • OpenShift
    • Installtion and Configuration
    • MiniShift/OKD
  • Terraform
  • pfSense
  • Puppet

I've been doing a bit of a dance whilst waiting for the project to finalise what/when/if I'll be joining them from next week. So that could be exciting.

In addition to the planning around me being tied up with work for a while, I got identified as "the choice option for PowerShell work" today. This suddenly becomes much less exciting when it was actually just all the guys in the team actively pointing at me when posed the question "Who can help out with some PowerShell stuff?". Either way, I'll take it.

In all, more on the way is the sum of it but at least it keeps me out of trouble.


Server changes again

Playing about with some server mods for Minecraft. Taking me back to the good old days
09/10/2019 @ 2334hrs | .txt | .minecraft

Pretty tired, so I'll keep this short. Reset the server about a week ago, to add some stuff.

Now on a flat/creative with loads of animals! A Longleat looking build is in progress and you can now see it on the DynMap linked below. Oh and the server address has changed.

Dynamic Map

More soon. Zzz...


PowerShell Wallpaper

Just a quick wallpaper created for fans of the pwsh hero
07/10/2019 @ 2350hrs | .pwsh

Created a wallapper to match the colour theme of the PC a couple months back. Uploading here.

Nothing special.


Server reset and a friend

Playing about with the new server and breaking it. Probably still the best way to learn but we are up and building
28/09/2019 @ 2130hrs | .txt | .minecraft

Yeah I broke it. Ha! After the first couple of nights, I tried to be clever and add some stuff in to the game... it didn't like it. It is an extremely low-spec hosting, but it does for a small audience.

It isn't just me though, as a couple of others have said that they'll jump on to satisfy a recent need to play again also. Neat.

Just a quick look at the "spawn" so far. I tidied up the village and "modernised" it. #NoCobblestone


Builds new PC... plays Minecraft

Built a new PC! Very exciting! How to test it... well, with something that isn't this probably
24/09/2019 @ 0130hrs | .txt | .minecraft

I may have built a new rig last week and I absolutely love it. I'll get some pictures of it on here soon (waiting on radiator). However, even though I've just about finished the best build I've ever done, you'd think I would push it a little with something to see how it gets on, right?

My chosen game to play on it at the moment...? Minecraft. Haha. Now I know, I know... but it keeps me out of trouble and for now it is entertaining and will likely be a short phase. I'll be on there if you need me...

You'll have to be whitelisted if you want to jump on, so ping me a message via however. It is a vanilla, creative and peaceful map and there is no real objective but to just build stuff. You can get the address of the server by giving the control pad up there a boop.


PowerShell 7 - Preview 4 (v7.0.0.4)

A runthrough on installing PowerShell 7 - Preview 4
20/09/2019 @ 2341hrs | .pwsh | .windows

It has been an extremely busy couple of weeks, but I won't go into the details. Part of it comes down to starting a new job this week, which has allowed me to get my head back into some PowerShell. Hooray!

I have been playing about with Azure and Azure stack, so expect some ramblings about that in the coming weeks. However, just some notes and screengrabs about yesterday's v7.0.0-preview.4 release of PowerShell Core. First is how pretty the .msix installer is, but it wouldn't work on my machine. I need to do some digging into it... new to me.

The regular .msi was all good though. Our PowerShell hero standing tall here...

...and there is it...

The obligatory look at the line-up...

The Shell menu looks ace in the dark mode...

As for using it? Well, I haven't yet. I did have a read though this Microsoft blog, which has all you need to know.


PowerShell macOS - Get System Version and Build using "sw_vers"

Getting that all important OS version infomation from a Mac
07/08/2019 @ 0012hrs | .pwsh | .macos

Sniffing around in PowerShell on macOS, occasionally throws up things you didn't know existed in Terminal. Take sw_vers as an example.

There is nothing special here, but it does present your current OS Version and Build Version. Useful if you need to have a minimum requirement etc.

# Gather details from "sw_vers"
$OSProductName = (sw_vers -productName)
$OSProductVersion = (sw_vers -productVersion)
$OSBuildVersion = (sw_vers -buildVersion)

# Output with a dash of Cyan becuase I like the colour
Write-Host "Product Name: $OSProductName" -ForegroundColor Cyan
Write-Host "Product Version: $OSProductVersion" -ForegroundColor Cyan
Write-Host "Build Version: $OSBuildVersion" -ForegroundColor Cyan

PowerShell macOS - Get IP Address / Parsing "ifconfig" output

Following on from the last post, but this time to get the IP address infomation from your mac using PowerShell
01/08/2019 @ 2357hrs | .pwsh | .macos

Here is a horrible way to get your IP address(es) from pwsh on macOS. Parsing the ifconfig command and making it a bit more useful in PowerShell.

Works for IPv4 addresses only and if you need your loopback, just comment out the section to ignore it.

# Take ifconfig and find any line with a formatted IPv4 address in it. Exclude Loopback.
$FindIP = (ifconfig | Where-Object {$_ -match '\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s' } | Where-Object {$_ -notmatch '127.0.0.1'})

# Go through each line and break the line into an array
foreach ($IPItem in $FindIP) {
    $PossibleIPs = $IPItem.split(" ")
    $Get1IP = 0
    $Get1SN = 0

    # Find the IP and Subnet. Avoids Broadcast Address.
    foreach ($IP in $PossibleIPs) {
        # Find the IP
        if ($IP -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') {
            $ThisIP = $IP
            $Get1IP = 1
        }
        # Find the Subnet Mask
        if ($IP.StartsWith('0x')) {
            $ThisSN = $IP
            $Get1SN = 1

            # Create the Decimal version
            $SNarr = ($ThisSN.Substring(2)).ToCharArray()
            $x1 = $SNarr[0];$x2 = $SNarr[1];$x3 = $SNarr[2];$x4 = $SNarr[3]
            $x5 = $SNarr[4];$x6 = $SNarr[5];$x7 = $SNarr[6];$x8 = $SNarr[7]
            $Octet1 = "$x1$x2";$Octet2 = "$x3$x4";$Octet3 = "$x5$x6";$Octet4 = "$x7$x8"
            $Octet1 = [Convert]::ToInt64($Octet1,16)
            $Octet2 = [Convert]::ToInt64($Octet2,16)
            $Octet3 = [Convert]::ToInt64($Octet3,16)
            $Octet4 = [Convert]::ToInt64($Octet4,16)
            $ThisSNDec = "$Octet1.$Octet2.$Octet3.$Octet4"
        }
        if (($Get1IP -like 1) -and ($Get1SN -like 1)) {
            # Create them into objects
            New-Object -TypeName PSObject -Property @{
                IPv4Address = $ThisIP
                SubnetMaskHex = $ThisSN
                SubnetMaskDec = $ThisSNDec
            }
            Break
        }
    }
}

PowerShell macOS - Get Disk information / Parsing "DF" output

Using PowerShell to convert the DF output on macos into something that PowerShell can use
11/07/2019 @ 2337hrs | .pwsh | .macos

I have a whole bunch of scripts at work that pull back data from clients on the network. CPU, Disk, RAM, OS etc. However, I don't collect anything from our Macs, so I've started modifying scripts for PowerShell 6 (or 7) to allow them to be included too.

This, the first of many coming up, is something to get the Disk infomation. Disks, Free, Used, Percent Free that kind of thing. Ultimately it just parses the df command and makes it usable in PowerShell.

I would assume that this, combined with the $isOSX and $isWindows variables would make for a single script... for something... maybe. Ha.

# Capture the 'df' command into a variable
$DF = df

# Set structure for regex comparisons
[regex] $HeaderRegex = '\s*Filesystem\s+512-blocks\s+Used\s+Available\s+Capacity\s+iused\s+ifree\s+%iused\s+Mounted\s*on\s*'
[regex] $LineRegex = '^\s*(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\s*%)\s+(\d+)\s+(\d+)\s+(\d+\s*%)\s+(.+)\s*$'

# Create an object containg each line from $DF
$Lines = @($DF -split '[\r\n]+')

# See if the $DF header matches the $HeaderRegex or fail as the rest might not parse correctly
if ($Lines[0] -match $HeaderRegex) {

    # Skip the header and parse each line
    foreach ($Line in ($Lines | Select-Object -Skip 1)) {
        [regex]::Matches($Line, $LineRegex) | ForEach-Object {
            New-Object -TypeName PSObject -Property @{
                Filesystem = $_.Groups[1].Value
                '512-blocks' = [decimal] $_.Groups[2].Value
                Used = [decimal] $_.Groups[3].Value
                Available = [decimal] $_.Groups[4].Value
                CapacityPercent = [decimal] ($_.Groups[5].Value -replace '\D')
                iused = $_.Groups[6].Value
                ifree = $_.Groups[7].Value
                iusedPercent = [decimal] ($_.Groups[8].Value -replace '\D')
                MountedOn = $_.Groups[9].Value
            } | Select-Object Filesystem, 512-blocks, Used, Available, CapacityPercent, iused, ifree, iusedPercent, MountedOn
        }
    }
}
else {
    Write-Warning -Message "Error in output. Failed to recognise headers from 'df' output."
}

Editing content from my phone

Finding it too easy to edit content from my phone using this neat little app
09/07/2019 @ 0035hrs | .txt

I just thought I'd give this app a try. I am not using any CMS or even a DB for this content, as i spend too much time faffing about tweaking it nor do I have any real reason to use one. So adding a new post is just me editing a file... very... ermmm... traditional. However, to do so meant I would fire up the rig or a laptop, but I thought I would give this "Codeanywhere" a spin. Out of interest more than anything else I think. Not bad but the cursor is jumping about all over the place.


Keeping it really simple

I decided to re-design the website again to keep it all very simple
07/07/2019 @ 2353hrs | .txt

I decided to go back to basics and strip away all the structure and fancy pants design. There is something quite satisfying about a really raw look and feel to web content. I spend quite a bit of my “feet up” time looking at web design ideas and trends, but they just all start to look the same. If it isn’t the bootstrap special “one-page” efforts, it’ll be a full screen splash and loads of animation. The animation bit I really like and I’d love to be creative at, but the rest is just boring. This is still very “bootstrappy” but it is just stripped bare, and likely to change a million times still to the never decided goal of content that I spew into the internet. :)


Taking a quick look at PowerShell 7.0.0-preview

Having a quick look at PowerShell 7 Preview on a mac starting from where to get it
28/06/2019 @ 2350hrs | .pwsh | .macos

Alternative to Homebrew installer / Use a .pkg to install PowerShell 7 Preview on your Mac

Download from here: https://github.com/PowerShell/PowerShell/releases

You'll find the different versions under "Assets" but here is the one I've used: powershell-7.0.0-preview.1-osx-x64.pkg

Assuming you already have the latest full release, you'll get another icon in your Launchpad...