powershell select string pattern ip address code example
Example: extract ip address from string powershell pattern
$Results = @()
$Hosts = @()
$Server = "Server01"
$LogPath = "C:\logs\$Server\logs\server.log"
$Lines = Get-Content $LogPath | Where-Object {$_ -match "AUDIT "}
Foreach ($Line in $Lines) {
$IP = $Object1 = $null
$IP = ($Line | Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value
IF($IP -notmatch "0.0.0.0"){
$Object1 = New-Object PSObject -Property @{
IPAddress = $IP
}
$Results += $Object1
}
}
$IPUnique = $Results | Select-Object IPAddress -Unique
Foreach ($Item in $IPUnique) {
$HostName = $Object2 = $null
$HostName = (Resolve-DnsName $Item.IPAddress -ErrorAction SilentlyContinue).NAMEHOST
If(!$HostName){$Hostname = "None"}
$Object2 = New-Object PSObject -Property @{
IPAddress = $item.ipaddress
NameHost = $HostName
}
$Hosts += $Object2
}
$Hosts | Out-GridView -Title "Hostnames"