Powershell - 模式匹配

时间:2017-06-01 18:43:47

标签: powershell

我有一个要求,其中日志文件有一些IP地址,需要用引用数据库的主机名替换它。我得到输出与数据库中找到的主机名匹配。我无法打印找不到主机名的IP地址。任何人都可以帮助获得完整的输出。

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.38

Hostname.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
        }
    }

2 个答案:

答案 0 :(得分:1)

最后我能够解决它.. 代码:

$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{$_}
                 }

答案 1 :(得分:0)

试试这个:

<th data-type="html" data-sort-use="text" data-sort-initial="ascending" data-sorted="true">Code</th>