Hi, Damian Garbus here and today I want to tell you my personal opinion. When I write this post is Wednesday. Two days ago on Monday one of my clients have requested issue in one of the Powershell automation, which I wrote 2 years ago.  This example shows that in a few years I learned a new way of writing scripts and  I’m still learning now. Check why I love use regex in Powershell scripts.

History details

For this client, I wrote more than 20 Powershell automation to manage permissions in IT infrastructure.  During troubleshooting, I have found the line in Powershell script which generates the problem. It’s nothing else than string modification. What are the string and others Powershell variable types you can read in this post. Ok, but what was wrong in the script. I’m getting the size of Exchange mailbox database and use substring in order to get numbers of GB to convert to integer type. 

$size = (Get-MailboxDatabase $DatabaseName2 -Status).DatabaseSize
if ($size -like "*GB*") {[int64]$temp = ($size.Substring(0,$size.indexof(".")));$temp; $size = ($temp * 1073741824)/1GB ;}
regex in Powershell

The problem occurred when the database size did not have a value after the dot.

regex in Powershell

Regex in Powershell for help

Now when I see my Powershell code written a few years ago like that I want to ask “who wrote this?” 🙂 I know that it was my mistake to use substring. Now in a case like that, I’m using regex in Powershell scripts.

$size = (Get-MailboxDatabase $DatabaseName2 -Status).DatabaseSize
$size = ($size -replace "\d+(.|\s)\d+\s(GB|MB|KB) [\(]| bytes[\)]","") -replace ",",""
$size = [math]::round($size/1GB, 0)
regex in Powershell


Human always learning new thing or way to do something. I love to learn and since a few months, I love use regex in Powershell scripts. To build regex I use Regexr.com. Maybe you know the better way than regex. Please share with me and other readers.

Get Access to Poshland Resources for FREE!!!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailerLite ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.