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 / Fix-ExcelWorkbookXml.ps1
Created April 13, 2022 11:15
Fix Excel's Name Manager (workbook contains too many bad references in named ranges) issue
# Thanks to [Reddit](https://www.reddit.com/r/excel/comments/70r89w/need_to_delete_thousands_of_errored_named_ranges/i4huccg)
# for the tip on resolving the name manager issue
# once you've extracted your XLSX file as a zip, find the `workbook.xml` file (should be under the `xl` subfolder)
$wbPath = 'C:\Temp\MyExtractedXlsx\xl\workbook.xml'
# open this XML file / parse it as XML
$wb = [xml](Get-Content -Path $wbPath -encoding UTF8 -Raw)
# find all `definedName` elements which contain the string `#REF!`.
@JohnLBevan
JohnLBevan / Convert-PemToX509Cert.ps1
Last active April 7, 2022 10:12
Simple script to convert PEM to X509 Certs; useful if you want to check which certs a PEM relates to, or check the order of the certs in the chain.
function Convert-PemToX509Cert {
Param (
[Parameter(Mandatory)]
[string]$Path
,
[Parameter()]
[System.Text.Encoding]$Encoding = [System.Text.Encoding]::UTF8
)
$options = [System.Text.RegularExpressions.RegexOptions]::CultureInvariant -bor [System.Text.RegularExpressions.RegexOptions]::Singleline
$regex = [System.Text.RegularExpressions.RegEx]::new('\-{5}BEGIN CERTIFICATE\-{5}(?<CERT>.*?)\-{5}END CERTIFICATE\-{5}', $options)
@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