Skip to content

Commit 97ee2fd

Browse files
committed
Fix #4
1 parent fb6ff38 commit 97ee2fd

File tree

1 file changed

+97
-116
lines changed

1 file changed

+97
-116
lines changed

Scripts/IPv4PortScan.ps1

+97-116
Original file line numberDiff line numberDiff line change
@@ -30,67 +30,61 @@
3030
[CmdletBinding()]
3131
param(
3232
[Parameter(
33-
Position=0,
34-
Mandatory=$true,
35-
HelpMessage='ComputerName or IPv4-Address of the device which you want to scan')]
33+
Position = 0,
34+
Mandatory = $true,
35+
HelpMessage = 'ComputerName or IPv4-Address of the device which you want to scan')]
3636
[String]$ComputerName,
3737

3838
[Parameter(
39-
Position=1,
40-
HelpMessage='First port which should be scanned (Default=1)')]
41-
[ValidateRange(1,65535)]
42-
[Int32]$StartPort=1,
39+
Position = 1,
40+
HelpMessage = 'First port which should be scanned (Default=1)')]
41+
[ValidateRange(1, 65535)]
42+
[Int32]$StartPort = 1,
4343

4444
[Parameter(
45-
Position=2,
46-
HelpMessage='Last port which should be scanned (Default=65535)')]
47-
[ValidateRange(1,65535)]
45+
Position = 2,
46+
HelpMessage = 'Last port which should be scanned (Default=65535)')]
47+
[ValidateRange(1, 65535)]
4848
[ValidateScript({
49-
if($_ -lt $StartPort)
50-
{
51-
throw "Invalid Port-Range!"
52-
}
53-
else
54-
{
55-
return $true
56-
}
57-
})]
58-
[Int32]$EndPort=65535,
49+
if ($_ -lt $StartPort) {
50+
throw "Invalid Port-Range!"
51+
}
52+
else {
53+
return $true
54+
}
55+
})]
56+
[Int32]$EndPort = 65535,
5957

6058
[Parameter(
61-
Position=3,
62-
HelpMessage='Maximum number of threads at the same time (Default=500)')]
63-
[Int32]$Threads=500,
59+
Position = 3,
60+
HelpMessage = 'Maximum number of threads at the same time (Default=500)')]
61+
[Int32]$Threads = 500,
6462

6563
[Parameter(
66-
Position=4,
67-
HelpMessage='Execute script without user interaction')]
64+
Position = 4,
65+
HelpMessage = 'Execute script without user interaction')]
6866
[switch]$Force
6967
)
7068

71-
Begin{
69+
Begin {
7270
Write-Verbose -Message "Script started at $(Get-Date)"
7371

7472
$PortList_Path = "$PSScriptRoot\Resources\ports.txt"
7573
}
7674

77-
Process{
78-
if(Test-Path -Path $PortList_Path -PathType Leaf)
79-
{
75+
Process {
76+
if (Test-Path -Path $PortList_Path -PathType Leaf) {
8077
$PortsHashTable = @{ }
8178

8279
Write-Verbose -Message "Read ports.txt and fill hash table..."
8380

84-
foreach($Line in Get-Content -Path $PortList_Path)
85-
{
86-
if(-not([String]::IsNullOrEmpty($Line)))
87-
{
88-
try{
81+
foreach ($Line in Get-Content -Path $PortList_Path) {
82+
if (-not([String]::IsNullOrEmpty($Line))) {
83+
try {
8984
$HashTableData = $Line.Split('|')
9085

91-
if($HashTableData[1] -eq "tcp")
92-
{
93-
$PortsHashTable.Add([int]$HashTableData[0], [String]::Format("{0}|{1}",$HashTableData[2],$HashTableData[3]))
86+
if ($HashTableData[1] -eq "tcp") {
87+
$PortsHashTable.Add([int]$HashTableData[0], [String]::Format("{0}|{1}", $HashTableData[2], $HashTableData[3]))
9488
}
9589
}
9690
catch [System.ArgumentException] { } # Catch if port is already added to hash table
@@ -99,30 +93,26 @@ Process{
9993

10094
$AssignServiceWithPort = $true
10195
}
102-
else
103-
{
96+
else {
10497
$AssignServiceWithPort = $false
10598

10699
Write-Warning -Message "No port-file to assign service with port found! Execute the script ""Create-PortListFromWeb.ps1"" to download the latest version.. This warning doesn`t affect the scanning procedure."
107100
}
108101

109102
# Check if host is reachable
110103
Write-Verbose -Message "Test if host is reachable..."
111-
if(-not(Test-Connection -ComputerName $ComputerName -Count 2 -Quiet))
112-
{
104+
if (-not(Test-Connection -ComputerName $ComputerName -Count 2 -Quiet)) {
113105
Write-Warning -Message "$ComputerName is not reachable!"
114106

115-
if($Force -eq $false)
116-
{
107+
if ($Force -eq $false) {
117108
$Title = "Continue"
118109
$Info = "Would you like to continue? (perhaps only ICMP is blocked)"
119110

120111
$Options = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes", "&No")
121112
[int]$DefaultChoice = 0
122-
$Opt = $host.UI.PromptForChoice($Title , $Info, $Options, $DefaultChoice)
113+
$Opt = $host.UI.PromptForChoice($Title , $Info, $Options, $DefaultChoice)
123114

124-
switch($Opt)
125-
{
115+
switch ($Opt) {
126116
1 {
127117
return
128118
}
@@ -138,63 +128,55 @@ Process{
138128
# Check if ComputerName is already an IPv4-Address, if not... try to resolve it
139129
$IPv4Address = [String]::Empty
140130

141-
if([bool]($ComputerName -as [IPAddress]))
142-
{
143-
$IPv4Address = $ComputerName
144-
}
145-
else
146-
{
147-
# Get IP from Hostname (IPv4 only)
148-
try{
149-
$AddressList = @(([System.Net.Dns]::GetHostEntry($ComputerName)).AddressList)
131+
if ([bool]($ComputerName -as [IPAddress])) {
132+
$IPv4Address = $ComputerName
133+
}
134+
else {
135+
# Get IP from Hostname (IPv4 only)
136+
try {
137+
$AddressList = @(([System.Net.Dns]::GetHostEntry($ComputerName)).AddressList)
150138

151-
foreach($Address in $AddressList)
152-
{
153-
if($Address.AddressFamily -eq "InterNetwork")
154-
{
155-
$IPv4Address = $Address.IPAddressToString
156-
break
157-
}
158-
}
159-
}
160-
catch{ } # Can't get IPAddressList
161-
162-
if([String]::IsNullOrEmpty($IPv4Address))
163-
{
164-
throw "Could not get IPv4-Address for $ComputerName. (Try to enter an IPv4-Address instead of the Hostname)"
165-
}
166-
}
139+
foreach ($Address in $AddressList) {
140+
if ($Address.AddressFamily -eq "InterNetwork") {
141+
$IPv4Address = $Address.IPAddressToString
142+
break
143+
}
144+
}
145+
}
146+
catch { } # Can't get IPAddressList
147+
148+
if ([String]::IsNullOrEmpty($IPv4Address)) {
149+
throw "Could not get IPv4-Address for $ComputerName. (Try to enter an IPv4-Address instead of the Hostname)"
150+
}
151+
}
167152

168153
# Scriptblock --> will run in runspaces (threads)...
169154
[System.Management.Automation.ScriptBlock]$ScriptBlock = {
170155
Param(
171-
$IPv4Address,
172-
$Port
156+
$IPv4Address,
157+
$Port
173158
)
174159

175-
try{
176-
$Socket = New-Object System.Net.Sockets.TcpClient($IPv4Address,$Port)
160+
try {
161+
$Socket = New-Object System.Net.Sockets.TcpClient($IPv4Address, $Port)
177162

178-
if($Socket.Connected)
179-
{
163+
if ($Socket.Connected) {
180164
$Status = "Open"
181165
$Socket.Close()
182166
}
183-
else
184-
{
167+
else {
185168
$Status = "Closed"
186169
}
187170
}
188-
catch{
171+
catch {
189172
$Status = "Closed"
190173
}
191174

192-
if($Status -eq "Open")
193-
{
175+
if ($Status -eq "Open") {
194176
[pscustomobject] @{
195-
Port = $Port
177+
Port = $Port
196178
Protocol = "tcp"
197-
Status = $Status
179+
Status = $Status
198180
}
199181
}
200182
}
@@ -209,20 +191,19 @@ Process{
209191
Write-Verbose -Message "Setting up Jobs..."
210192

211193
#Set up job for each port...
212-
foreach($Port in $StartPort..$EndPort)
213-
{
214-
$ScriptParams =@{
215-
IPv4Address = $IPv4Address
216-
Port = $Port
217-
}
194+
foreach ($Port in $StartPort..$EndPort) {
195+
$ScriptParams = @{
196+
IPv4Address = $IPv4Address
197+
Port = $Port
198+
}
218199

219200
# Catch when trying to divide through zero
220201
try {
221-
$Progress_Percent = (($Port - $StartPort) / $PortsToScan) * 100
222-
}
223-
catch {
224-
$Progress_Percent = 100
225-
}
202+
$Progress_Percent = (($Port - $StartPort) / $PortsToScan) * 100
203+
}
204+
catch {
205+
$Progress_Percent = 100
206+
}
226207

227208
Write-Progress -Activity "Setting up jobs..." -Id 1 -Status "Current Port: $Port" -PercentComplete ($Progress_Percent)
228209

@@ -232,7 +213,7 @@ Process{
232213

233214
$JobObj = [pscustomobject] @{
234215
RunNum = $Port - $StartPort
235-
Pipe = $Job
216+
Pipe = $Job
236217
Result = $Job.BeginInvoke()
237218
}
238219

@@ -245,22 +226,21 @@ Process{
245226
# Total jobs to calculate percent complete, because jobs are removed after they are processed
246227
$Jobs_Total = $Jobs.Count
247228

248-
# Process results, while waiting for other jobs
229+
# Process results, while waiting for other jobs
249230
Do {
250231
# Get all jobs, which are completed
251-
$Jobs_ToProcess = $Jobs | Where-Object -FilterScript {$_.Result.IsCompleted}
232+
$Jobs_ToProcess = $Jobs | Where-Object -FilterScript { $_.Result.IsCompleted }
252233

253234
# If no jobs finished yet, wait 500 ms and try again
254-
if($null -eq $Jobs_ToProcess)
255-
{
235+
if ($null -eq $Jobs_ToProcess) {
256236
Write-Verbose -Message "No jobs completed, wait 500ms..."
257237

258238
Start-Sleep -Milliseconds 500
259239
continue
260240
}
261241

262242
# Get jobs, which are not complete yet
263-
$Jobs_Remaining = ($Jobs | Where-Object -FilterScript {$_.Result.IsCompleted -eq $false}).Count
243+
$Jobs_Remaining = ($Jobs | Where-Object -FilterScript { $_.Result.IsCompleted -eq $false }).Count
264244

265245
# Catch when trying to divide through zero
266246
try {
@@ -275,8 +255,7 @@ Process{
275255
Write-Verbose -Message "Processing $(if($null -eq $Jobs_ToProcess.Count){"1"}else{$Jobs_ToProcess.Count}) job(s)..."
276256

277257
# Processing completed jobs
278-
foreach($Job in $Jobs_ToProcess)
279-
{
258+
foreach ($Job in $Jobs_ToProcess) {
280259
# Get the result...
281260
$Job_Result = $Job.Pipe.EndInvoke($Job.Result)
282261
$Job.Pipe.Dispose()
@@ -285,24 +264,26 @@ Process{
285264
$Jobs.Remove($Job)
286265

287266
# Check if result is null --> if not, return it
288-
if($Job_Result.Status)
289-
{
290-
if($AssignServiceWithPort)
291-
{
267+
if ($Job_Result.Status) {
268+
if ($AssignServiceWithPort) {
292269
$Service = [String]::Empty
293270

294-
$Service = $PortsHashTable.Get_Item($Job_Result.Port).Split('|')
295-
271+
if ($PortsHashTable.Get_Item($Job_Result.Port)) {
272+
$Service = $PortsHashTable.Get_Item($Job_Result.Port).Split('|')
273+
}
274+
else {
275+
$Service = @("Unknown", "Unknown")
276+
}
277+
296278
[pscustomobject] @{
297-
Port = $Job_Result.Port
298-
Protocol = $Job_Result.Protocol
299-
ServiceName = $Service[0]
279+
Port = $Job_Result.Port
280+
Protocol = $Job_Result.Protocol
281+
ServiceName = $Service[0]
300282
ServiceDescription = $Service[1]
301-
Status = $Job_Result.Status
283+
Status = $Job_Result.Status
302284
}
303285
}
304-
else
305-
{
286+
else {
306287
$Job_Result
307288
}
308289
}
@@ -319,6 +300,6 @@ Process{
319300
Write-Verbose -Message "Script finished at $(Get-Date)"
320301
}
321302

322-
End{
303+
End {
323304

324305
}

0 commit comments

Comments
 (0)