Skip to content

Instantly share code, notes, and snippets.

@amnich
Last active August 22, 2017 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amnich/829c50c8ec10f09b64f80c9a1ca5b9fe to your computer and use it in GitHub Desktop.
Save amnich/829c50c8ec10f09b64f80c9a1ca5b9fe to your computer and use it in GitHub Desktop.
# Monitor hostname ip change
# First create CSV
# Resolve-Host -HostName HostName | Export-Csv -Path $hosts_csv_path -Encoding UTF8
# or Add hosts
# Resolve-Host -HostName AnotherHostname | Export-Csv -Path $hosts_csv_path -Encoding UTF8 -Append
function Resolve-Host {
param($HostName)
BEGIN {
Write-verbose "In function Resolve-Host"
}
PROCESS {
Write-Verbose "$hostName"
$host_ips = [System.Net.Dns]::GetHostAddresses("$hostName")
if ($?) {
foreach ($host_ip in $host_ips) {
Write-Verbose " $($host_ip.ipaddresstostring)"
[pscustomobject][ordered]@{
HostName = $hostName
IP = $host_ip.ipaddresstostring
Date = Get-Date -Format ("yyyy-MM-dd")
}
}
}
}
}
$OldVerbosePreference = $VerbosePreference
$VerbosePreference = "continue"
#path to csv with hosts and ips
$hosts_csv_path = "C:\Temp\hosts.csv"
$scriptname = $MyInvocation.MyCommand.Name
$LogPath = "c:\Logs\"
$log = "$LogPath$scriptname.log"
Start-Transcript $log
$email_props = @{
SMTP = "192.168.1.1"
From = "$env:computername@domain.com"
To = "email.to@domain.com"
}
if ($my_error) {
Remove-Variable my_error -ErrorAction SilentlyContinue
}
Write-Verbose "CSV Path $hosts_csv_path"
try {
$hosts_csv = Import-Csv $hosts_csv_path -ErrorVariable +my_error
} catch {
Throw "Error importing $hosts_csv_path`nHint: Create CSV`n Resolve-Host -HostName HostName | Export-Csv -Path $hosts_csv_path -Encoding UTF8`n$($my_error[0] | out-string)"
}
if (-not $hosts_csv.hostname -or $hosts_csv.count -eq 0) {
Throw "No results from CSV file"
}
write-verbose "Hosts from file`n $($hosts_csv | out-string)"
#group by hostname
$host_list = $hosts_csv | Group-Object -Property hostname -ErrorVariable +my_error
$results = foreach ($host_single in $host_list) {
$hostname = $host_single.Name
$query = Resolve-Host -HostName $hostname
if ($query) {
foreach ($row in $query) {
if (!($host_single.group.ip -contains $row.ip)) {
$row
Write-Verbose " Add $($row.ip)"
} else {
Write-Verbose " Skip $($row.ip)"
}
}
}
}
if ($results) {
Write-Verbose "Send mail with results"
Send-MailMessage @email_props -Subject "Hostname IP change" -Body $(($results | ForEach-Object {"$($_.ip) $($_.hostname)"}) -join "`n")
Write-Verbose "Export results"
$results | Export-Csv -Append $hosts_csv_path -NoTypeInformation -Encoding utf8 -ErrorVariable +my_error
}
Stop-Transcript
if ($my_error) {
Write-Warning "Send Errors"
Send-MailMessage @email_props -Subject "Error in $scriptname " -Body $(Get-Content $log)
}
$VerbosePreference = $OldVerbosePreference
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment