首页 > 代码库 > 经典的powershell example1

经典的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
        }
 }


本文出自 “Erick WAY” 博客,谢绝转载!

经典的powershell example1