Friday, September 30, 2011

Windows Powershell Script - Scan for active IP addresses in a Subnet then execute a batch file using PSEXEC

*** Disclaimer: This is a modified script originally posted on ComputerPerformance.co.uk. The original script is located here under Example 4. All credit for this script goes to the guys at ComputerPerformance.co.uk.

Ah yes, more administrative scripting. I have been using VBScript and batch files forever. But the more I use Powershell, the more I am liking it Smile. With that said, here is a script that I would like to share with the world! Here is what the script does, in order:

1) Start PINGING a defined subnet with the last octect starting at 1 (such as 192.168.1.1).
2) Once a PC successfully responds to PING, execute the PSEXEC command to launch a batch file on the remote computer.
3) Loop and move on to the next IP address until the end of the subnet is reached.

One caveat to this Powershell script is that once PSEXEC successfully launches the batch file, it waits for the batch file to finish before moving on to the next computer. So if you are looking to push out a software installation with this script, and that install is fairly large and lengthy, then this script is not for you. Copy\paste the text in notepad and save the file as PINGBATCH.PS1. Here is the text:

---------------------START TEXT-------------------

set-alias psexec "c:\windows\system32\psexec.exe"

#### Set the octect to start scanning at 10.
$i =10

#### Set the network IP subnet to scan.
$Ip = "192.168.1."

#### Display Text in the Powershell window.
Write-Host "IP Address"
Write-Host "----------------------------------------"


Do { $Ip4th = $Ip + $i
$Pingy = Get-WmiObject Win32_PingStatus -f "Address='$Ip4th'"
if($Pingy.StatusCode -eq 0)
    {
        "{0,0} {1,5} {2,5}" -f
        $Pingy.Address, $Pingy.StatusCode,"Deploying Script..."
        #### If the IP address is active, run the PSEXEC command.
        & psexec \\$Pingy.Address -u DOMAIN_NAME\USER_NAME -p USER_PASSWORD  \\SERVER\BATCHFILE.bat
        }
        else
        {
            #### If there is no PING response, display the following text.
            "{0,0} {1,5} {2,5}" -f $Pingy.Address, $Pingy.StatusCode, " No PING Response."
        }
       
        #### Increase the last octect by 1 and loop.
        $i++
    }
until ($i -eq 255)

----------------------END TEXT ---------------------