Skip to content

Commit 4592b40

Browse files
committed
Code improved / better error handling
1 parent 31098fe commit 4592b40

File tree

1 file changed

+32
-34
lines changed

1 file changed

+32
-34
lines changed

Scripts/New-IPv4PortScan.ps1

Lines changed: 32 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ param(
6565
)
6666

6767
Begin{
68-
Write-Verbose "Script started at $(Get-Date)"
68+
Write-Verbose -Message "Script started at $(Get-Date)"
6969

7070
# IANA --> Service Name and Transport Protocol Port Number Registry -> xml-file
7171
$IANA_PortList_WebUri = "https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml"
@@ -78,15 +78,15 @@ Begin{
7878
function UpdateListFromIANA
7979
{
8080
try{
81-
Write-Verbose "Create backup of the IANA Service Name and Transport Protocol Port Number Registry..."
81+
Write-Verbose -Message "Create backup of the IANA Service Name and Transport Protocol Port Number Registry..."
8282

8383
# Backup file, before donload a new version
8484
if([System.IO.File]::Exists($XML_PortList_Path))
8585
{
8686
Rename-Item -Path $XML_PortList_Path -NewName $XML_PortList_BackupPath
8787
}
8888

89-
Write-Verbose "Updating Service Name and Transport Protocol Port Number Registry from IANA.org..."
89+
Write-Verbose -Message "Updating Service Name and Transport Protocol Port Number Registry from IANA.org..."
9090

9191
# Download xml-file from IANA and save it
9292
[xml]$New_XML_PortList = Invoke-WebRequest -Uri $IANA_PortList_WebUri -ErrorAction Stop
@@ -100,7 +100,7 @@ Begin{
100100
}
101101
}
102102
catch{
103-
Write-Verbose "Cleanup downloaded file and restore backup..."
103+
Write-Verbose -Message "Cleanup downloaded file and restore backup..."
104104

105105
# On error: cleanup downloaded file and restore backup
106106
if([System.IO.File]::Exists($XML_PortList_Path))
@@ -142,15 +142,13 @@ Begin{
142142
}
143143
}
144144

145-
$NewResult = [pscustomobject] @{
145+
[pscustomobject] @{
146146
Port = $Result.Port
147147
Protocol = $Result.Protocol
148148
ServiceName = $Service
149149
ServiceDescription = $Description
150150
Status = $Result.Status
151151
}
152-
153-
return $NewResult
154152
}
155153

156154
End{
@@ -166,7 +164,7 @@ Process{
166164
}
167165
elseif(-Not([System.IO.File]::Exists($XML_PortList_Path)))
168166
{
169-
Write-Host 'No xml-file to assign service with port found! Use the parameter "-UpdateList" to download the latest version from IANA.org. This warning doesn`t affect the scanning procedure.' -ForegroundColor Yellow
167+
Write-Warning -Message "No xml-file to assign service with port found! Use the parameter ""-UpdateList"" to download the latest version from IANA.org. This warning doesn`t affect the scanning procedure."
170168
}
171169

172170
# Check if it is possible to assign service with port --> import xml-file
@@ -184,34 +182,37 @@ Process{
184182
# Validate Port-Range
185183
if($StartPort -gt $EndPort)
186184
{
187-
Write-Host "Invalid Port-Range... Check your input!" -ForegroundColor Red
188-
return
185+
Write-Error -Message "Invalid Port-Range... Check your input!" -Category InvalidArgument -ErrorAction Stop
189186
}
190187

191188
# Check if host is reachable
192-
Write-Verbose "Test if host is reachable..."
189+
Write-Verbose -Message "Test if host is reachable..."
193190
if(-not(Test-Connection -ComputerName $ComputerName -Count 2 -Quiet))
194191
{
195-
Write-Host "$ComputerName is not reachable!" -ForegroundColor Red
192+
Write-Warning -Message "$ComputerName is not reachable!"
196193

197194
if($Force -eq $false)
198195
{
199-
do {
200-
$Answer = Read-Host "Would you like to continue? (perhaps only ICMP is blocked) [yes|no]"
201-
202-
} while("yes","y","no","n" -notcontains $Answer)
203-
204-
if("no","n" -contains $Answer)
205-
{
206-
return
196+
$Title = "Continue"
197+
$Info = "Would you like to continue? (perhaps only ICMP is blocked)"
198+
199+
$Options = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes", "&No")
200+
[int]$Defaultchoice = 0
201+
$Opt = $host.UI.PromptForChoice($Title , $Info, $Options, $Defaultchoice)
202+
203+
switch($Opt)
204+
{
205+
1 {
206+
return
207+
}
207208
}
208209
}
209210
}
210211

211212
$PortsToScan = ($EndPort - $StartPort)
212213

213-
Write-Verbose "Scanning range from $StartPort to $EndPort ($PortsToScan Ports)"
214-
Write-Verbose "Running with max $Threads threads"
214+
Write-Verbose -Message "Scanning range from $StartPort to $EndPort ($PortsToScan Ports)"
215+
Write-Verbose -Message "Running with max $Threads threads"
215216

216217
# Check if ComputerName is already an IPv4-Address, if not... try to resolve it
217218
$IPv4Address = [String]::Empty
@@ -239,8 +240,7 @@ Process{
239240

240241
if([String]::IsNullOrEmpty($IPv4Address))
241242
{
242-
Write-Host "Could not get IPv4-Address for $ComputerName. (Try to enter an IPv4-Address instead of the Hostname)" -ForegroundColor Red
243-
return
243+
Write-Error -Message "Could not get IPv4-Address for $ComputerName. (Try to enter an IPv4-Address instead of the Hostname)" -Category InvalidData -ErrorAction Stop
244244
}
245245
}
246246

@@ -268,23 +268,21 @@ Process{
268268
$Status = "Closed"
269269
}
270270

271-
$Result = [pscustomobject] @{
271+
[pscustomobject] @{
272272
Port = $Port
273273
Protocol = "tcp"
274274
Status = $Status
275275
}
276-
277-
return $Result
278276
}
279277

280-
Write-Verbose "Setting up RunspacePool..."
278+
Write-Verbose -Message "Setting up RunspacePool..."
281279

282280
# Create RunspacePool and Jobs
283281
$RunspacePool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, $Threads, $Host)
284282
$RunspacePool.Open()
285283
[System.Collections.ArrayList]$Jobs = @()
286284

287-
Write-Verbose "Setting up Jobs..."
285+
Write-Verbose -Message "Setting up Jobs..."
288286

289287
#Set up job for each port...
290288
foreach($Port in $StartPort..$EndPort)
@@ -318,7 +316,7 @@ Process{
318316
[void]$Jobs.Add($JobObj)
319317
}
320318

321-
Write-Verbose "Waiting for jobs to complete & starting to process results..."
319+
Write-Verbose -Message "Waiting for jobs to complete & starting to process results..."
322320

323321
# Total jobs to calculate percent complete, because jobs are removed after they are processed
324322
$Jobs_Total = $Jobs.Count
@@ -331,7 +329,7 @@ Process{
331329
# If no jobs finished yet, wait 500 ms and try again
332330
if($Jobs_ToProcess -eq $null)
333331
{
334-
Write-Verbose "No jobs completed, wait 500ms..."
332+
Write-Verbose -Message "No jobs completed, wait 500ms..."
335333

336334
Start-Sleep -Milliseconds 500
337335
continue
@@ -350,7 +348,7 @@ Process{
350348

351349
Write-Progress -Activity "Waiting for jobs to complete... ($($Threads - $($RunspacePool.GetAvailableRunspaces())) of $Threads threads running)" -Id 1 -PercentComplete $Progress_Percent -Status "$Jobs_Remaining remaining..."
352350

353-
Write-Verbose "Processing $(if($Jobs_ToProcess.Count -eq $null){"1"}else{$Jobs_ToProcess.Count}) job(s)..."
351+
Write-Verbose -Message "Processing $(if($Jobs_ToProcess.Count -eq $null){"1"}else{$Jobs_ToProcess.Count}) job(s)..."
354352

355353
# Processing completed jobs
356354
foreach($Job in $Jobs_ToProcess)
@@ -378,13 +376,13 @@ Process{
378376

379377
} While ($Jobs.Count -gt 0)
380378

381-
Write-Verbose "Closing RunspacePool and free resources..."
379+
Write-Verbose -Message "Closing RunspacePool and free resources..."
382380

383381
# Close the RunspacePool and free resources
384382
$RunspacePool.Close()
385383
$RunspacePool.Dispose()
386384

387-
Write-Verbose "Script finished at $(Get-Date)"
385+
Write-Verbose -Message "Script finished at $(Get-Date)"
388386
}
389387

390388
End{

0 commit comments

Comments
 (0)