How to retry a script block in PowerShell

by May 23, 2017

Hi Guys,

I have recently started learning PS and I think I am catching on pretty well. I have written a piece of code which lets me query the local admin group member of servers in a OU and then remove anything non-standard accounts. Now mostly the script works fine, however on some machines even though they are online and accessible. I get the below error message.

 

The following exception occurred while retrieving member "Invoke": "The network path was not found.
"
At C:PowerShellScriptsGetLocalAdminMELocal_Admin.ps1:48 char:2
+ $objGroupMembers = $objGroup.Invoke("Members") | foreach {$_.GetType().InvokeMe …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember
#####################################################################################################

 

The part of the code which queries for the local admin group membership is:

####################################################
foreach ($server in $serverlist) {

$reachable = Test-connection -ComputerName $server -Count 3 -Quiet

if($reachable -eq "true"){
try{
write-host "Checking server $server"
$objGroup = [ADSI]("WinNT://$server/Administrators")
$objGroupMembers = $objGroup.Invoke("Members") | foreach {$_.GetType().InvokeMember("Name", 'GetProperty',$null, $_, $null)}
}

Catch

{

$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
ConvertTo-Html –building "<H4 style=color:red>I failed to connect the server $server, possibily a name resolution issue. Needs to be checked manually</H4>" | Out-File -Append $errorreport

}

}
####################################################

What i need to do is for the failed computers, have the script try to retrieve the members a couple of times, like retrying. Chances are even that might fail
but its Ok, since I have tried a couple of times before checking the next server.

Also if I try to connect to the fail servers by IP, it works! But as now I will be happy if I can build a retry action to this issue..

Any idea?

-A