编写脚本从 NIC 备份 DNS 设置,并在执行其他一些操作后将其改回原样。
$BACKUP = Get-DnsClientServerAddress -InterfaceAlias WLAN* >>c:\tmp\dns.txt
dns.txt 的内容
InterfaceAlias Interface Address ServerAddresses
Index Family
-------------- --------- ------- ---------------
WLAN 2 6 IPv4 {1.1.1.1, 8.8.8.8}
WLAN 2 6 IPv6 {}
现在为了恢复,我只需要 {} 之间的 2 个 IP,所以我从
$OLD = Get-Content C:\tmp\dns.txt | Select-String -Pattern 'ipv4' -SimpleMatch
让我剩下什么
WLAN 2 6 IPv4 {1.1.1.1, 8.8.8.8}
但是我如何去掉其余的 IP 以仅获取 $Old 中剩下的 2 个 IP
谢谢你的帮助
答案1
尝试更多之后我会回答我自己的问题
$Old = Get-Content C:\tmp\dns.txt | Select-String -Pattern 'ipv4' -SimpleMatch
$Old = Get-TextWithin $Old -StartChar '{' -EndChar '}'
$DNS = $Old -split ',\s*'
function Get-TextWithin {
[CmdletBinding()]
param(
[Parameter(Mandatory,
ValueFromPipeline = $true,
Position = 0)]
$Text,
[Parameter(ParameterSetName = 'Single', Position = 1)]
[char]$WithinChar = '"',
[Parameter(ParameterSetName = 'Double')]
[char]$StartChar,
[Parameter(ParameterSetName = 'Double')]
[char]$EndChar
)
$htPairs = @{
'(' = ')'
'[' = ']'
'{' = '}'
'<' = '>'
}
if ($PSBoundParameters.ContainsKey('WithinChar')) {
$StartChar = $EndChar = $WithinChar
if ($htPairs.ContainsKey([string]$WithinChar)) {
$EndChar = $htPairs[[string]$WithinChar]
}
}
$pattern = @"
(?<=\$StartChar).+?(?=\$EndChar)
"@
[regex]::Matches($Text, $pattern).Value
}
答案2
您不需要转储到文本文件,然后使用正则表达式解析字符串。该Get-DnsClientServerAddress
命令有一个-AddressFamily
您指定"IPv4"
仅获取这些地址的参数。
电源外壳
(Get-DnsClientServerAddress -InterfaceAlias WLAN* -AddressFamily "IPv4").ServerAddresses