0

我想使用 powershell 从格式每次都相同的字符串中获取服务器名称。我使用 HP Data Protector 中的命令创建了一个文本文件。字符串的示例是...

   host="ts-sve-serverT.ca.mycompany.com"  
   host="ts-sve-serverG.ca.mycompany.com"  
   host="ts-sve-serverA.ca.mycompany.com"  

开头有3个空格。我有兴趣在第一组引号之后和第一个句点之前提取服务器名称。服务器名称可能包含 0 到 2 个破折号。

4

2 回答 2

1
$serverNames = gc 'c:\logfile.txt' |?{ $_ -match '"([^\.]*)\.' } |%{ $matches[1] }
于 2013-08-06T19:36:48.650 回答
0

按照latkin的建议,使用-match运算符或cmdlet:Select-String

$names = gc 'C:\path\to\your.log' | Select-String '"(.*?)\.' | % {
  $_.Matches.Groups[1].Value
}

以上需要 PowerShell v3。在早期版本中,您必须像这样扩展匹配项:

$names = gc 'C:\path\to\your.log' | Select-String '"(.*?)\.' `
  | select -Expand Matches `
  | select -Expand Groups `
  | select -Last 1 Value
于 2013-08-06T19:47:57.123 回答