С набором (в отличие от одного значения) в качестве LHS оператор -match
:
Вот почему ваш вывод содержал совпадающие строки в целом .
Чтобы вернуть только совпадающие части, вы можете использовать оператор switch
с опцией -Regex
, чтобы l oop по вашему массиву строк, в этом случае $Matches
заполнено для каждой строки ввода:
# Array of sample lines.
# For illustrative purposes I've tweaked the `script<number>.ps1`
# tokens to have successive numbers.
$lines = @'
+ ~~~~~\nA 'using' statement must appear before any other statements in\
\ a script.\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script35.ps1:20 char:8\n+ using Microsoft.Build.Framework;\n\
+ ~\nMissing using directive\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script36.ps1:20 char:3\n+ using Microsoft.Build.Framework;\n\
+ ~~~~~\nA 'using' statement must appear before any other statements in\
\ a script.\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script37.ps1:21 char:8\n+ using Microsoft.Build.Utilities;\n\
+ ~\nMissing using directive\nAt C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\\
1.1.3\\Downloads\\script38.ps1:21 char:3\n+ using Microsoft.Build.Utilities;\n\
+ ~~~~~\nA 'using' statement must appear before any other statements in\
'@ -split '\r?\n'
# Perform the matching, line by line,
# and output each line's matching part,
# resulting in an array of strings.
# Prepend
# $result =
# to store the array in a variable.
switch -Regex ($lines) {
'\d+(?=\.\w+)' { $Matches[0] } # to extract only the *1st* match,
# append `; break` inside the { ... }
}
Выше приведены значения:
35
36
37
38
Обратите внимание, что switch
также поддерживает чтение строк непосредственно из файла, используя опцию -File
(switch -Regex -File $filePath { ... }
).