我想从PowerShell脚本解析我的主机文件。
我观察到了不同的行为:
$hostsFile = "$env:windir\System32\drivers\etc\hosts"
$hostsRegex = '^\s*(?<Address>[0-9\.\:]+)\s+(?<Host>[\w\.\-]+)\s*$'
$entries = Get-Content $hostsFile -Encoding Ascii
-match
:$entries -match $hostsRegex
它的行为符合预期,并输出我的所有条目(并且仅输出我的条目)。
Regex.Matches
方法的[Regex]::Matches($entries, $hostsRegex)
什么也不返回(也尝试使用
Multiline
,SingleLine
等选项... 我的目标是获取自定义PS对象,以进行进一步处理。其实我希望这能工作:
function Get-HostsEntries{
$hostsFile = "$env:windir\System32\drivers\etc\hosts"
$hostsRegex = '^\s*(?<Address>[0-9\.\:]+)\s+(?<Host>[\w\.\-]+)\s*$'
$entries = Get-Content $hostsFile -Encoding Ascii
[Regex]::Matches($entries, $hostsRegex ) | %{
New-Object PSObject -Property @{
Address = $_.Groups["Address"].Value
Host = $_.Groups["Host"].Value
}
}
}
Get-HostsEntries
但是什么也没返回。
所以我的问题是:
最佳答案
使用-Raw
将文件读取为单个字符串。否则,Get-Content
会为您提供[Regex]::Matches
无法处理的字符串列表。
$hostsFile = "$env:windir\System32\drivers\etc\hosts"
$entries = Get-Content $hostsFile -Encoding Ascii -Raw
$hostsRegex = [Regex]'(?m)^\s*(?<Address>[0-9.:]+)\s+(?<Host>[\w.-]+)'
$hostsRegex.Matches($entries)
对我来说很好。
注意正则表达式中的
(?m)
多行修饰符。另外,也不必在字符类中转义.
,:
或-
。最后,将表达式直接转换为
[Regex]
,从而消除了以后跳过“静态方法”箍的需要。
关于regex - 主机文件的正则表达式的行为有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220400/