I am looking for a command (an IF test) that will run quickly to see if a computer can be connected to. I do one if-test and if it passes then I will run a slew of commands to pull the information I need. If the first test fails, then it does not run the commands as otherwise it would have to fail out on each test which would take a long time.
The following code works, but it is very slow and results in a "GUI (Not Responding)" if the computer is not on the network. I am looking for something to check quicker if it fails.
if (Test-Path "\\$PCNAME\c`$")
{
# Slew of WMI commands go here.
}
I sometimes query large lists of computers and if a majority of them are off, the command above will take a ton of time to complete.
I know this is way after the fact, but I found a solution. I was looking for an if test to try and test the connection, but when it would fail, it would take a long time to fail. When a connection was made it would go through right away.
$timeoutSeconds = 1 # set your timeout value here
$j = Start-Job -ScriptBlock {
# your commands here, e.g.
Test-Connection -ComputerName $args[0] -Count 1
} -ArgumentList $computer
#"job id = " + $j.id # report the job id as a diagnostic only
Wait-Job $j -Timeout $timeoutSeconds | out-null
if ($j.State -eq "Completed")
{
#connection to PC has been verified and WMI commands can go here.
$richtextbox1.Text = "Connection can be made to $computer"
}
elseif ($j.State -eq "Running")
{
#After the timeout ($timeoutSeconds) has passed and the test is still running, I will assume the computer cannot be connected.
$richtextbox1.Text = "Could not Connect to $computer"
}
I am not sure exactly where I got this code from. I think I used - adding a timeout to batch/powershell
I hope this helps someone in the future.