#PowerShell script to format Serial Number with a certain length and exclusion of special characters

Here is a little #PowerShell snippet that queries the BIOS WMI Class for the Serial Number. Formats it with certain length of your choice and removes special characters, spaces and hyphens.

The Sample snippet is using the Length Parameter Variable $SNLength as 6 (Please change this as per your requirement). My use case was to only fetch the last 6 characters of the Serial Number from the right.

SerialNumberPS

 

SerialNumberPS2

SerialNumberPS3

The snippet uses the Regex expression as below:

-replace ‘[^a-zA-Z0-9]’, ”

This replaces everything that is non Alpha Numeric

  • Note: ^ is to Inverse the allowed characters selection that are followed by the symbol itself. Please refer to a great Regex Blog from Francois-Xavier Cat
$SNLength = "6" # Fetches the Last 6 Alpha Numberic characters of the Serial Number from the Right # Excluding Special Characters, Spaces and Hyphens

$SN = (Get-WmiObject -Class Win32_Bios).SerialNumber

$SN1 = $SN.ToUpper() -replace '[^a-zA-Z0-9]', ''

$SN1.Substring($SN1.Length - $SNLength)

Cheers 🙂

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: