Как получить конкретную строку из текстового файла в PowerShell и назначить ее в качестве переменной - PullRequest
0 голосов
/ 27 сентября 2018

В настоящее время я запускаю приведенный ниже сценарий PowerShell для захвата ошибок:

# 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"

}

Вывод следующий: ErrorCode: ExA77C31 ErrorParameters: ErrorParameters ErrorDescription: Не удалось включить новый облачный архив 00000000-0000-0000-0000-000000000000 почтового ящика b306e73d-4fdc-43e5-af00-518b13e962ab, так как существует другой архив 852910fe-67ed-4b7b-9e1a-ef70289d4c36.Чтобы включить новый архив, сначала отключите архив локально.После следующего цикла синхронизации Dirsync снова включите локальный архив.

В «ErrorDescription:» мне нужно получить 852910fe-67ed-4b7b-9e1a-ef70289d4c36 и назначить его в качестве переменной.Как я могу это сделать?

Ответы [ 2 ]

0 голосов
/ 27 сентября 2018

Ниже работает для меня.

# 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'

Это использует простое совпадение регулярных выражений и классную функцию PowerShell.Присвоение цикла переменной сохранит все, что записано в stdout, в переменную цикла.

Затем мы возвращаем последний индекс в этом массиве, поскольку требуемое значение всегда является последним, соответствующим нашему регулярному выражению.Надеюсь, это отвечает вашим потребностям.

0 голосов
/ 27 сентября 2018

Как насчет чего-то вроде:

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 }
...