首页 > 系统服务 > 详细

经典的powershell example1

时间:2016-11-15 01:29:04      阅读:247      评论:0      收藏:0      [点我收藏+]

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

原文:http://ericfu.blog.51cto.com/416760/1872822

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!