Bits and Bytes
Synopsis
I've been doing things with computers for a billion years now, and over that time I've picked up a myriad of odds & sods and bits & bobs of helpful - or just silly - processes, code and just ideas. With search now becoming a bit of lost art, I thought I'd stick all of them on a single page. Therefore, this lot of stuff doesn't have any coherent thread running through it. It's just a collection of things. As this comes from different times there is a difference in the coding styles and formatting. It's a historical record, so I'm not going to change it. I've added a few extra comments where I think they'll be helpful. For all you still using Perl, here's a link to my Perl code going back about 10-15 years.
Disclaimer
A lot of the code you'll see here probably isn't the best, most efficient or fastest way of doing something. But it all works - for me at least - and at the time it was good enough. Some of it may be a little bit verbose, but I've found that a bit of verbosity helps you understand it when you come back to it in 6 months. Clever code is all well and good, but it's useless when you can't make head nor tail of your brilliance... Also, this code is free to use for whatever you want, but you do so at your own risk.
Index
Make your computer talk though PowerShell (and .Net)
A little bit of fun to start the page off. This one just takes a string as the first command-line parameter (remember to stick quotes around it) and reads it aloud. Uses a .Net assembly to do the speech. Uses the default voice - on my system that's an American woman - but you can change that by setting different parameters to the $talker object. How to make those changes is left as an exercise for the reader.
Usage: .\speak.ps1 "My voice is my password"
# Get the commandline parameter
param( [string]$speakmystring )
# Add the speech assembly
Add-Type -AssemblyName System.speech
# Create the speech object
$talker = New-Object System.Speech.Synthesis.SpeechSynthesizer
# Say our words
$talker.speak($speakmystring)
Show disks with less than 20% free space using PowerShell
This one will just list through the drives on your computer, including any mapped network drive, and show how much free space they have (in Gb). It'll highlight in red those with less than 20% free, and in green for those will more than 20% free.
Usage: .\freespace.ps1
# Firstly we get all the disk information, excluding optical media (by using the where-oject cmdlet
# to exclude any objects where the drivetype=5).
# Then we pipe this into a foreach-object cmdlet which will iterate through the object(s) returned
# performing the commands between the {}s. We use the semi-colon (;) as the end character to separate commands.
# For the ease of reading we want the freespace to be in gb, rounded to two decimal places.
# We do this here so that we can just drop in the variable when we're outputing and also because we can't
# use the [math]:: functions within a Write-Host cmdlet.
# Now we start writing information; firstly we write the deviceid (aka the drive letter).
# We then do a bit of maths to determine if the freespace is less than 20% of the total space.
# If it is then we output the freespace (the rounded variable version that we made in the step above)
# in a foreground colour (or "color" as PowerShell insists it's called) of red, otherwise we'll output the value in green.
# Then we write out the providername - if we dealing with a network drive then this will be the
# UNC path; local drives will be blank.
# The output is separated by single tabs, so we can dump this output to a .CSV (technically it'd be a .TSV) and
# sling it into Excel or whatever. Though, as we're using Write-Host (so we can have colour) rather than Write-Output
# we'll need to run this command from a CMD window and then redirect the output to a file.
(Get-WmiObject win32_logicaldisk | where-object {$_.drivetype -ne 5}) |
foreach-object {
$spaceingb = [math]::round($_.freespace/1gb,2);
write-host -nonewline $_.deviceid;
if ($_.freespace/$_.size -lt 0.2) {
write-host -foregroundcolor red `t$spaceingb GB -nonewline
} else {
write-host -foregroundcolor green `t$spaceingb GB -nonewline
};
write-host `t $_.providername;
}
A sine wave screensaver effect in a PowerShell window
Inspired by Dave Plummer's video on making a Matrix style screensaver where he scrolls a sine wave (or three) down the screen using ANSI control codes, I thought I'd give it a while. The version of PowerShell I'm using doesn't support ANSI control codes (I think that's version 7 and above), so it scrolls it upwards instead. The code will adjust it's width to the console window and you can change the width of the line - it's just a collection of characters.
Usage: .\text-sine.ps1
# Make a command-line sine wave
# PowerShell trig functions work on radians
# rad = deg * (pi/180)
# To get value between 0 and -1
# [math]::sin($deg * ([math]::pi/180))
# Uses [system.console]::keyavailable to check if a key has been pressed, stopping if it has.
# Setup some variables
$hostwidth = $Host.UI.RawUI.WindowSize.Width
$display_char= ".-=:§[#]§:=-."
$dcl = $display_char.length
$hostwidth = ($hostwidth - (2 * $dcl)) / 2
$centre = $hostwidth + ($dcl / 2)
$delay = 15
$continue = $true
$str_colours = "DarkGreen", "DarkCyan", "DarkYellow", "Gray", "DarkGray", "Green", "Cyan", "Red", "Magenta", "Yellow", "White"
$change_colour = 360 / $str_colours.count
$clear_screen_after = $str_colours.count * 4
$number_of_runs = 0
$lowest_speed = 2
$speed = $lowest_speed
$speed_inc = 1
$max_speed = 18
Clear-Host
While ($continue -eq $true) {
$str_colours = $str_colours | Sort-Object {Get-Random} # Shuffle the colour order
For ($deg = -90; $deg -lt 270; $deg = $deg + $speed) { # Start at -90 to draw at left-hand column
# Calcualte where we're drawing
$offset_delta = [math]::sin($deg * ([math]::pi/180))
$offset = ($centre * $offset_delta)
$location = [math]::round($centre + $offset + $dcl)
# Pad the string to get us to the location
$display_str = $display_char.PadLeft($location, " ")
# Change the colour at equal time based on how many colours we're using
$str_colour_num = [math]::truncate(($deg / $change_colour))
$str_colour = $str_colours[$str_colour_num]
# Write the string
Write-Host -ForegroundColor ${str_colour} "${display_str}"
# Wait a little bit to avoid screen tearing and check for a keypress to exit
Start-Sleep -Milliseconds $delay
If ([system.console]::keyavailable) {
$continue = $false
break
}
}
# Clear the screen after a set number of runs, stops the screen buffer filling up
$number_of_runs++
If ($number_of_runs -gt $clear_screen_after) {
Clear-Host
$number_of_runs = 0
}
$speed = $speed + $speed_inc
If ($speed -eq $max_speed) { $speed_inc = -1 }
If ($speed -eq $lowest_speed) { $speed_inc = 1 }
}
Using dates in Windows batch files
Sometimes when you're using batch files you'll find a need to use date and or the time. The below shows you how to put them all into their own variable and combine them as you see fit. It's based on the UK time and locale settings of DD/MM/YYYY and time in HH:MM. Notice there are no spaces either side of the equals sign when using the Set command - they'll be included as part of your variable name and/or value if you include them.
The :~a,b part of the Set command works like a sub-string command. It'll 'chop' out the number of characters specified by b starting at location a (baring in mind that it's zero-based).
REM Set the DATE variables
set year=%date:~6,4%
set month=%date:~3,2%
set day=%date:~0,2%
REM Set the TIME variables
set hour=%time:~0,2%
if %hour% lss 10 set hour=0%hour:~1,1%
set min=%time:~3,2%
REM Ouput the variable - this is optional and is give as an example
echo %year%-%month%-%day% %hour%:%min%
Using dates in PowerShell
Like in the above, sometimes it's helpful to be able to use date and time variables in PowerShell. There's a couple of way's for getting the time. We can use the TimeOfDay property. Or we can use the ToString method and use a string pattern.
# Get the time and date now - this should be in your locale settings
$now = Get-Date
# Get the time variables
$hours = $now.TimeOfDay.Hours
$minutes = $now.TimeOfDay.Minutes
# Get the time variables another way
$hours = $now.ToString("HH") # 24-hour clock
$hours = $now.ToString("hh") # 12-hour clock
$minutes = $now.ToString("mm")
# Get the date variables
$year = $now.Year
$month = $now.Month
$day = $now.Day
# Get the date variables another way
$year = $now.ToString("YY") # 2-digit years - not Y2K compliant...
$year = $now.ToString("YYYY") # 4-digit years
$month = $now.ToString("MM") # 2-digit month
$month = $now.ToString("MMM") # 3-letter month
$month = $now.ToString("MMMM") # Full name of the month
$day = $now.ToString("dd") # 2-digit month
$day = $now.ToString("ddd") # 3-letter day of the week
$day = $now.ToString("dddd") # full day of the week
Get a random number in a batch file
Sometimes - and I'm not really sure when - you'll need a random number in a batch file. There's an environment variable - %random% - which will give a value between 0 and 65535 (a 16-bit value). That's often too big of a range though. This script will let you specifiy the start and end values for your range. The Set command has a /a parameter that we use when we want to do some arithmetic.
Usage: .\random-number.bat low_value high_value
@echo off
REM This will output a random number between the %minimum% and %maximum% values
REM Takes parameters from the commandline as %1 and %2 respectively
REM Obviously, %minimum% MUST be lower than %maximum%
REM Currently, there are no checks made on the validity of parameters, or even if they're entered
REM Set limits
set minimum=%1
set /a maximum=%2 +1
:create_value
REM Get our value. The modulo divide symbol is %, but we need to escape it in a batch file. We add %minimum%
REM to keep us within the range. We've already added +1 to %maximum% to keep us within the range
REM We stick a label marker in so that we can loop around if we need a lot of values.
set /a number=%random% %% (%maximum%-%minimum%) + %minimum%
REM Output the value with a carriage return, or...
echo %number%
REM ...output the value without a carriage return.
REM echo | set /p=%number%
REM If we want a stream of random values, then un-REM the line below
REM goto create_value
Pseudo-code for a simple wave folding algorithm
This is a simple variation on a wave folding algorithm I wrote at some point towards the end of the last century (and doesn't describing the 1990s like that make us old feel old!). For ease of explanation of what wave folding is and how it works, I'm just going to use the positive side of the waveform - it mirrors for the negative side - and use signed 8-bit values (-127 to +127).
In it's simplest form a wave folder changes the direction of change in a set of values in a waveform when those value go above a certain threshold. Here's a picture of a sine wave. The grey line is the 0 point, the red line is the threshold we're going to set.

In our algorithm, the values above the red line - our threshold - will be flipped so that they are below the threshold. This is, basically, wave folding and it introduces more harmonic content into the sound.

Where that threshold sits determines how much of the wave gets folded, along with the frequency (or frequencies) that get added.
$value = The signed value we're taking from either a sample or from a audio-digital converter (ADC)
$positive_threshold = The value where we're setting our positive threshold
$negative_threshold = The value where were settings our negative threshold, we're making these two different
to allow us more variety with our final waveform.
$new_value = The value we're going to use, either to write to a sample or the digital-audio converter (DAC)
If ($value > $positive_threshold) {
$new_value = $positive_threshold - ($value - $positive_threshold)
} ElseIf ($value < $negative_threshold) {
$new_value = $negative_threshold - ($value - $negative_threshold)
} Else {
$new_value = $value
}
Psuedo-code for a more complicated wave folding algorithm
While our algorithm above works perfectly fine, we're reducing the overall amplitude of our sample - and while the extra harmonic content may make up a little for that, it's going to give us a quieter sound. So, why not throw in some gain? It's easy enough done with quick multiple of the $value variable before we hit our If blocks.
However, when we start getting a bit eager with our gain we may find that our $new_value variable ends up going so much into the negative that it goes beyond the bounds of our sample range (in this example -127, but in most cases you'll probably be dealing with 16-bit data so that'd be -32768). Now, we can't write that value into our sample data so we need a way to limit its value. A threshold if you will. You can probably already see where this is going. We can adjust our pseudo-code a little and add in a secondary wave fold. It shouldn't introduce too much overhead and the algorithm should still remain quite performant.
If you're feeling brave and have processor cycles to spare you could probably keep nesting this over and over again to get even more harmonic content. I'll leave that as an exercise for the reader.
$value = The signed value we're taking from either a sample or from an audio-digital converter (ADC)
$positive_threshold = The value where we're setting our positive threshold
$negative_threshold = The value where were settings our negative threshold, we're making these two different
to allow us more variety with our final waveform.
$new_value = The value we're going to use, either to write to a sample or the digital-audio converter (DAC)
$gain = How much to amplify our $value by
$value = $value * $gain
If ($value > $positive_threshold) {
$new_value = $positive_threshold - ($value - $positive_threshold)
If ($new_value < $negative_threshold) {
$new_value = $negative_threshold - ($new_value - $negative_threshold)
}
} ElseIf ($value < $negative_threshold) {
$new_value = $negative_threshold - ($value - $negative_threshold)
If ($new_value > $positive_threshold) {
$new_value = $positive_threshold - ($new_value - $positive_threshold)
}
} Else {
$new_value = $value
}
Use PowerShell to get a list of listening ports
Sometimes you might have the need to find out all the ports that you've got open on a machine. You might then want to know if there's a firewall rule setup to accommodate those ports. If that's the situation you're in - and I'll grant you it's a bit niche - then this code will help you out.
What this code does is look for all the ports that have a state of Listening. It then uses their Process ID (aka PID) to get their process name and description. It'll then check the existing firewall rules to see if a rule exists to allow access to the port.
# Get the list of ports that have a state of 'Listen'. Use the process id to look up the name and description.
# Check the firewall to see if the port is already covered by a firewall rule.
# Write a header
Write-Host "LocalPort,ProcessName,ProcessID,Description,HasFirewallRule"
# Get our list of listening ports
$portlist = Get-NetTCPConnection | Where-Object {$_.state -eq "Listen"} | Sort-Object -Property LocalPort
# Get our list of firewall rules. To avoid having to repeatedly querying the rules, we can get them once
# and then query the results
$firewallrules = Get-NetFirewallPortFilter
# Iterate through our list of ports and get the process name
ForEach ( $port in $portlist ) {
# Set port and process variables
$localport = $port.LocalPort
$owningprocessid = $port.OwningProcess
# Look up the process, store the details in variables
$owningprocess = Get-Process -ID $owningprocessid
$owningprocessname = $owningprocess.ProcessName
$owningprocessdescription = $owningprocess.Description
# Look up to see if there is a firewall rule
$hasfirewallruleboolean = $firewallrules | Where-Object -Property LocalPort -EQ $localport
If ($hasfirewallruleboolean) {
$hasfirewallruletext = "True"
} Else {
$hasfirewallruletext = "False"
}
# Write out the data to the console
Write-Host "${localport},${owningprocessname},${owningprocessid},${owningprocessdescription},${hasfirewallruletext}"
}
Create multiple firewall rules in one go using PowerShell
Using the code above we can find out what ports we might need to create a set of rules for. This script takes the port - or even a range of ports - and a description from a CSV file and creates a set of rules. To make management easier we'll give all the rules the same group name.
# Create a rules for a collection of file ports. Their numbers and descriptions are given in a CSV file
# Needs to run as admin to make the rules.
#
# CSV needs to be formatted thusly -
# 80, This is HTTP
# 9000-9010, Something that's using 11 ports
# ...
$port_number = 0
$rule_name = ""
$rule_description = ""
$protocol = "TCP"
$rule_group = "Custom Rule Name Goes Here"
$portsfile = ".\A-List-Of-Open-Ports-To-Make-Rules-From.csv"
# Import the values
$portdata = Import-Csv -Path $portsfile -Header port, description
# Iterate through each row
ForEach ( $ruleitem in $portdata) {
# Set the variables from the CSV
$port_number = $ruleitem.port
$rule_name = $ruleitem.description
$rule_description = $ruleitem.description
# Display what we're creating
Write-Host "Port Number: " -NoNewLine
Write-Host -ForegroundColor Green "$port_number"
Write-Host "Creating rule: " -NoNewLine
Write-Host -ForegroundColor Green $rule_name
Write-Host "Description: " -NoNewLine
Write-Host -ForegroundColor Green "$rule_description"
New-NetFirewallRule -DisplayName $rule_name -Description $rule_description -Direction Inbound -LocalPort $port_number -Protocol $protocol -Action Allow -Group $rule_group
}
An analogue clock in PowerShell
Afer messing with the trigonometry in the text sine screensaver above I realised that with a sine and cosine function I could draw a circle. And I could draw angled lines. And if I could draw a circle and angled lines then I could make an analoge clock. So I did.
The way this works that we define a two-dimensional array to act as an analogue (no pun intended) of our console window. We treat this array as an x-y space and using some maths we populate the necessary values into the array.
To display the clock we then iterate our way through the array and display the characters that the number correspond to. "Hmm", I can hear you think, "that's probably not the most efficient way of doing it". And you'd be absolutely right. Just before I completed this I found out about the [Console]::SetCursorPosition(x,y) function. Using that would make this more efficient - at the moment large sizes can take over a second to display which isn't great for a clock. Maybe for the future I'll rework the code, but for now this is how it stands.
Sizes less than 30 seem to work well, above gets a bit slow to display.
Usage: .\analogue-clock.ps1 size
# An analogue clock. Outputing to the console.
# PowerShell trig functions work on radians
# rad = deg * (pi/180)
# To get value between 0 and -1
# [math]::sin($deg * ([math]::pi/180))
# opp = hyp * sin x
# adj = hyp * cos x
# opp = adj * tan x
# Get the array size from the command line
param([Parameter(Mandatory=$True)]$ArraySize)
# Set the X length from the parameter
$xlength = $ArraySize
# Check to see if we've been passed an even value, make it odd if we have.
If ($xlength % 2 -eq 0) {
$xlength++
}
# X and Y must match
$ylength = $xlength
# Create the array
$arraydata = New-Object 'object[,]' $xlength, $ylength
# Clear the screen
Clear-Host
# START THE LOOP
$continue = $true
While ($continue -eq $true) {
# Fill the array with 0
For ($y = 0; $y -le ($ylength-1); $y++) {
For ($x = 0; $x -le ($xlength-1); $x++) {
$arraydata[$y, $x] = 0
}
}
# Set the centre point - remember to account for us being 0-based
$xcentre = (($xlength / 2) + 0.5) - 1
$ycentre = (($ylength / 2) + 0.5) - 1
# Set the length of the hands.
$hourradius = $xcentre / 4
$minuteradius = $hourradius * 2
$secondradius = ($hourradius * 2) +1
# Draw a face outline
$fradius = ($xlength / 3)
For ($fy = 0; $fy -lt 360; $fy++) {
$xval = [math]::sin($fy * ([math]::pi/180))
$yval = [math]::cos($fy * ([math]::pi/180))
$xpoint = $xcentre + ($fradius * $xval)
$ypoint = $ycentre + ($fradius * $yval)
$arraydata[$xpoint, $ypoint] = 4
}
# Draw minute points
$pointradius = ($xlength / 3) - 1.5
For ($fy = 0; $fy -lt 360; $fy = $fy + 6) {
$xval = [math]::sin($fy * ([math]::pi/180))
$yval = [math]::cos($fy * ([math]::pi/180))
$xpoint = $xcentre + ($pointradius * $xval)
$ypoint = $ycentre + ($pointradius * $yval)
$arraydata[$xpoint, $ypoint] = 6
}
# Draw hour points
$pointradius = ($xlength / 3) - 1
For ($fy = 0; $fy -lt 360; $fy = $fy + 30) {
$xval = [math]::sin($fy * ([math]::pi/180))
$yval = [math]::cos($fy * ([math]::pi/180))
$xpoint = $xcentre + ($pointradius * $xval)
$ypoint = $ycentre + ($pointradius * $yval)
$arraydata[$xpoint, $ypoint] = 5
}
# Get the time and set the variables
$now = Get-Date
$hours = $now.TimeOfDay.Hours
$minutes = $now.TimeOfDay.Minutes
$seconds = $now.TimeOfDay.Seconds
# Get the hour and minute angles
# Clock face only has 12 hours, so we don't use the 24-hour clock
If ($hours -gt 12) { $hours = $hours - 12 }
$hours_angle = (360 / 12) * $hours
$minutes_angle = (360 / 60) * $minutes
$seconds_angle = (360 / 60) * $seconds
# Move the Hours hand as the minutes go round - 1 minute moves it 0.5 degrees
# 720 minutes per 12 hours (1440 per day). 360 degrees / 720 minutes = 0.5
$hours_angle = $hours_angle + ($minutes * 0.5)
# Clock needs to be rotated -90 degress so 12 o'clock is vertical
$hours_angle = $hours_angle - 90
$minutes_angle = $minutes_angle - 90
$seconds_angle = $seconds_angle - 90
# Get the endpoint of the hands
$hours_x = $hourradius * ([math]::Sin($hours_angle * ([math]::pi/180)))
$hours_y = $hourradius * ([math]::Cos($hours_angle * ([math]::pi/180)))
$minutes_x = $minuteradius * ([math]::Sin($minutes_angle * ([math]::pi/180)))
$minutes_y = $minuteradius * ([math]::Cos($minutes_angle * ([math]::pi/180)))
$seconds_x = $secondradius * ([math]::Sin($seconds_angle * ([math]::pi/180)))
$seconds_y = $secondradius * ([math]::Cos($seconds_angle * ([math]::pi/180)))
# Round to integers
$hours_x = [math]::round($hours_x)
$hours_y = [math]::round($hours_y)
$minutes_x = [math]::round($minutes_x)
$minutes_y = [math]::round($minutes_y)
$seconds_x = [math]::round($seconds_x)
$seconds_y = [math]::round($seconds_y)
# Define our start points
$hours_start_x = $xcentre
$hours_start_y = $ycentre
$minutes_start_x = $xcentre
$minutes_start_y = $ycentre
$seconds_start_x = $xcentre
$seconds_start_y = $ycentre
# Define our end points
$hours_end_x = $xcentre + $hours_x
$hours_end_y = $ycentre + $hours_y
$minutes_end_x = $xcentre + $minutes_x
$minutes_end_y = $ycentre + $minutes_y
$seconds_end_x = $xcentre + $seconds_x
$seconds_end_y = $ycentre + $seconds_y
# Draw the seconds hands
$distance_seconds_x = $seconds_end_x - $seconds_start_x
$distance_seconds_y = $seconds_end_y - $seconds_start_y
$seconds_steps = [math]::Max( [math]::Abs($distance_seconds_x), [math]::abs($distance_seconds_y) )
$seconds_increment_x = $distance_seconds_x / $seconds_steps
$seconds_increment_y = $distance_seconds_y / $seconds_steps
For ($j = 0; $j -le $seconds_steps; $j++ ) {
$drawpoint_x = $seconds_start_x + ($j * $seconds_increment_x)
$drawpoint_y = $seconds_start_y + ($j * $seconds_increment_y)
$arraydata[$drawpoint_x, $drawpoint_y] = 7
}
# Draw the minutes hands
$distance_minutes_x = $minutes_end_x - $minutes_start_x
$distance_minutes_y = $minutes_end_y - $minutes_start_y
$minutes_steps = [math]::Max( [math]::Abs($distance_minutes_x), [math]::abs($distance_minutes_y) )
$minutes_increment_x = $distance_minutes_x / $minutes_steps
$minutes_increment_y = $distance_minutes_y / $minutes_steps
For ($j = 0; $j -le $minutes_steps; $j++ ) {
$drawpoint_x = $minutes_start_x + ($j * $minutes_increment_x)
$drawpoint_y = $minutes_start_y + ($j * $minutes_increment_y)
$arraydata[$drawpoint_x, $drawpoint_y] = 1
}
# Draw the hours hands
$distance_hours_x = $hours_end_x - $hours_start_x
$distance_hours_y = $hours_end_y - $hours_start_y
$hours_steps = [math]::Max( [math]::Abs($distance_hours_x), [math]::abs($distance_hours_y) )
$hours_increment_x = $distance_hours_x / $hours_steps
$hours_increment_y = $distance_hours_y / $hours_steps
For ($j = 0; $j -le $hours_steps; $j++ ) {
$drawpoint_x = $hours_start_x + ($j * $hours_increment_x)
$drawpoint_y = $hours_start_y + ($j * $hours_increment_y)
$arraydata[$drawpoint_x, $drawpoint_y] = 2
}
# Draw in the centrepoint
$arraydata[$ycentre, $xcentre] = 3
# Display the array
# This resets the cursor to point 0,0 - top left corner and avoids clearing the screen before redrawing.
# It makes for a nicer scroll
[Console]::SetCursorPosition(0,0)
$crop = ($xlength/12) # Quick hack to crop off the first and last lines as they're blank
For ($y = $crop; $y -le (($ylength-1)-$crop); $y++) {
For ($x = 0; $x -le ($xlength-1); $x++) {
$outputvalue = $arraydata[$y,$x]
# We'll use a switch to determine which character we're writing
Switch ($outputvalue) {
0 { Write-Host " " -NoNewLine }
1 { Write-Host -ForegroundColor White "MM" -NoNewLine } # Minutes
2 { Write-Host -ForegroundColor Green "HH" -NoNewLine } # Hours
3 { Write-Host -ForegroundColor DarkRed "OO" -NoNewLine} # Centrepoint
4 { Write-Host -ForegroundColor Gray "::" -NoNewLine } # Face edge
5 { Write-Host -ForegroundColor Red "++" -NoNewLine } # Hour marks
6 { Write-Host -ForegroundColor DarkRed "--" -NoNewLine } # Minute marks
7 { Write-Host -ForegroundColor Yellow "SS" -NoNewLine } # Seconds
}
}
Write-Host
}
Start-Sleep 1
}
A looping Lorenz Attractor simulation in PowerShell
After discovering the [Console]::SetCursorPosition(x,y) function, I realised that I could now throw characters anywhere on screen. No more building arrarys and iterating through them - I can just jump to a location and write my characters there.
For this one I asked Microsoft Copilot (the one that comes with Edge) to show me the BASIC version of a Lorenz Attractor algorithm. It was then pretty easy to convert that into PowerShell. The BASIC version is atop the code - I don't know why the variables are labelled different that the other versions of the algorithm you'll find online.
This versions has random variations on the main parameters so each run will be slightly different. Change the $iterations variable to change how many times the code iterates. With the limited resolution I've found 5,000 to be a nice value.
There is a weird quirk / bug which I've not looked into properly. For some window heights the output becomes vertically double-spaced. No idea why. The solution is to just increase or decrease the window height by couple of lines and that resolves it.
# BASIC version from Microsoft Copilot
# 10 REM Lorenz Attractor
# 20 DIM x(1000), y(1000), z(1000)
# 30 s = 10: r = 28: b = 8 / 3
# 40 x(0) = 0.1: y(0) = 0: z(0) = 0
# 50 dt = 0.01
# 60 FOR i = 1 TO 1000
# 70 dx = s * (y(i - 1) - x(i - 1))
# 80 dy = x(i - 1) * (r - z(i - 1)) - y(i - 1)
# 90 dz = x(i - 1) * y(i - 1) - b * z(i - 1)
# 100 x(i) = x(i - 1) + dx * dt
# 110 y(i) = y(i - 1) + dy * dt
# 120 z(i) = z(i - 1) + dz * dt
# 130 NEXT i
# 140 FOR i = 1 TO 1000
# 150 PLOT x(i), y(i)
# 160 NEXT i
#
# [Console]::SetCursorPosition(x,y) - how to set a the cursor position. 0,0 is top left.
# Set the variables
$iterations = 5000
$x = New-Object 'object[]' $iterations
$y = New-Object 'object[]' $iterations
$z = New-Object 'object[]' $iterations
$console_width = $Host.UI.RawUI.WindowSize.Width - 2
$console_height = $Host.UI.RawUI.WindowSize.Height - 2
$xcentre = $console_width / 3
$ycentre = $console_height / 2
$xscale = 1.5
$yscale = 1
$continue = $true
While ($continue -eq $true) {
# Clear the screen
Clear-Host
# Set our Lorenz variables
$s = Get-Random -Minimum 5 -Maximum 15 # +/- 5
$r = Get-Random -Minimum 18 -Maximum 38 # +/- 10
$b = [math]::pi + ((Get-Random -Minimum -20 -Maximum 20) / 10) # +/- 2 to two decimal places
$x[0] = 0.1
$y[0] = 0
$z[0] = 0
$dt = 0.01
# Write our values to the screen
Write-Host "$s, $r, $b"
# Start iterating and draw
For ( $i = 1; $i -lt $iterations; $i++ ) {
$dx = $s * ($y[$i - 1] - $x[$i - 1])
$dy = $x[$i - 1] * ($r - $z[$i - 1]) - $y[$i - 1]
$dz = $x[$i - 1] * $y[$i - 1] - $b * $z[$i - 1]
$x[$i] = $x[$i - 1] + $dx * $dt
$y[$i] = $y[$i - 1] + $dy * $dt
$z[$i] = $z[$i - 1] + $dz * $dt
# Draw
$plotx = ($xcentre + [math]::Round($x[$i])) * $xscale
$ploty = ($ycentre + [math]::Round($y[$i])) * $yscale
# Keep us within the window
If ($plotx -gt $console_width) { $plotx = $console_width }
If ($plotx -lt 0) { $plotx = 0 }
If ($ploty -gt $console_height) { $ploty = $console_height }
If ($ploty -lt 0) { $ploty = 0 }
# Move the cursor and draw
[Console]::SetCursorPosition($plotx, $ploty)
If ($i % 2 -eq 1) {
Write-Host -ForegroundColor Green "O" -NoNewLine
} Else {
Write-Host -ForegroundColor Yellow "+" -NoNewLine
}
}
}
List all the text-to-speech voice using PowerShell
This will list all the text-to-speech voices that are installed and available. This list will probably differ depending on which operating system you're using.
Usage: .\Speech-List-Voices.ps1
# List the voices available for text to speech
# Add the assembly to do the speech
Add-Type -AssemblyName System.speech
# Create the speech object
$talker = New-Object System.Speech.Synthesis.SpeechSynthesizer
# List the voices
$talker.GetInstalledVoices() | Select-Object -Property voiceinfo -ExpandProperty voiceinfo
# Dispose of the speech object
$talker.Dispose()
Text-to-speech-to-wave-file using PowerShell
As we saw earlier we can do text-to-speech through PowersShell. While that's handy, sometimes it'd be even handier to have that output as a .wav file. In our script we choose which voice we'll be using. I'm using the Microsoft Zira Desktop voice, but you might want something different - or it might not be installed on your OS. In that case we can use the script above to list the available voices.
One caveat I found with this is that it won't write the wave file to a OneDrive folder or to a mapped network drive (including local ones you've done through the net use command. I don't know why but it'll only write to actual, physical disks.
Usage: .\Speech-to-Wav.ps1 -filename .\path-to-file.wav -speaktext "you are hearing me talk"
# Do speech to .wav file
# Get our inputs - the text to speak and the filename
param( [string]$speaktext,
[string]$filename )
Write-Host "Speaking: " -NoNewLine
Write-Host -ForegroundColor Yellow "$speaktext"
Write-Host "To file: " -NoNewLine
Write-Host -ForegroundColor Yellow "$filename"
# Add the assembly to do the speech
Add-Type -AssemblyName System.speech
# Create the speech object
$talker = New-Object System.Speech.Synthesis.SpeechSynthesizer
# Set the voice
$talker.SelectVoice("Microsoft Zira Desktop")
# Set the output to a file
$talker.SetOutputToWaveFile($filename)
# Speak
$talker.Speak($speaktext)
# Dispose of the speech object
$talker.Dispose()
Fake an old teletype using PowerShell
For those of you of a certain age you might remember actual teletype machines. For those of you a bit younger you might remember the effect from when the football results were displayed on Grandstand on a Saturday afternoon.
Essentially what this script does is create a function (Write-TeleType) that displays each character of string one at a time with a delay between the characters. The delay is random within minimum and maximum values, given in milliseconds. In the usage below, these values give a good approximation a half-decent typist. Adjust to taste, but values that are close together won't really be noticiable to the viewer. We're using Write-Host as it's got the -NoNewLine parameter which something like Write-Output lacks.
It's written as a function so you can include it easily into your own code. Just remember that the function doesn't do bounds checking on your delay values, so you'll need to ensure you're passing -MinDelay with a value less than -MaxDelay.
Usage: .\TeleType.ps1 -Message "this is the `ntext I want to display" -MinDelay 10 -MaxDelay 200
# Output text like an old teletype machine. Think the football results on Grandstand in the 80s.
# Parameters to the script
Param ( [Parameter(Mandatory=$True)]$Message,
[Parameter(Mandatory=$True)]$MinDelay,
[Parameter(Mandatory=$True)]$MaxDelay)
# The function
Function Write-TeleType {
Param ( [Parameter(Mandatory=$True)]$Message,
[Parameter(Mandatory=$True)]$MinDelay,
[Parameter(Mandatory=$True)]$MaxDelay)
For ( $i = 0; $i -lt $Message.Length; $i++ ) {
$DelayTime = Get-Random -Minimum $MinDelay -Maximum $MaxDelay
Start-Sleep -Milliseconds $DelayTime
Write-Host -NoNewLine "$($Message[$i])"
}
}
# Code to call the function and to check that that MaxDelay is larger than MinDelay
If ( $MinDelay -ge $MaxDelay ) {
Write-Host "Maximum delay time must be greater then the minimum time"
Exit 1
}
Write-TeleType -Message $Message -MinDelay $MinDelay -MaxDelay $MaxDelay
© 2026 D.Shaw. All work is free for you to use - just note that you do so at your own risk. It shouldn't do anything bad, but if it does then that's on you.
Apologies for any speeling mistookes. darren@anexium.com