The classic PowerShell example1

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.