| $ErrorActionPreference = 'Stop' |
| |
| $ipText = @" |
| 10.10.103.31 |
| 10.10.103.61 |
| "@ |
| |
| [string[]]$ipArry = $ipText.Split([char[]]"`r`n") | % { $_.Trim() } | ? { $_.Length -gt 0 } |
| |
| |
| Write-Output "共有待处理 ip 数: $($ipArry.Length)" |
| |
| Import-Module powershell-yaml |
| |
| class YamlParser { |
| |
| $yamlObject = $null |
| |
| [void] load($filePath) { |
| |
| $yamlContent = Get-Content -Path $filePath -Raw |
| $this.yamlObject = ConvertFrom-Yaml -Yaml $yamlContent |
| } |
| |
| |
| [string[]] findProxyNamesByGroupName([string] $groupName) { |
| |
| [array]$groups = $this.yamlObject['proxy-groups'] |
| |
| for ($idx = 0; $idx -lt $groups.Count; $idx++) { |
| |
| $group = $groups[$idx] |
| |
| |
| if ($group['name'] -eq $groupName) { |
| |
| $proxies = $group.proxies |
| return $proxies |
| } |
| } |
| |
| return @() |
| } |
| |
| [string] parseGroupName([string] $rule) { |
| |
| |
| |
| |
| if ([string]::IsNullOrWhiteSpace($rule)) { |
| return $null |
| } |
| |
| $ruleArray = $rule.Split(',') |
| $groupName = $ruleArray[-1] |
| |
| return $groupName |
| } |
| |
| [string] findRuleByIp([string] $ip) { |
| |
| |
| $result = $null |
| |
| |
| foreach ($rule in $this.yamlObject.rules) { |
| |
| if ($rule -match $ip) { |
| $result = $rule |
| break |
| } |
| } |
| |
| |
| if ($result) { |
| Write-Output "找到匹配的规则: $result" |
| } |
| else { |
| Write-Output "未找到匹配的规则。" |
| } |
| |
| return $result |
| } |
| } |
| |
| $yamlFilePath = 'config.yml' |
| |
| $parser = [YamlParser]::new() |
| $parser.load($yamlFilePath) |
| |
| foreach ($ip in $ipArry) { |
| |
| $rule = $parser.findRuleByIp($ip) |
| $group = $parser.parseGroupName($rule) |
| $proxies = $parser.findProxyNamesByGroupName($group) |
| $proxies = $proxies | ? { $_ -ne 'Gateway' } |
| $proxyNems = $proxies -join ',' |
| |
| |
| |
| Write-Output "$ip $group $($proxyNems)" |
| } |