Skip to content

Instantly share code, notes, and snippets.

View JohnLBevan's full-sized avatar
🏠
Working from home

John Bevan JohnLBevan

🏠
Working from home
View GitHub Profile
@JohnLBevan
JohnLBevan / HandlingExceptionsInLoops.ps1
Created March 31, 2022 12:40
A colleague recently asked about where to handle exceptions in PowerShell. My response was; it depends / handle them wherever you can do something about them / consider what else should happen even if one part fails, vs what shouldn't happen. Always ensure that issues get handled or bubbled up to be logged/output somewhere, rather than catching …
<#
This example shows how you can collect information on exceptions which occur in a loop,
whilst still processing other items in that loop, and bubbling up the exceptions which
were thrown during the loop
#>
# Dummy methods for illustration
function Do-Something{'Did Something'}
function Do-SomethingToTheThing([int]$thing) {
if ($thing % 7 -eq 0) {
@JohnLBevan
JohnLBevan / FreeDockerDiskSpace.ps1
Last active March 18, 2025 14:53
Free up disk space caused by Docker files
# :: Prune dangling (untagged) images
docker image prune
# :: Stop Docker Desktop
Stop-Service 'com.docker.service'
# :: Stop the WSL service to ensure that doesn't lock the file
wsl --shutdown
@JohnLBevan
JohnLBevan / Get-TlsCertificate.ps1
Created September 2, 2021 10:55
Certificate discovery script; basically a port scanner which checks for an ssl connection and pulls back the certificate info where available
# See also https://gist.github.com/JohnLBevan/a6c819ba5d825f29d465fb0433b54082 -- useful for fetching a range of IPs to be scanned
Function Get-TlsCertificate {
# Note: This uses PS7's parallel foreach feature; so requires PS7. If we wanted to write a version compatible with older versions we could use workflows (e.g. https://codereview.stackexchange.com/questions/97726/powershell-to-quickly-ping-a-number-of-machines) or add custom job/runspace logic (though that's much less tidy)
[CmdletBinding(DefaultParameterSetName = 'ByComputerAndPort')]
Param (
[Parameter(ParameterSetName = 'ByComputerAndPort', Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$ComputerName
,
[Parameter(ParameterSetName = 'ByComputerAndPort', ValueFromPipelineByPropertyName)]
@JohnLBevan
JohnLBevan / Covert-CidrToIpV4List.ps1
Last active March 8, 2024 15:34
Converts a CIDR notation IP Range to an array of those IPs
<#
.SYNOPSIS
Converts a CIDR notation IP Range to an array of those IPs, or an object containing the first and last values in the range.
All representations of IPs are returned as type: [System.Net.IPAddress]
.DESCRIPTION
Converts a CIDR notation IP Range to an array of those IPs, or an object containing the first and last values in the range.
All representations of IPs are returned as type: [System.Net.IPAddress]
.PARAMETER IpRangeCidr
@JohnLBevan
JohnLBevan / RegexReplace.bas
Last active July 26, 2021 14:52
VBA worksheet function implementation of a regex replace
' Simple Example Usage: `=RegexReplace(S181,"(\d+)\.(\d+)\.(\d+)", "$3-$2-$1 00:00:00")` - dd.mm.yyyy formatted date replaced with yyyy-MM-dd HH:mm:ss
' Ensure you add a reference to `Microsoft VBScript Regular Expressions 5.5` (or later)
' Thanks to AutomateThis for their answer pointing me to this library: https://stackoverflow.com/a/22542835/361842
Option Explicit
Option Base 0
Public Function RegexReplace(sourceString As String, matchPattern As String, replaceVar As String, Optional globalRegex As Boolean = True, Optional multiLine As Boolean = True, Optional ignoreCase As Boolean = True) As String
' Could improve by adding validation (e.g. is the matchPattern blank), but for now just doing a quick and dirty
Dim regEx As New RegExp
@JohnLBevan
JohnLBevan / StorageAccountBlobTypes.md
Last active July 21, 2021 11:26
Various Azure Notes

Azure Storage Account Blob Types

  • Block Blobs: Files typically read / written in their entirety.
  • Page Blobs: Files which may be partially read/written out of sequence; e.g. VHDs, MDFs, etc.
  • Append Blobs: Files which are written to sequentially over time; e.g. log files.
<# This script fixed the below issue
Log Name: Application
Source: Microsoft-Windows-CAPI2
Event ID: 513
Task Category: None
Level: Error
Keywords: Classic
User: N/A
Description:
Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
@JohnLBevan
JohnLBevan / Get-AsgMembers.ps1
Created July 7, 2021 13:31
Query to list all of an application security group (ASG)'s members (VMs). Thanks to Clive for the graph query. https://feedback.azure.com/forums/217313-networking/suggestions/35655277-show-membership-of-application-security-groups
# https://docs.microsoft.com/en-us/azure/governance/resource-graph/first-query-powershell#run-your-first-resource-graph-query
# Install-Module -Name Az.ResourceGraph # - installs the module; no need to run if you've previously installed this.
# Login-AzAccount # brings up a web browser to log you in to Azure (interactive) so PS can run under your credentials
# Set-AzContext -SubscriptionId '0000000-1111-etc' # use this to target the subscription your resources live in; amending the subscrcription id as needed
(Search-AzGraph -Query @'
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| project name, nics = properties.networkProfile.networkInterfaces
| mvexpand nics
@JohnLBevan
JohnLBevan / Remove-AzTagTrailingSpace.ps1
Created July 2, 2021 12:03
Remove trailing spaces from Azure tag names
#
# Rough and ready script to clean up trailing spaces from tag names
# Loops through all resources and resource groups under all subscriptions to which you have access.
# If a resource isn't already tagged with the clean (same name with no trailing space) then the clean tag name is given the diry tag's value, and the dirty tag is removed.
# If a resource has both clean and dirty tags, this shows a warning (even if the values are the same... I was lazy / didn't add a check for that) and leaves to the caller to fix manually.
# If a resource doesn't have any dirty tags, it's not affected.
#
Clear-Host
Login-AzAccount # (interactive / opens web browser)
@JohnLBevan
JohnLBevan / Test-SqlConnection.ps1
Created May 18, 2021 16:17
A script for quickly testing a SQL Server Db Connection; useful when debugging potential connectivity issues (beyond just Test-NetConnection)
Function Test-SqlConnection {
[CmdletBinding(DefaultParameterSetName = 'ByConnectionString')]
Param (
[Parameter(ParameterSetName = 'ByConnectionString', Mandatory)]
[string]$ConnectionString
,
[Parameter(ParameterSetName = 'AuthSqlUser', Mandatory)]
[Parameter(ParameterSetName = 'AuthAdCredentials', Mandatory)]
[Alias('DbInstance')]
[string]$ComputerName