Monitor Website IP Changes Hourly with PowerShell and Capture Ping Results
## Monitor Website IP Changes Hourly with PowerShell and Capture Ping Results
This blog post will guide you through creating a PowerShell script that automatically checks if a specific website's IP address has changed every hour. If a change is detected, the script will execute the `ping` command and save a screenshot of the output to a designated folder.
Here's the PowerShell script:
```powershell
# Configuration
$TargetSite = "example.com" # Website address to monitor for IP changes
$LogFilePath = "C:\Temp\IPChangeLog.txt" # Path to save the log file
$ScreenshotFolderPath = "C:\Screenshots" # Folder path to save screenshots
# Create the screenshot folder if it doesn't exist
if (-not (Test-Path -Path $ScreenshotFolderPath -PathType Container)) {
New-Item -Path $ScreenshotFolderPath -ItemType Directory -Force | Out-Null
}
# Initialize variable to store the previous IP address
$PreviousIP = $null
# Function to check for IP change and capture screenshot
function Check-IPChange {
param(
[string]$Site
)
try {
# Get the current IP address using Resolve-DnsName
$CurrentIP = (Resolve-DnsName -Name $Site).IpAddress
# Compare with the previous IP address
if ($PreviousIP -ne $CurrentIP) {
# IP address has changed
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "$Timestamp - IP address changed: $PreviousIP -> $CurrentIP ($Site)"
# Log the change to the file
"$Timestamp - IP address changed: $PreviousIP -> $CurrentIP ($Site)" | Out-File -Append $LogFilePath
# Execute the ping command
$PingOutput = ping $Site
Write-Host "Ping Result:"
Write-Host $PingOutput
# Save a screenshot
$ScreenshotFileName = "<span class="math-inline">ScreenshotFolderPath\\$Site\-IPChanged\-</span>(Get-Date -Format "yyyyMMdd-HHmmss").png"
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
$bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
$bitmap = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
# Capture the entire screen
$graphics.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bounds.Size)
$bitmap.Save($ScreenshotFileName, [System.Drawing.Imaging.ImageFormat]::Png)
Write-Host "Ping result screenshot saved to: $ScreenshotFileName"
# Update the previous IP address
$PreviousIP = $CurrentIP
} else {
# IP address has not changed
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Write-Host "$Timestamp - IP address unchanged ($Site)" # Uncomment if you want to log unchanged status
}
# Update the previous IP address on the first run or when no change occurs
if ($PreviousIP -eq $null) {
$PreviousIP = $CurrentIP
}
} catch {
Write-Error "An error occurred: $($_.Exception.Message)"
"$Timestamp - An error occurred: $($_.Exception.Message)" | Out-File -Append $LogFilePath
}
}
# Scheduling (run every hour)
$Action = {
Check-IPChange -Site $TargetSite
}
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration ([TimeSpan]::MaxValue)
$TaskName = "Check-$TargetSite-IPChange"
$TaskDescription = "Checks the IP address of $TargetSite hourly and captures ping results if it changes."
$TaskAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -WindowStyle Hidden -File `"$PSCommandPath`""
# Remove existing task if it exists (optional)
if (Get-ScheduledTask -TaskName $TaskName) {
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}
Register-ScheduledTask -TaskName $TaskName -Action $TaskAction -Trigger $Trigger -Description $TaskDescription
Write-Host "Task to check '$TargetSite' IP address hourly has been registered in Task Scheduler."
Write-Host "Log file: $LogFilePath"
Write-Host "Screenshot folder: $ScreenshotFolderPath"
Explanation:
- 
Configuration:
$TargetSite: Replace"example.com"with the actual website address you want to monitor.$LogFilePath: Specify the path where you want to save the log file that records IP address changes.$ScreenshotFolderPath: Define the folder where screenshots will be saved. The script will create this folder if it doesn't exist.
 - 
Create Screenshot Folder:
- The 
ifstatement checks if the specified screenshot folder exists. If not, it creates the folder usingNew-Item. 
 - The 
 - 
Initialize Previous IP:
$PreviousIP = $null: This variable will store the IP address from the previous check. It's initialized tonull.
 - 
Check-IPChangeFunction:- Takes the 
$Site(website address) as a parameter. - Error Handling: The 
try...catchblock handles potential errors during IP resolution or pinging. - Get Current IP: 
$CurrentIP = (Resolve-DnsName -Name $Site).IpAddressuses theResolve-DnsNamecmdlet to get the current IP address of the target website. This is a more reliable way than parsingpingoutput. - Compare IPs: It compares the 
$CurrentIPwith the$PreviousIP. - IP Change Detected:
- A timestamped message indicating the IP change is displayed and logged to the 
$LogFilePath. - The 
ping $Sitecommand is executed, and the output is displayed. - Screenshot Capture:
- The necessary 
.NET Frameworkassemblies for screen capturing (System.DrawingandSystem.Windows.Forms) are loaded. - The bounds of the primary screen are retrieved.
 - A 
Bitmapobject is created with the screen dimensions. - A 
Graphicsobject is created from theBitmap. $graphics.CopyFromScreen()captures the entire screen.- The captured image is saved as a PNG file in the 
$ScreenshotFolderPathwith a filename containing the site name and timestamp. 
 - The necessary 
 $PreviousIPis updated to the$CurrentIP.
 - A timestamped message indicating the IP change is displayed and logged to the 
 - No IP Change:
- A timestamped message indicating no IP change is displayed (commented out by default, you can uncomment it if needed).
 
 - Initial IP Update:
- If 
$PreviousIPisnull(on the first run), it's set to the$CurrentIP. 
 - If 
 
 - Takes the 
 - 
Scheduling:
$Action: Defines the script block to be executed (calling theCheck-IPChangefunction).$Trigger: Creates a scheduled task trigger to run the task once, starting one hour from the current time, and repeating every hour indefinitely.$TaskName: Sets the name of the scheduled task.$TaskDescription: Provides a description for the scheduled task.$TaskAction: Defines the action to be performed, which is running the PowerShell script in a hidden window.- Remove Existing Task (Optional): The 
ifblock checks if a task with the same name already exists and removes it. You can modify or remove this part if needed. Register-ScheduledTask: Registers the new scheduled task with the defined trigger, action, name, and description.- Confirmation messages are displayed, showing the log file path and screenshot folder.
 
 
How to Use:
- Copy the script and save it as a 
.ps1file (e.g.,CheckIP.ps1). - Modify the 
$TargetSite,$LogFilePath, and$ScreenshotFolderPathvariables at the beginning of the script to match your requirements. - Run PowerShell as an administrator and execute the script. This will register the scheduled task.
 - The script will now run every hour. If the IP address of the target website changes, a screenshot of the 
pingcommand output will be saved in the specified folder, and the change will be logged in the log file. 
Important Notes:
- Running the script to register the scheduled task might require administrator privileges due to Task Scheduler modifications.
 - The scheduled task will run automatically in the background according to the defined schedule.
 - The 
Resolve-DnsNamecmdlet is available on Windows 8 and later, and Windows Server 2012 and later. For older systems, you might need to use[System.Net.Dns]::GetHostAddresses($Site).IPAddressToStringor parse the output ofnslookup, althoughResolve-DnsNameis generally more reliable. - The script captures the entire primary screen. If you need to capture a specific window or region, you'll need to add more advanced screen capturing logic.
 - Ensure that the user account under which the scheduled task runs has the necessary permissions to write to the specified log file path and screenshot folder.
 
댓글
댓글 쓰기