经典的powershell example1

简介:

老外写的一个比较经典的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

    }

}

 

改进:

# 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
        }
 }

本文转自 bilinyee博客,原文链接:  http://blog.51cto.com/ericfu/1872822      如需转载请自行联系原作者


相关文章
|
存储 缓存 网络协议
|
缓存 网络协议 Windows