Stop a scan midway by pressing a key

Gaetan Meister 21 Reputation points
2021-12-01T15:10:27.503+00:00

I'm adding a scan in my script to check for available IPs in 2 subnets. I would like to be able to stop the scan midway. How would I achieve that so that we don't wait until the end of the scan ? CTRL-C will skip then end of the bigger script

# Subnet selection
function Show-Menu
    {param ( [string]$Title = 'subnet selection' )
     Write-Host "================ $Title ================"
     Write-Host "1: 192.168.128.0/24"
     Write-Host "2: 192.168.129.0/24"
     }
do
{Show-Menu
$input = Read-Host "Which subnet will the VM be on"
switch ($input)
     {
           '1' {$subnet="128_subnet"; $GW="192.168.128.1"}            
           '2' {$subnet="129_subnet"; $GW="192.168.129.1"} 
     }
 } until ($input)
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Gaetan Meister 21 Reputation points
    2021-12-01T15:52:33.783+00:00

    Apologies. wrong script

     # Subnet selection
     function Show-Menu
         {param ( [string]$Title = 'subnet selection' )
          Write-Host "================ $Title ================"
          Write-Host "1: 192.168.128.0/24"
          Write-Host "2: 192.168.129.0/24"
          }
     do
     {Show-Menu
     $input = Read-Host "Which subnet will the VM be on"
     switch ($input)
          {
       '1' {2..250|ForEach { if (!((Test-Connection 192.168.128.$_ -count 1 -Quiet) -and (resolve-dnsname -ea 0 192.168.128.$_ ))) {write-Output "IP Address Available 192.168.128.$_ and no DNS entries"}}}
       '2' {2..250|ForEach { if (!((Test-Connection 192.168.129.$_ -count 1 -Quiet) -and (resolve-dnsname -ea 0 192.168.129.$_ ))) {write-Output "IP Address Available 192.168.129.$_ and no DNS entries"}}}
          }
      } until ($input)
    
    0 comments No comments

  2. Rich Matheisen 47,901 Reputation points
    2021-12-01T16:10:54.78+00:00

    You'll need to deal $host and poll for a keypress:

    stop-powershell-with-keypress


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.