Skip to content

Instantly share code, notes, and snippets.

@byronwai
Created February 20, 2025 06:38
Show Gist options
  • Select an option

  • Save byronwai/d6410509983da44515606975c3509ba1 to your computer and use it in GitHub Desktop.

Select an option

Save byronwai/d6410509983da44515606975c3509ba1 to your computer and use it in GitHub Desktop.
param (
[string]$Target, # Target IP or domain provided as an argument
[string]$OutputFile = "ScanResults.csv" # Default output file
)
# Check if Target is provided
if (-not $Target) {
Write-Host "Usage: .\PortScanner.ps1 -Target <IP or Domain>"
exit
}
# Define range of ports to scan
$startPort = 1
$endPort = 65535
# Create an array to store results
$results = @()
# Display header
Write-Host "`nScanning $Target from port $startPort to $endPort..." -ForegroundColor Cyan
# Scan ports
for ($port = $startPort; $port -le $endPort; $port++) {
$result = Test-NetConnection -ComputerName $Target -Port $port -InformationLevel Quiet
if ($result) {
# Store result
$results += [PSCustomObject]@{
"Target" = $Target
"Port" = $port
"Status" = "Open"
}
# Print result to console
Write-Host "Port $port is Open" -ForegroundColor Green
}
# Moderate scan speed by adding a small delay
Start-Sleep -Milliseconds 10
}
# Check if results exist
if ($results.Count -gt 0) {
# Display results in table format
$results | Format-Table -AutoSize
# Export to CSV
$results | Export-Csv -Path $OutputFile -NoTypeInformation
Write-Host "`nResults saved to $OutputFile" -ForegroundColor Yellow
} else {
Write-Host "`nNo open ports found on $Target." -ForegroundColor Red
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment