powershell-7

Extract substring from a result in Select


I'm attempting to get a substring in a Select filter from a command result. Much like this

Connect-ExchangeOnline
Get-DistributionGroup -ResultSize Unlimited
Get-DistributionGroupMember -Identity "Groupname" -ResultSize Unlimited |
Select FirstName, LastName, LastName.Substring(0,2)

An error is reported at the .Substring apart.

What would a working way to extract a substring from a result with Select


Solution

  • The most straightforward approach is to create a custom property using a hashtable in your Select-Object filter:

    Select FirstName, LastName, @{ Label="ShortName";Expression={$_.LastName.Substring(0,2)} }