码迷,mamicode.com
首页 > 系统相关 > 详细

经典的powershell example1

时间:2016-11-15 01:31:49      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:powershell

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

标签:powershell

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!