How to get a specific string from a text file in PowerShell and assign it as a variable

302 views Asked by At

I am currently running the PowerShell script below to capture errors:

# Declare Variables
$Information = Import-Csv "c:\scripts\GUIDIssue\UPNList.csv"

# Connect to O365 Tenant
Connect-MsolService

foreach ($Info in $Information) {
(Get-MsolUser -UserPrincipalName $Info.UPN).errors.errordetail.objecterrors.errorrecord| fl > "C:\scripts\GUIDIssue\error.txt"

}

The output is the following: ErrorCode : ExA77C31 ErrorParameters : ErrorParameters ErrorDescription : Failed to enable the new cloud archive 00000000-0000-0000-0000-000000000000 of mailbox b306e73d-4fdc-43e5-af00-518b13e962ab because a different archive 852910fe-67ed-4b7b-9e1a-ef70289d4c36 exists. To enable the new archive, first disable the archive on-premises. After the next Dirsync sync cycle, enable the archive on-premises again.

In the "ErrorDescription:" I need to get 852910fe-67ed-4b7b-9e1a-ef70289d4c36 and assign it as a variable. How can I do that?

2

There are 2 answers

0
jazzdelightsme On

How about something like:

echo "ErrorCode : ExA77C31 ErrorParameters : ErrorParameters ErrorDescription : Failed to enable the new cloud archive 00000000-0000-0000-0000-000000000000 of mailbox b306e73d-4fdc-43e5-af00-518b13e962ab because a different archive 852910fe-67ed-4b7b-9e1a-ef70289d4c36 exists. To enable the new archive, first disable the archive on-premises. After the next Dirsync sync cycle, enable the archive on-premises again." >test.txt

gc test.txt | `
    where { $_ -match "because a different archive (?<id>.*) exists" } | `
    %{ $matches.id }
0
Cory Lundgren On

The below works for me.

# Split the error message on spaces so we can compare each word to our regex
$SplitErrorMessage = ((Get-Content -Path 'C:\scripts\GUIDIssue\error.txt') -split "\s")
# Assign the output from within our loop to the $ErrorMatches variable
$ErrorMatches = foreach ($Word in $SplitErrormessage) {

    if ($Word -match '\w{8}-\w{4}-\w{4}-\w{4}-\w{12}') {
        # Write-Output inside the loop adds the output to our loop variable $ErrorMatches
        Write-Output $Word
    }
}
#Return the last item in the $ErrorMatches variable as this should be the GUID you are targeting
$ErrorMatches[-1]

'852910fe-67ed-4b7b-9e1a-ef70289d4c36'

This uses a simple regex match and a cool feature of PowerShell. Assigning a loop to a variable will save anything written to stdout into the loop variable.

Then we return the last index in that array since the value you want is always the last to match our regex. Hopefully this meets your needs.