Trinitrotoluene
Trinitrotoluene

Reputation: 1458

Powershell extract text from string with unknown length

I don't think I can use a standard cmdlet for this. I have the following string Backup Job INDETERMINABLE STRING HERE completed successfully

I need to extract the INDETERMINABLE STRING HERE which could be any length and any number of words. The text to the left will always be Backup Job and the text to the right will either be completed successfully OR failed with errors.

How would I go about this?

Upvotes: 1

Views: 1187

Answers (1)

David Martin
David Martin

Reputation: 12248

Here you go, this makes use of the $matches automatic variable.

$regEx = "Backup Job (.*)(completed successfully|failed with errors)"
$good  = "Backup Job INDETERMINABLE STRING HERE completed successfully"
$bad   = "Backup Job INDETERMINABLE STRING HERE failed with errors"

if ($good -match $regEx)
{
    $matches[1]
}
if ($bad -match $regEx)
{
    $matches[1]
}

Upvotes: 2

Related Questions