Ping Servers with PowerShell

来源:互联网 发布:新手python推荐书籍 编辑:程序博客网 时间:2024/06/06 02:52

这里给大家分享一个在工作中写的小脚本,原理很简单。

在我的工作中时常有大批服务器需要操作管理,当你从线上拿下几台server做处理操作后,就需要时刻监视server的在线状态,下面我写了一个ping server list的脚本,该脚本支持添加loop、online、offline参数。最后还会显示ping server list所花费的时间。

 

参数说明:

[loop]循环运行ping脚本

[online]只显示ping通的server

[offline]只显示未ping通的server

[loop][online]以循环模式显示ping通的server

[loop][offline]以循环模式显示未ping通的server

具体说明随后会演示。

 

脚本的核心十分的简单,调用了WMI的ping状态来判断,最后结合参数配合调用。运行的时候输入保存的server list文本地址就可以批量ping server了。

 

<#.SYNOPSIS Adds a file name extension to a supplied name..DESCRIPTIONAdds some parameters. .PARAMETER ExtensionSpecifies the ping mode..INPUTSNone. You cannot pipe objects to ping.ps1..OUTPUTSSystem.String. ping.ps1 returns a string with the extension or file name..EXAMPLEC:\PS> C:\ping.ps1DEMOSER01    Online!DEMOSER02    Offline!DEMOSER03    Online!.EXAMPLEC:\PS> C:\ping.ps1 -loopDEMOSER01    Online!DEMOSER02    Offline!DEMOSER03    Online!DEMOSER01    Online!DEMOSER02    Offline!DEMOSER03    Online!............................EXAMPLEC:\PS> C:\ping.ps1 -onlineDEMOSER01    Online!DEMOSER03    Online!.EXAMPLEC:\PS> C:\ping.ps1 -offlineDEMOSER02    Offline!.LINKContact: anders@wenov.com#>param([switch]$online,[switch]$offline,[switch]$loop)$filepath = Read-Host "Please enter the file location"$ComPList =  Get-Content "$filepath"function global:Ping_Test{   <#The Process statement list runs one time for each object in the pipeline.While the Process block is running, each pipeline object is assigned to the $_ automatic variable, one pipeline object at a time. #>PROCESS    {$results = Get-WmiObject -query "SELECT * FROM Win32_PingStatus WHERE Address = '$_'"#      $RT = $results.ResponseTime#      $TTL = $results.ResponseTimeToLiveif ($results.StatusCode -eq 0){if(($online -eq $true -and $offline -ne $true) -or ($online -ne $true -and $offline -ne $true)){Write-Host "$Server  Online!" -ForegroundColor Green}}else{if(($online -ne $true -and $offline -eq $true) -or ($online -ne $true -and $offline -ne $true)){Write-Host "$Server  Offline!" -ForegroundColor Red}}}}#call procedure output resultsdo{$time=Measure-Command{foreach ($Server in $ComPList){  $Server | Ping_Test}}Write-Host ">>>>>>>> SpendTime:"$time" <<<<<<<<<"  #add "" for $time variable can convert format to time.}while($loop) # if Switch Parameters are active the statement block cycling


 

运行界面如下(因为出于安全,我将机器名作了些涂抹):

 

 

添加loop参数,开启循环ping主机,直到按下中断组合键CTRL+C才会停止

 

添加online参数后只会显示ping通的主机

 

添加offline参数则只显示ping不通的主机

 

另外也可以使用组合参数loop和offline,脚本将会循环ping server,并且只显示ping不通的主机,直到按下CTRL+C中断组合键停止

 

原创粉丝点击