I am attempting to put together a simple script that will check the status of a very large list of servers. in this case we'll call it servers.txt. I know with Test-Connection the minimum amount of time you can specify on the -count switch is 1. my problem with this is if you ended up having 1000 machines in the script you could expect a 1000 second delay in returning the results. My Question: Is there a way to test a very large list of machines against test-connection in a speedy fashion, without waiting for each to fail one at a time?
current code:
Get-Content -path C:\Utilities\servers.txt | foreach-object {new-object psobject -property #{ComputerName=$_; Reachable=(test-connection -computername $_ -quiet -count 1)} } | ft -AutoSize
Test-Connection has a -AsJob switch which does what you want. To achieve the same thing with that you can try:
Get-Content -path C:\Utilities\servers.txt | ForEach-Object { Test-Connection -ComputerName $_ -Count 1 -AsJob } | Get-Job | Receive-Job -Wait | Select-Object #{Name='ComputerName';Expression={$_.Address}},#{Name='Reachable';Expression={if ($_.StatusCode -eq 0) { $true } else { $false }}} | ft -AutoSize
Hope that helps!
I have been using workflows for that. Using jobs spawned to many child processes to be usable (for me).
workflow Test-WFConnection {
param(
[string[]]$computers
)
foreach -parallel ($computer in $computers) {
Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
}
}
used as
Test-WFConnection -Computers "ip1", "ip2"
or alternatively, declare a [string[]]$computers = #(), fill it with your list and pass that to the function.
Powershell 7 and Foreach-Object -Parallel makes it much simpler now:
Get-Content -path C:\Utilities\servers.txt | ForEach-Object -Parallel {
Test-Connection $_ -Count 1 -TimeoutSeconds 1 -ErrorAction SilentlyContinue -ErrorVariable e
if ($e)
{
[PSCustomObject]#{ Destination = $_; Status = $e.Exception.Message }
}
} | Group-Object Destination | Select-Object Name, #{n = 'Status'; e = { $_.Group.Status } }
Related
I was able to find a piece of code that could ping all systems at once, better than any other job examples I've come across. This thing can take an entire file full of hosts, line by line, and ping them all literally at the same time. But how can I add the ones that are up to my $online array? I tried adding in the true block but it didn't work. Im simply trying to stick $online += $pc somewhere. Any help would be appreciated. Thanks.
$online = #()
$pc = Get-Content C:\servers.txt
$pc | ForEach-Object { Test-Connection -ComputerName $_ -Count 1 -AsJob } | Get-Job | Receive-Job -Wait | Select-Object #{Name='ComputerName';Expression={$_.Address}},#{Name='Reachable';Expression={if ($_.StatusCode -eq 0) { $true } else { $false }}} | ft -AutoSize
You can store the result of your jobs and then filter by Reachable. I've also simplified your code a bit and added -AutoRemove which I consider important to dispose your jobs when done.
$result = Get-Content C:\servers.txt | ForEach-Object {
Test-Connection -ComputerName $_ -Count 1 -AsJob
} | Receive-Job -Wait -AutoRemoveJob | ForEach-Object {
[pscustomobject]#{
ComputerName = $_.Address
Reachable = $_.StatusCode -eq 0
}
}
$online = $result | Where-Object Reachable
# if you want just the `ComputerName` values, you can do
$online = $result | Where-Object Reachable | ForEach-Object ComputerName
# or easier, using member-access enumeration and `.Where` method
$online = $result.Where{ $_.Reachable }.ComputerName
If you're interested in grouping the results between Reachable and Not Reachable during enumeration, the way to do it is with a hash table having 2 List<T> values.
$result = #{
Online = [System.Collections.Generic.List[object]]::new()
Offline = [System.Collections.Generic.List[object]]::new()
}
Get-Content C:\servers.txt | ForEach-Object {
Test-Connection -ComputerName $_ -Count 1 -AsJob
} | Receive-Job -Wait -AutoRemoveJob | ForEach-Object {
$obj = [pscustomobject]#{
ComputerName = $_.Address
Reachable = $_.StatusCode -eq 0
}
if($obj.Reachable) {
return $result['Online'].Add($obj)
}
$result['Offline'].Add($obj)
}
$result.Online.ComputerName # => has all reachable records
I believe the issue here is the pipe ft -autosize.
Try to pipe after the if/else statement as per below:
| ForEach-Object {
if ($_.Reachable -eq $true) {
$online += $_.ComputerName
}
}
Then if you want to view the results you can always do:
$online | ft -AutoSize
I'd also suggest a better formatting as all one line isn't easy to read. Try something like this:
$online = #()
$pc = Get-Content C:\servers.txt
$pc | ForEach-Object {
Test-Connection -ComputerName $_ -Count 1 -AsJob
} | Get-Job | Receive-Job -Wait |
Select-Object #{Name='ComputerName';Expression={$_.Address}},#{Name='Reachable';Expression={
if ($_.StatusCode -eq 0) {
$true
} else {
$false
}
}} | ForEach-Object {
if ($_.Reachable -eq $true) {
$online += $_.ComputerName
}
}
$online | ft -AutoSize
I will create (with PowerShell script) a table and add the result(Positive/negative) to it.
I have a text file computers.txt, in which all PCs are listed.
Like this
CSNAME Hotfixinfo
PC1 is installed
PC2 is not installed
PC3 is installed
etc.
With my actual script I can only see the positive result.
Get-Content .\computers.txt | Where {
$_ -and (Test-Connection $_ -Quiet)
} | foreach {
Get-Hotfix -Id KB4012212 -ComputerName $_ |
Select CSName,HotFixID |
ConvertTo-Csv |
Out-File "C:\$_.csv"
}
I'd suggest parsing through and handling the positive and negative results (also faster than the pipeline ForEach-Object):
:parse ForEach ($Computer in (Get-Content C:\Path\computers.txt))
{
If (Test-Connection $Computer -Quiet)
{
$Result = Get-Hotfix -Id KB4012212 -ComputerName $Computer -ErrorAction 'SilentlyContinue'
If ($Result)
{
$Result |
Select-Object -Property CSName,HotFixID |
ConvertTo-Csv -NoTypeInformation |
Out-File "C:\$Computer.csv"
Continue :parse
}
"`"CSName`",`"HotFixID`"`r`n`"$Computer`",`"NUL`"" |
Out-File "C:\$Computer.csv"
} Else { Write-Host 'Unable to connect to $Computer' }
}
Hi I have an issue in powershell where the Do Until Condition is true, but the loop doesn't stop. If I change the -eq to 0. It will stop... Basically what this should do is get the number of computers in the text file. Store that number in $count. Then restart the service for each computer in the list until it reaches the last one.
$computers = gc C:\temp\computers.txt
$count = $computers.count
Do {
foreach($computer in $computers){
$readCount = $computer.ReadCount
gwmi win32_service -ComputerName $computer | where {$_.name -like "*was*"} | Restart-Service
}
}
Until (($count - $readCount) -eq 1)
You don't need a Do-Until loop here since you can just iterate over the computers. To skip the last computer, use the Select-Object cmdlet with the -SkipLast 1 parameter:
Get-Content 'C:\temp\computers.txt' | Select-Object -SkipLast 1 | Forach-Object {
gwmi win32_service -ComputerName $computer |
where {$_.name -like "*was*"} |
Restart-Service
}
I'm sure there is a simple solution, but I'm stuck. The output in the members column is like this
{domain\Domain Admins, domain\joerod...
How can I show the
$member
value on each line?
Function Get-AdminGroups{
foreach($i in (Get-Content C:\Users\joerod\Desktop\remove_users.txt)){
#test if machine is on the network
if (-not (Test-Connection -computername $i -count 1 -Quiet -ErrorAction SilentlyContinue)) {
Write-Warning "$i is Unavalible"
"`r"
}
else {
(invoke-command {
$members = net localgroup administrators |
? {$_ -AND $_ -notmatch "command completed successfully"} |
select -skip 4
New-Object PSObject -Property #{
Computername = $env:COMPUTERNAME
Users=$members
}
} -computer $i -HideComputerName |
Select * -ExcludeProperty RunspaceID )
}
}
}
Get-AdminGroups |ft
Iterate through $members and make an object for each one. This creates an empty array, loops through the computers in your text file, and in that loop it pulls a list of the local administrators, and for each one it creates a custom object just like you are doing, and it adds it to that array.
$Results = #()
foreach($i in (GC C:\Users\joerod\Desktop\remove_users.txt)){
#test if machine is on the network
if (!(Test-Connection -computername $i -count 1 -Quiet -ErrorAction SilentlyContinue)) {
Write-Warning "$i is Unavalible`r"
Continue
}
invoke-command {
$members = net localgroup administrators |?{$_ -AND $_ -notmatch "command completed successfully"} | select -skip 4
ForEach($member in $members){
$Results += New-Object PSObject -Property #{
Computername = $env:COMPUTERNAME
Users=$member
}
}
} -computer $i -HideComputerName # | Select * -ExcludeProperty RunspaceID
}
$Results | FT
I'm using the following code to get a list of machines with IP addresses. It prints out the hostname and IP address. If the host is offline, it says "$computername is offline." Here is the code:
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address
}
catch
{
"$computer is offline"
}
}
It works great and outputs the data like so:
Address IPV4Address
------- -----------
TESTMACHINE 192.168.1.1
TESTMACHINE2 192.168.1.2
TESTMACHINE3 is offline.
However no amount of trickery is allowing me to write all of this to a file, even though it's displaying like that in the console. It writes to a blank file or only writes the exception.
How can I capture this output exactly as it is?
You can create a custom powershell object using the same field names as the test-connection fields you are selecting and then export both success and failure to CSV. See below for an example:
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address | Export-Csv -Path .\ConnectionTest.csv -Append
}
catch
{
$Output = New-Object PSObject -Property #{
Address = $computer
IPV4Address = "Offline"
}
$Output | Export-Csv -Path .\ConnectionTest.csv -Append
}
}
In my style of writing scripts I'd use simple if..then..else loop. It seems most logical to me. You did try the "Out-File" switch after pipe, didn't you?... I have just run the below on localhost and some random name, and that worked just fine...
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
if (Test-Connection $computer -Count 1 -Quiet)
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address | Out-file -append "SomeFile.txt"
}
else
{
"$computer is offline" | Out-File -Append "SomeFile.txt"
}
}
Try this:
$csv = Get-Content TEST_MACHINES.csv
'' > foo.log
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address >> foo.log
}
catch
{
"$computer is offline" >> foo.log
}
}