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"   
 
#Checking log file
$Lines =  Get-Content $LogPath | Where-Object {$_ -match "AUDIT "}
 
#Remotely
#$Lines =  icm -cn $Server {param($LogPath)Get-Content $LogPath | Where-Object {$_ -match "AUDIT "}} -ArgumentList $LogPath
 
#Getting IP Addresses
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   
    }
}
#Selecting unique IPs
$IPUnique = $Results | Select-Object IPAddress -Unique
 
#Checking hostname
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"