The Powershell Substring: Finding a String Inside a String

A common scenario in an admin’s world is to figure out a way to find a certain snippet of text inside a string; called the substring.  Powershell makes finding a substring extremely easy.  Let’s go over an example.

First, let’s say we’ve got a product code that has the following format:  XXXXVVVV-MM-DD-YYYY.  All products have this code format and never deviate from it.  Now, the wonky inventory management software that generated this code didn’t include a date created field in the database.  However, the software always put this date as MM-DD-YYYY in the product code itself so we can infer this from the product code.  We need to get this date for our products to create some super-fancy yet extremely unnecessary report to management to show when each product was inserted into the database.  Here’s a good way to get this done.

In this example, we’re using the Powershell SubString method for the inherent String object and passing the number for the first character we want to find as the parameter. Since we’re not specifying the stopping character it assumes we want all characters to the end of the string. To find the number in the first place, we’re first getting the length of the entire product code and simply subtracting 10 from that. In this example, this means we want to start at the 10th character from the right of the string and everything to the right of that.

The [DateTime] doesn’t necessarily go with the substring topic of the post but I thought it’d fit in nicely with the specific example.  After we get our string of 11-12-2013 we then type cast it to a [DateTime] object which converts what was once a dumb string into a nice object.  From here, we can do all the fancy date arithmetic management wants us to do on it and generate that fancy bar chart report!

Adam Bertram

Adam Bertram

Chief Automator at Adam the Automator, LLC
Adam Bertram is an independent consultant, technical writer, trainer and presenter. Adam specializes in consulting and evangelizing all things IT automation mainly focused around Windows PowerShell. Adam is a Microsoft Windows PowerShell MVP, 2015 PowerShell hero and has numerous Microsoft IT pro certifications. He authors IT pro course content for Pluralsight, is a regular contributor to numerous print and online publications and presents at various user groups and conferences.You can find Adam here on the blog or on Twitter at @adbertram.
Adam Bertram

Latest posts by Adam Bertram (see all)


  • Hello and thanks for your light


    I try to retrieve in a TXT or XML file all the names (…..) that
    Are between and


    I try to use a command but I am not successful
    Select-String -Path “C: \ temp \ 14.txt” -Pattern ” ”
    Get-content file.txt | Where {$ _ -match ” “} | Foreach
    {$ _. SubString ($ _. IndexOf (” “) + 1)}

    Thank you for your help

Leave a Reply