从 PowerShell 中的字符串中提取值(使用正则表达式)

Extracting values from string in PowerShell (with Regex)

我有以下文件:

<Mapping ServerPath="$/Test/Dev/test/sunday/project" LocalPath="$(SourceDir)\Test" Version="Latest" WorkspaceMappingType="Map">
<Mapping ServerPath="$/Test/Dev/test/aaa/project2" LocalPath="$(SourceDir)\Test\project" Version="Latest" WorkspaceMappingType="Map">
<Mapping ServerPath="$/Test/Dev/test/sunday/project/test" LocalPath="$(SourceDir)\Test-machine" Version="Latest" WorkspaceMappingType="Map">
<Mapping ServerPath="$/Test/Dev/test/besaide/monday" LocalPath="$(SourceDir)\Monday" Version="Latest" WorkspaceMappingType="Map">

我需要从每一行中提取这两个值:

ServerPath="$/Path"

LocalPath="$(SourceDir)\Path"

我使用此方法将文件内容保存在 PS 变量中:

$file = Get-Content C:\test\file.txt

现在如何使用 Regex 从每一行中检索 2 个值? (或者如果可能的话不使用正则表达式)。

要提取这两个路径:

$input_path = 'C:\inputpath.txt'
$output_file = 'C:\outputpath.txt'
$regex = 'ServerPath=[^\s]+|LocalPath=[^\s]+'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

除了缺少结束标记外,您显示的输入看起来像 XML 变体。如果是这样,我建议使用 XML 工具而不是正则表达式:

Select-Xml -Path path\to\file.xml -XPath '//Mapping[@ServerPath and @LocalPath]'|%{
    # grab the values of these
    $_.Node.ServerPath
    $_.Node.LocalPath
}