Scripting with Bash and PowerShell, verily

Skip to content

This doth be a machine-wrought text which may contain errors!

If thou hast performed the selfsame task for the third time, ‘tis time to automate it. Scripting doth concern itself with allowing the machine to do the tedious labour for thee, with greater speed and without forgetting aught.

Wherefore Automate?

Certain tasks in IT operation are oft performed:

  • To update servers
  • To create users
  • To take backup
  • To restart services after an update
  • To check that services do run

To perform these manually each time doth consume time, and ‘tis easy to forget a step. A script doth the same each time, without complaint.

Bash: Scripting in Linux

Bash doth be the shell (the terminal) in most Linux distributions, and ‘tis capable also of running scripts. A Bash script is naught but a text file containing commands which are executed in order.

Thy First Script

Create a file hight oppdater.sh:

#!/bin/bash
# Doth update the package list and install updates
echo "Oppdaterer systemet..."
sudo apt update
sudo apt upgrade -y
echo "Ferdig!"

Make the file runnable, and bid it run:

chmod +x oppdater.sh
# Gjør skriptet kjørbart.
./oppdater.sh
# Kall på skriptet for å utføre oppdateringen.

#!/bin/bash

The first line is hight a shebang. ‘T doth tell the operating system that this file shall be run with Bash. Without it, the system knoweth not which program to interpret the script withal.

Variables and Input

‘Tis meet we speak of variables and input, for these do form the very sinews of our calculations. A variable, good sirs, doth hold a value, which may be altered as the course of the program doth unfold. Think of it as a vessel, capable of containing divers quantities.

Input, on the other hand, is the manner whereby we impart knowledge unto the program from the world without. ‘Tis by input that we bid the program to act upon specific data, and thus achieve a desired outcome.

Consider, if you will, a simple example. We might declare a variable named “age,” and then request of the user their years, which shall then be stored within this selfsame variable. Thus armed, the program may proceed to tailor its responses according to the age provided.

#!/bin/bash
BRUKERNAVN=$1

if [ -z "$BRUKERNAVN" ]; then
    echo "Use: ./lag_bruker.sh <username>" # Bruk: ./lag_bruker.sh <brukernavn>
    exit 1
fi

sudo adduser "$BRUKERNAVN"
sudo usermod -aG sudo "$BRUKERNAVN"
echo "User $BRUKERNAVN created with sudo access." # Bruker $BRUKERNAVN opprettet med sudo-tilgang.

Here doth the script receive a username as argument ($1 being the first argument). Shouldst thou run ./lag_bruker.sh ola, ‘twill create the user ola and grant unto them sudo access.

Useful Bash Concepts

Concept Example What it doth
Variable NAVN="Ola" Doth store a value
Argument $1, $2 Input from the command line
If-check if [ -f "fil.txt" ]; then Checketh if a file doth exist
For-loop for f in *.log; do Doth something for each matching file
Pipe cat logg.txt \| grep "ERROR" Sendeth output from one command to another

PowerShell: Scripting in Windows

PowerShell doth be Windows’ answer to Bash, yet ‘tis more object-orientated. It worketh with objects, and not merely text, which doth render it puissant for the governance of Windows systems.

Example: Verify Disc Space

Husk at du må ha tilstrekkelig diskplass for å installere programvaren. Følg disse trinnene for å sjekke hvor mye ledig plass du har:

  1. Åpne Terminal.
  2. Skriv inn kommandoen df -h.
  3. Se etter / (rotpartisjonen) i utdataene. Kolonnen “Available” viser hvor mye ledig plass du har.

Hvis du ikke har nok plass, må du frigjøre plass ved å slette unødvendige filer eller programmer, eller ved å utvide partisjonen.

Hark, and take heed, for thou must possess sufficient disc space ere thou attempt to install this software. Follow these steps to ascertain how much room remaineth:

  1. Open the Terminal, I pray thee.
  2. Enter the command df -h.
  3. Seek out / (the root partition) within the output. The column titled “Available” doth reveal the measure of space yet free.

Shouldst thou find thyself lacking, thou must needs make room by deleting superfluous files or programs, or by expanding the partition itself.

# Prithee, examine the available disc space
Get-PSDrive -PSProvider FileSystem | Select-Object Name, 
    @{Name="Brukt (GB)"; Expression={[math]::Round($_.Used / 1GB, 2)}},
    @{Name="Ledig (GB)"; Expression={[math]::Round($_.Free / 1GB, 2)}}

Example: Installing Software with Winget

Winget er et kommandolinjeverktøy som lar deg installere og administrere programvare på Windows 10 og nyere. Det er en pakkehåndterer, omtrent som apt på Debian/Ubuntu eller brew på macOS.

For å installere et program med Winget, bruker du kommandoen winget install <programnavn>. For eksempel, for å installere 7-Zip, kan du kjøre:

winget install 7zip

Du kan søke etter programvare med kommandoen winget search <søketerm>. For eksempel:

winget search VLC

Winget kan også brukes til å oppgradere installert programvare. Bruk kommandoen winget upgrade for å oppgradere alle installerte programmer, eller winget upgrade <programnavn> for å oppgradere et spesifikt program.

Winget is a command-line tool which doth permit thee to install and manage software upon Windows 10 and later. ‘Tis a package handler, much as apt upon Debian/Ubuntu or brew upon macOS.

To install a program with Winget, thou dost employ the command winget install <program name>. For example, to install 7-Zip, thou mayest run:

winget install 7zip

Thou canst search for software with the command winget search <search term>. For example:

winget search VLC

Winget may also be used to upgrade installed software. Employ the command winget upgrade to upgrade all installed programs, or winget upgrade <program name> to upgrade a specific program.

# Installer more programs at once
winget install Mozilla.Firefox
winget install Microsoft.VisualStudioCode
winget install Git.Git
winget install Python.Python.3.12

This doth prove much swifter than to download and install all by hand. Thou mayst preserve the list within a script and run it each time thou dost set up a new machine.

Easy Task the First - A Script for Refreshing

Compose, pray thee, a Bash script which shall:

  1. Renew the catalogue of packages
  2. Install all updates that be available
  3. Restart Nginx (or some other service thou hast running)
  4. Print forth a message when ‘tis finished

Run it upon one of thy Virtual Machines and observe if it doth function as intended.

Easy Task the Second - Automate Machine Setup

Compose a PowerShell script (.ps1) or a simple list of winget install commands for all the programs thou dost require upon a new PC. Consider well:

  • Which programs dost thou ever install?
  • Might thou also configure some settings with the script?

The next time thou dost set up a machine, merely run the script instead of spending an hour upon manual installation.

Summary

  • If thou dost perform a thing more than twice, consider to automate it.
  • Bash (Linux) and PowerShell (Windows) be the most common tools for scripting.
  • Bash scripts are text files with commands which run in sequence.
  • PowerShell doth work with objects and is puissant for Windows administration.
  • Variables, arguments, if checks, and loops be the chief building blocks.