Script running slow when servers are offline.

Hi EE

Can someone help me review this script and see why it runs slow ?  a lot of the servers on the list that is checking will not be online and I seem to think
that is where its slowing down because when I use this script and know all are valid servers the script does not seem to take a long time.

function get-localusers {
param(
  [Parameter(Mandatory=$true,valuefrompipeline=$true)]
  [string]$strComputer
)
  Process {
    $Select = "Name","Class","Parent" | %{  
      Invoke-Expression "@{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}"  
    }
    If (Test-Connection $strComputer -Count 2 -Quiet){
      try{
        $adminlist =""
        $computer = [ADSI]("WinNT://" + $strComputer + ",computer")
        $AdminGroup = $computer.psbase.children.find("Administrators")
        $Adminmembers= $AdminGroup.psbase.invoke("Members") | Select $Select
        foreach ($admin in $Adminmembers) {
          $admin | Select @{N="ComputerName"  ; E={$strComputer}},
                           @{N="Administrators"; E={"$(($_.parent) -replace "WinNT://|.*/")\$($_.Name)"}},
                           Class,
                           @{N="Parent"        ; E={ $_.parent -replace '.*//.*/.*', 'local' -replace '.*//'  }}
        }
      }
      catch
        { "" | Select @{N="ComputerName";E={$strComputer}},@{N="Administrators";E={"Access Denied"}},Class,Parent }
    }
    Else {
      "" | Select @{N="ComputerName";E={$strComputer}},@{N="Administrators";E={"Not able to Ping"}},Class,Parent
    }
  }
}

  Get-Content "C:\Servers.txt" |
  get-localusers | Select ComputerName,Administrators,Class,Parent |
  Export-Csv "C:\ServerData_$((get-date).toString('MM-dd-yyyy')).csv" -NTI

Open in new window

LVL 2
MilesLoganAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jose Gabriel Ortega CastroEE Solution Guide/Topic Advisor and CEO Faru Bonon ITCommented:
What you can do is to change the line count number on line 10

 If (Test-Connection $strComputer -Count 2 -Quiet){

Open in new window


to

 If (Test-Connection $strComputer -Count 1 -Quiet){

Open in new window


Or just define and use this function:
Function Test-ComputerConnection 
{
	<#	
		.SYNOPSIS
			Test-ComputerConnection sends a ping to the specified computer or IP Address specified in the ComputerName parameter.
		
		.DESCRIPTION
			Test-ComputerConnection sends a ping to the specified computer or IP Address specified in the ComputerName parameter. Leverages the System.Net object for ping
			and measures out multiple seconds faster than Test-Connection -Count 1 -Quiet.
		
		.PARAMETER ComputerName
			The name or IP Address of the computer to ping.

		.EXAMPLE
			Test-ComputerConnection -ComputerName "THATPC"
			
			Tests if THATPC is online and returns a custom object to the pipeline.
			
		.EXAMPLE
			$MachineState = Import-CSV .\computers.csv | Test-ComputerConnection -Verbose
		
			Test each computer listed under a header of ComputerName, MachineName, CN, or Device Name in computers.csv and
			and stores the results in the $MachineState variable.
			
	#>
	[CmdletBinding()]
	param
	(
		[Parameter(Mandatory=$True,
		ValueFromPipeline=$True, ValueFromPipelinebyPropertyName=$true)]
		[alias("CN","MachineName","Device Name")]
		[string]$ComputerName	
	)
	Begin
	{
		[int]$timeout = 20
		[switch]$resolve = $true
		[int]$TTL = 128
		[switch]$DontFragment = $false
		[int]$buffersize = 32
		$options = new-object system.net.networkinformation.pingoptions
		$options.TTL = $TTL
		$options.DontFragment = $DontFragment
		$buffer=([system.text.encoding]::ASCII).getbytes("a"*$buffersize)	
	}
	Process
	{
		$ping = new-object system.net.networkinformation.ping
		try
		{
			$reply = $ping.Send($ComputerName,$timeout,$buffer,$options)	
		}
		catch
		{
			$ErrorMessage = $_.Exception.Message
		}
		if ($reply.status -eq "Success")
		{
			$props = @{ComputerName=$ComputerName
						Online=$True
			}
		}
		else
		{
			$props = @{ComputerName=$ComputerName
						Online=$False			
			}
		}
		New-Object -TypeName PSObject -Property $props
	}
	End{}
}

Open in new window


so the use in line 10:
If (Test-ComputerConnection $strComputer){

Open in new window


source code in: https://www.reddit.com/r/PowerShell/comments/3rnrj9/faster_testconnection/

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MilesLoganAuthor Commented:
Thanks man for the tips .. I will try those changes .
David Johnson, CD, MVPRetiredCommented:
about 1 minute difference here between 27 and 1 machine
function get-localusers 
{
  param(
    [Parameter(Mandatory = $true,valuefrompipeline = $true)]
    [string]$strComputer
  )
  Process {
    Write-Verbose -Message $strComputer
    $Select = 'Name', 'Class', 'Parent' | ForEach-Object -Process {
      Invoke-Expression -Command "@{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}"
    }
    If (Test-Connection -ComputerName $strComputer -Count 2 -Quiet)
    {
      try
      {
        $adminlist = ''
        $computer = [ADSI]('WinNT://' + $strComputer + ',computer')
        $AdminGroup = $computer.psbase.children.find('Administrators')
        $Adminmembers = $AdminGroup.psbase.invoke('Members') | Select-Object -Property $Select
        foreach ($admin in $Adminmembers) 
        {
          $admin | Select-Object -Property @{
            N = 'ComputerName'
            E = {
              $strComputer
            }
          }, 
          @{
            N = 'Administrators'
            E = {
              "$(($_.parent) -replace 'WinNT://|.*/')\$($_.Name)"
            }
          }, 
          Class, 
          @{
            N = 'Parent'
            E = {
              $_.parent -replace '.*//.*/.*', 'local' -replace '.*//'  
            }
          }
        }
      }
      catch
      {
        '' | Select-Object -Property @{
          N = 'ComputerName'
          E = {
            $strComputer
          }
        }, @{
          N = 'Administrators'
          E = {
            'Access Denied'
          }
        }, Class, Parent
      }
    }
    Else 
    {
      '' | Select-Object -Property @{
        N = 'ComputerName'
        E = {
          $strComputer
        }
      }, @{
        N = 'Administrators'
        E = {
          'Not able to Ping'
        }
      }, Class, Parent
    }
  }
}
$starttime = get-date

$strfilename = 'C:\ServerData_' + $( Get-Date -Format 'MM-dd-yyyy' )+ '.csv'
Get-Content -Path 'C:\Servers.txt' |
get-localusers |
Select-Object -Property ComputerName, Administrators, Class, Parent |
  
Export-Csv -Path $strfilename -NTI
$counter = (get-content "c:\servers.txt").count
$elapsedtime = (get-date) - $starttime
Write-Output -InputObject ('It took {0:hh} Hours {0:mm} Minutes and {0:ss} Seconds to process {1:N0} Computers'-f $elapsedtime,$counter)
#Start-Process -FilePath notepad.exe -ArgumentList $strfilename

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.