The foreigner wrote a more classic PowerShell example
# Functionto Check if $Server is online
Functioncanping ($Server) {
$error. Clear ()
$tmp = test-connection $Server-erroractionsilentlycontinue
if ($?) {
Write-host "Ping succeeded: $Server"; Return $true
}
else {
Write-host "Ping failed: $Server."; Return $false
}
}
# Functionto Check if $Server is remotely accessible
Functioncanremote ($Server) {
$s = new-pssession $Server-authenticationcredssp-credential $Credentials-name "Test"-erroractionsilentlycontinue
if ($s-is[system.management.automation.runspaces.pssession]) {
Enter-pssession-session $s
Exit-pssession
Write-host "Remote Test succeeded: $Server."; Return $true
}
else {
Write-host "Remote test failed: $Server."; Return $false
}
}
# Executefunctions to check $Server
if ($Server-ne "UNC") {
if (canping $Server) {
if (-not (Canremote $Server)) {
Write-host "Exit loop REMOTE"-foregroundcolor Yellow
Continue
}
}
else {
Write-host "Exit loop PING"-foregroundcolor Yellow
Continue # ' Continue ' to the nextobject and don ' t execute the rest of the code, ' break ' exits the foreach loopcompletely
}
}
Improvements :
# Function to check if $Server is remotely accessible
Function Canremote ($Server) {
Try {
$s = new-pssession $Server-authentication credssp-credential $Credentials-name "Test"-erroraction Stop
Write-host "Remote Test succeeded: $Server."
$true
Remove-pssession $s
}
Catch {
"Remote Test failed: $Server."
$false
}
}
This article from the "Erick" blog, declined to reprint!
The classic PowerShell example1