$body+="This is an auto-response to the email that you have recently sent to contoso.com user."

$body+="The email has been forwarded to otherdomain.com user mailbox and the recipient has received it successfully."

$body+="Please be informed that, due to the account migration to a unified somedomain.com, this user no longer has a @contoso.com mailbox. For this reason it is advisable that you use otherdomain.com email address for your future emails to this user."

$body+=""

$body+="This email was auto-generated, so please do not reply to it. If you have any questions, please contact Anyone, Company IT Director."

… that maybe came from the body of a file, was returned by some other part of a script, etc., and you just want the portions that are actually between the quotes, the quickest and easiest way to get it is through a regular expression match.

That’s right, forget splitting or trimming or doing other weird string manipulation stuff. Just use the [regex]::matches() feature of PowerShell to get your values.

PowerShell

1

[regex]::matches($s,'(?<=\").+?(?=\")').value

Matches takes two parameters. 1. The value to look for matches in, in this case the here-string in my $s variable, and 2. The regular expression to be used for matching. Since Matchesreturns a few items, we are making sure to just select the value for each match.

So what is that regex doing? Let’s break it down into it’s parts.

(?<=\”) this part is a look behind as specified by the ?<= part. In this case, whatever we are matching will come right after a quote. Doing the look behind prevents the quotation mark itself from actually being part of the matched value. Notice I have to escape the quotation mark character.

.+? this part basically matches as many characters as it takes to get to whatever the next part of the regex is. Look into regex lazy mode vs greedy mode.

(?=\”) this part is a look ahead as specified by the ?= part. We’re looking ahead for a quotation mark because whatever comes after our match is done will be a quotation mark.

So basically what we’ve got is “whatever comes after a quotation mark, and as much of that as you need until you get to another quotation mark”. Easy, right? Don’t you love regex?