Scripting

Scripting

Welcome to the scripting hub, a dedicated space where we dive deep into automating tasks with scripts, exploring the endless possibilities within IT innovation. With over 15 years of experience in the dynamic IT industry, I’ve navigated through various roles—from providing frontline help desk support to designing complex systems architectures. Throughout this journey, automating tasks with scripts has proven to be an invaluable skill, enabling me to streamline operations, enhance productivity, and continually evolve my technical expertise.

As I continue this journey of mastering scripting, I’m eager to share my experiences and insights with fellow IT enthusiasts and professionals. While I do not claim to be an expert, my experience with automating tasks with scripts, particularly with PowerShell, Bash, and Python, has been driven by curiosity, experimentation, and a commitment to improving efficiency. Each script I write is not just a piece of code, but a solution to a problem, a step towards optimizing workflows, and a tool for better understanding the complexities of IT systems.

On this page, you’ll discover a curated collection of scripts, each crafted out of necessity and a desire to simplify the complexities of everyday IT tasks. Whether you’re looking to automate repetitive processes, manage infrastructure more effectively, or simply learn new techniques, you’ll find scripts that range from basic automation to more intricate optimizations. These scripts represent my ongoing learning process and my passion for automating tasks with scripts to make life easier for IT professionals.

Whether you are new to scripting and seeking a starting point or a seasoned professional looking to share your knowledge and provide guidance, this space is for collaboration and growth. Together, let’s delve into the nuances of scripting, learn from each other’s experiences, and continuously explore how to make the most of automating tasks with scripts.

Join me on this journey where every line of code is a step toward unlocking new capabilities, enhancing your IT toolkit, and mastering the art of scripting.

PowerShell

CodeSign

This script is designed to sign a PowerShell script file with a code signing certificate stored in a Personal Information Exchange (PFX) file.

# Change "Script-Name-Here.ps1" for you script file name!
# Specify the path to the PFX file containing the code signing certificate
$PfxFilePath = "C:\CodeSign\codesign-cert.pfx"

# Check if the PFX file exists
if (-not (Test-Path -Path $PfxFilePath -PathType Leaf)) {
    Write-Host "Error: PFX file not found at $PfxFilePath" -ForegroundColor Red
    return
}

try {
    # Get the certificate from the PFX file
    $certificate = Get-PfxCertificate -FilePath $PfxFilePath

    # Specify the path to the script to be signed
    $ScriptPath = ".\Script-Name-Here.ps1"

    # Check if the script file exists
    if (-not (Test-Path -Path $ScriptPath -PathType Leaf)) {
        Write-Host "Error: Script file not found at $ScriptPath" -ForegroundColor Red
        return
    }

    # Sign the script with the specified certificate and timestamp server
    Set-AuthenticodeSignature -FilePath $ScriptPath -Certificate $certificate -IncludeChain All -TimestampServer "http://timestamp.digicert.com"

    # Display the details of the code signing
    Get-AuthenticodeSignature $ScriptPath -Verbose | Format-List

} catch {
    Write-Host "Error occurred: $_" -ForegroundColor Red
}

Windows Uptime

Monitoring uptime on Windows 10 and 11 can be challenging when Fast Boot or Quick Boot is enabled due to the way these features affect system behavior during shutdown and startup.

Fast Boot, also known as Hybrid Boot or Fast Startup, is a feature introduced in Windows 8 and continued in Windows 10 and 11. When enabled, Fast Boot allows Windows to hibernate the kernel session instead of fully shutting down the system. This hibernation process involves saving the kernel session to the hiberfile (hibernation file) upon shutdown and restoring it upon startup, resulting in faster boot times.

While Fast Boot provides quicker startup times, it can affect the accuracy of uptime monitoring tools and techniques. Since the kernel session is hibernated rather than fully shut down, traditional methods of tracking uptime, such as checking system boot time using event logs or system information, may not reflect the true duration of system uptime.

Here is a PowerShell script i have writen to search for specific events related to system boot and shutdown in the Windows Event Log and then output the timestamp of the latest matching event.

# Define the Event IDs and messages to search for
$eventIDs = @(27, 1074)
$messages = @("The boot type was 0x0", "The boot type was 0x1", "The boot type was 0x2", "Shut-down type: power off")

# Initialize variable to store the latest event time
$latestEventTime = [datetime]::MinValue

# Get the events from the Event Log
foreach ($eventID in $eventIDs) {
    $events = Get-WinEvent -FilterHashtable @{LogName='System'; ID=$eventID} -ErrorAction SilentlyContinue

    # Loop through each event and check if the message matches
    foreach ($event in $events) {
        $message = $event.Message
        foreach ($searchMessage in $messages) {
            if ($message -match $searchMessage) {
                $eventTime = $event.TimeCreated
                if ($eventTime -gt $latestEventTime) {
                    $latestEventTime = $eventTime
                }
            }
        }
    }
}

# Output the latest event time, if any matching events were found
if ($latestEventTime -ne [datetime]::MinValue) {
    write-output "Last Boot/Reboot: $latestEventTime"
}

Windows Firewall Status

This script defines a function Check-FirewallEnabled that takes a parameter $ProfileName representing the firewall profile name. It then checks the status of the firewall for the specified profile using Get-NetFirewallProfile cmdlet. Finally, it outputs the status of each firewall profile.

# Function to check if firewall is enabled for a given profile
Function Check-FirewallEnabled {
    param (
        [string]$ProfileName
    )
    
    $FirewallStatus = Get-NetFirewallProfile -Name $ProfileName | Select-Object -ExpandProperty Enabled
    if ($FirewallStatus -eq 'True') {
        $Output = "Enabled"
    } else {
        $Output = "Disabled"
    }
    Write-Output "$ProfileName Firewall: $Output"
}

# Call the function to check Firewall status for each profile
Check-FirewallEnabled -ProfileName 'Domain'
Check-FirewallEnabled -ProfileName 'Public'
Check-FirewallEnabled -ProfileName 'Private'

Bitlocker Drive Encryption Status

This script defines a function Check-DriveEncryption that takes a parameter $DriveLetter representing the drive letter of the drive to be checked. Inside the function, it uses Get-BitLockerVolume cmdlet to check if BitLocker encryption is enabled on the specified drive. If BitLocker is enabled, it outputs “Encrypted”; otherwise, it outputs “Not Encrypted”. Please Note: This script must be run as administrator.

# Function to check if a drive is encrypted
Function Check-DriveEncryption {
    param (
        [string]$DriveLetter
    )

    $Drive = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='$DriveLetter'"
    
    # Check if BitLocker is enabled on the drive
    $BitLockerStatus = Get-BitLockerVolume -MountPoint $Drive.DeviceID -ErrorAction SilentlyContinue
    if ($BitLockerStatus) {
        $Output = "Encrypted"
    } else {
        $Output = "Not Encrypted"
    }

    Write-Output "$($Drive.DeviceID) $Output"
}

# Get a list of all drive letters on the device
$DriveLetters = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 } | Select-Object -ExpandProperty DeviceID

# Call the function to check encryption status for each drive
foreach ($DriveLetter in $DriveLetters) {
    Check-DriveEncryption -DriveLetter $DriveLetter
}

Bash

Update Check

Save this script to a file (e.g., check_updates.sh), make it executable (chmod +x check_updates.sh), and then run it using ./check_updates.sh. It will first check if apt-show-versions is installed, then update the package lists, use apt-show-versions to get the list of available updates, count them, and finally output the number of updates available.

#!/bin/bash

# Check if apt-show-versions is installed
if ! command -v apt-show-versions &> /dev/null; then
    echo "Error: apt-show-versions is not installed. Please install it using 'sudo apt install apt-show-versions'."
    exit 1
fi

# Update package lists
sudo apt update > /dev/null

# Use apt-show-versions to get the list of available updates and count them
updates_count=$(apt-show-versions -u | wc -l)

# Output the number of updates available
echo "$updates_count"

Ubuntu Auto Update

This script is designed to update and install all packages in ubuntu 22.04 (with phased patches turned off). How to turn of phased patches? A full guide on how to setup this script can be found here on the setup guides page.

#!/bin/bash

# Define a file to track progress
PROGRESS_FILE="/var/log/update-script-progress"

# Function to check if a reboot is required
check_reboot() {
    if [ -f /var/run/reboot-required ]; then
        echo "Reboot required. Rebooting now..."
        echo "step1_reboot" > $PROGRESS_FILE
        reboot
        exit 0
    fi
}

# Function to check the progress and continue where left off
check_progress() {
    if [ -f $PROGRESS_FILE ]; then
        PROGRESS=$(cat $PROGRESS_FILE)
        case $PROGRESS in
            "step1_reboot")
                echo "Continuing after first reboot..."
                step2_install_updates
                ;;
            "step2_updates")
                echo "Continuing after updates..."
                step3_install_kept_back
                ;;
            "step3_kept_back")
                echo "Continuing after installing kept-back packages..."
                check_reboot_after_updates
                ;;
            *)
                echo "Unknown progress state, starting from the beginning."
                start_script
                ;;
        esac
    else
        start_script
    fi
}

# Function to start the script
start_script() {
    check_reboot
    step2_install_updates
}

# Function to perform updates
step2_install_updates() {
    echo "Updating package lists..."
    sudo apt update

    echo "Upgrading installed packages..."
    # Set non-interactive frontend to avoid prompts
    sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y --with-new-pkgs

    echo "step2_updates" > $PROGRESS_FILE
    step3_install_kept_back
}

# Function to install kept-back packages
step3_install_kept_back() {
    echo "Installing kept-back packages..."
    # Install kept-back packages by explicitly listing them
    KEPT_BACK=$(apt list --upgradable 2>/dev/null | grep -P '^\S+' -o)
    if [ -n "$KEPT_BACK" ]; then
        sudo DEBIAN_FRONTEND=noninteractive apt-get install -y $KEPT_BACK
    fi

    echo "step3_kept_back" > $PROGRESS_FILE
    check_reboot_after_updates
}

# Function to check if a reboot is required after updates
check_reboot_after_updates() {
    check_reboot
    cleanup
}

# Function to clean up unnecessary packages
cleanup() {
    echo "Cleaning up unnecessary packages..."
    sudo apt autoremove -y
    sudo apt autoclean

    echo "System is up to date. No reboot required."
    rm -f $PROGRESS_FILE
}

# Start or continue the script
check_progress

Python

Coming soon!