Using Powershell Workflows to scan for Hyper-V instances in parallel

Here is a powershell script I’ve worked up to scan a network for Hyper-V hosts (or at least machines that have the Hyper-V port 2179 open).

It runs the tests in parallel using the foreach –Parallel option, and I decided to limit it to 32 threads, you can experiment with different numbers.

This will search everything on 192.168.X.X.  You can easily modify it for different ranges of IPs.

This must be run in a 64 bit mode, so if you are doing this through Powershell ISE, make sure it isn’t the x86 version.



workflow workflow1{
    $port = 2179

    $net = "192.168"

    $range = 1..254
    $netrange = 0..254
  
    foreach ($nr in $netrange)
    {
        $currentnet = "{0}.{1}" -F $net,$nr
        "scanning $currentnet.0"
        foreach -Parallel -ThrottleLimit 32 ($r in $range)
        {
			$ip = "{0}.{1}" -F $currentnet,$r

			if(Test-Connection -BufferSize 32 -Count 1 -Quiet -ComputerName $ip)
			{
				InlineScript{
					$ip = $using:ip
					$port = $using:port
					Try
					{
						 $socket = new-object System.Net.Sockets.TcpClient($ip, $port)
					}
					Catch{}

					If($socket.Connected)
					{

						".................. $ip is listening on port $port" 

						$socket.Close()
					}
				}
			}
         }
    }
 }

  
 workflow1
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s