我有一個要求,其中日誌文件有一些IP地址,它需要被引用數據庫的主機名替換。我得到的輸出與在數據庫中找到的主機名匹配。我無法打印沒有找到主機名的IP地址,因爲它可以幫助獲得完整的輸出。Powershell - 模式匹配
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"
[email protected]()
$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
}
}
@TessellatingHeckler我不知道,如果是下面的邏輯我應該嘗試和它仍然打印只解決IP's.Below是代碼。 – Vijay
'$ log =「C:\ Users \ IP_Address.txt」 $ DB = @() $ DB = Get-Content C:\ Users \ Hostname.txt Get-Content $ log | Where-Object {$ _ -match'(? \ d {1,3} \。\ d {1,3} \。\ d {1,3} \。\ d {1,3})'} | 的ForEach-對象{ 的foreach(在$ $ DB DBE) { 如果($ _ -match $ DBE.Split( 「=>」)[0]) { 獲取內容$ log | 的foreach對象{ 如果($ _ $ -match IP){$ _ $ -replace IP,$ DBE} }} } }' –
Vijay
你好隊,我將不勝感激,如果任何人可以解決這個問題。我試過一切都沒有爲我工作。 – Vijay