1

I wish to select the thirdline of text from a sting in powershell.

The string I have is coming from the body of an email:

  $olFolderInbox = 6
  $outlook = new-object -com outlook.application;
  $ns = $outlook.GetNameSpace("MAPI");
  $inbox = $ns.GetDefaultFolder($olFolderInbox)

   foreach ($email in $inbox.items){

         if($email.Subject -eq "PASSED") {

         $Body = $email.Body 

         write-host  $emailSentOn
         write-host  $email.Body 

        } 
 }

The $Body string is formatted like so:

<BLANK LINE>
Queue Cleared!
Server Name
Username

I wish to exact the Server name from the 4 line text string.

Thanks

4 Answers 4

4

Assuming the format is consistent

if ($Body[2] -match '(?m:^Server (?<server>\w+))' ) {
    # do something with $matches.server
}
Sign up to request clarification or add additional context in comments.

Comments

1

Using a multi-line regex:

$body = @"

Queue Cleared!
Server Name
Username
"@

#$regex = '(?ms).+?$(.+)?$.+?$.+' #Capture second line.
$regex = '(?ms).+?$.+?$(.+)?$.+' #Capture third line.
$body -replace $regex,'$1'

Server Name

Each .+?$ represents one line of the body. The third line is captured and used for the -replace operation.

The title doesn't quite match the descripion in the post (second line vs third line) so I've included both.

Comments

0

You can split a string using the -split operator:

$foo -split "`n"

You'll get an array back. You can then get an element from that array using indexing:

($foo -split "`r?`n")[2]

1 Comment

Brilliant! Tank you for the quick response! :)
0

This will send only the 3rd item of the array (server name) to the Body. The count starts at zero, so that's why [2] = 3rd.

 $Body[2] = $email.Body 

Body result

Server Name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.