创建文件的 cmdlet 返回一个文本块,其中包含文件的名称。该文件的格式为字符串[数字].ps1,但数字是随机的,所以我想提取该数字并将其存储在变量中。
供参考的文本块:
+ ~~~~~\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\\script35.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\\script35.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\\script35.ps1:21 char:3\n+ using Microsoft.Build.Utilities;\n\
+ ~~~~~\nA 'using' statement must appear before any other statements in\
我想$result -match '\d\d+(?=\.\w+)'
可以,但它只返回找到该号码的行,而不仅仅是号码。
With a 收藏(而不是单个值)作为 LHS,-match操作员:
这就是为什么你的输出包含匹配行作为一个整体.
要仅返回匹配的部分,您可以使用switch陈述与-Regex
循环遍历行数组的选项,在这种情况下$Matches
is为每个输入行填充:
# 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
option
(switch -Regex -File $filePath { ... }
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)