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.
$product_code = 'ABCD1234-11-12-2013'
$date_created = [DateTime]$product_code.SubString($product_code.Length-10)
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!
Latest posts by Adam Bertram (see all)
- Review: Ansible shows the beef - January 19, 2017
- PowerShell integration tests with Pester - January 19, 2017
- Update multiple SQL Server systems with PowerShell - January 18, 2017