我有一个要求,其中日志文件有一些IP地址,它需要替换为引用数据库的主机名。我正在获得与数据库中找到的主机名匹配的输出。我无法打印的IP地址的主机名找不到,因为它is.Can任何人帮助获得完整的输出。
IP_Address.txt
dhhdhja sasa 10.1.154.6
sasas swssss 10.1.154.10
assas 10.1.154.14
10.1.154.34
10.1.154.38Hostname.txt
10.1.154.6=>Host1
10.1.154.10=>Host2
10.1.154.14=>Host3电流输出
dhhdhja sasa 10.1.154.6=>Host1
sasas swssss 10.1.154.10=>Host2
assas 10.1.154.14=>Host3预期输出
dhhdhja sasa 10.1.154.6=>Host1
sasas swssss 10.1.154.10=>Host2
assas 10.1.154.14=>Host3
10.1.154.34
10.1.154.38代码
$log = "C:\Users\IP_Address.txt"
$DB=@()
$DB = Get-Content C:\Users\Hostname.txt
Get-Content $log |
Where-Object {$_ -match '(?<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'} |
ForEach-Object {
# Try to resolve the IP
Try
{
$IP = $Matches.IP
foreach($DBE in $DB)
{
if($IP -match $DBE.split("=>")[0])
{
$hostname = $DBE
if ($hostname -ne "")
{
Get-Content $log |
Where-Object {$_ -match $IP} |
ForEach-Object {
$_ -replace $IP, $hostname
}
}
}
}
}
catch
{
#$_ -replace $IP, $IP
}
}发布于 2017-06-03 14:52:48
我终于能够解决这个问题了..代码:
$log = "C:\Users\IP_Address.txt"
$DB=@()
$DB = Get-Content "C:\Users\Hostname.txt"
$file = Get-Content "C:\Users\Hostname.txt"
Get-Content $log |
Where-Object {$_ -match '(?<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'} |
ForEach-Object {
$IP = $Matches.IP
$containsWord = $file | %{$_ -match $IP}
If($containsWord -contains $true)
{
# Try to resolve the IP
$IP = $Matches.IP
foreach($DBE in $DB)
{
if($IP -match$DBE.split("=>")[0])
{
$hostname = $DBE
if ($hostname -ne "")
{
Get-Content $log |
Where-Object {$_ -match $IP} |
ForEach-Object {
$_ -replace $IP, $hostname
}
}
}
}
}
Else{$_}
}发布于 2017-06-02 04:21:15
试试这个:
$log = "C:\Users\IP_Address.txt"
$DB=@()
$DB = Get-Content C:\Users\Hostname.txt
## Loop through each line in IP_Address.txt to do the replacement, as needed
Get-Content $log | ForEach-Object {
## Perform work if we run into a line with an IP
if ($_ -match '(?<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})') {
$DBE = $DB | ? { $_ -like "$($_)*" }
## Make sure the entry we get back is a valid IP
if ($DBE -match '(?<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})') {
$_.Replace($_, $DBE) ## Replace just the IP with the IP/hostname from hostname.txt
} else {
$_ ## Else just emit the line as-is which still contains the original IP
}
} else {
$_
}
}https://stackoverflow.com/questions/44314878
复制相似问题