Like in the heading, this is a very simple IP scanner for scanning small networks using ICMP.
This post is not just for a simple IP scanner, But demonstrates sequential and parallel code execution.
This script can be used to ping ip range from 1 to 254
$networkSegment = "192.168.1."
$startIP = 1
$endIP = 20
#To ping from 192.168.1.1 to 192.168.1.20
$scanResult = @()
$startIP..$endIP | ForEach-Object {
Write-Progress -Activity "PINGING $networkSegment$_" -Status "Progress:" -PercentComplete ($_/$endIP*100)
if(Test-Connection "$networkSegment$_" -Count 1 -ErrorAction SilentlyContinue)
{
$pingResult = New-Object -TypeName PSObject -Property @{
IP = "$networkSegment$_"
Status = "ACTIVE"
}
}
else
{
$pingResult = New-Object -TypeName PSObject -Property @{
IP = "$networkSegment$_"
Status = "INACTIVE"
}
}
$scanResult += $pingResult
}
$scanResult
Result:
Above script does the job sequentially and thereby increases the execution time. Below is another code which does the ping parallelly
Powershell workflow is used to for parallel execution. In workflow, foreach -parallel loop is available. For new version of powershell, I.e. PowerShell 7, -parallel parameter is available.
#Workflow definition
workflow Start-Scan
{
Param
(
# Start IP
[int]
$startIP,
# End IP
[int]
$endIP,
#Network Info
[string]
$networkSegment
)
$sequence = $startIP..$endIP
#limiting the parallel task to 8 at a time
foreach -parallel -throttlelimit 8 ($item in $sequence)
{
if(Test-Connection "$networkSegment$item" -Count 1 -ErrorAction SilentlyContinue)
{
$pingResult = New-Object -TypeName PSObject -Property @{
IP = "$networkSegment$item"
Status = "ACTIVE"
}
}
else
{
$pingResult = New-Object -TypeName PSObject -Property @{
IP = "$networkSegment$item"
Status = "INACTIVE"
}
}
$pingResult
}
}
#End of Workflow definition
#invoking the workflow
#To ping from 192.168.1.1 to 192.168.1.20
$result = Start-Scan 1 254 "192.168.1."
$result | Select IP, Status
Result:
As expected, the result of the parallel execution is not in the order. But the script executed faster.
Thank you for reading my post. Hope this is helpful to you.
Recent Comments