Ping Servers with PowerShell

本文分享了一个使用PowerShell批量检查服务器在线状态的脚本,支持循环运行、仅显示在线或离线服务器等功能。通过调用WMI的ping状态,可以高效地管理和监控大量服务器。

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

在我的工作中时常有大批服务器需要操作管理,当你从线上拿下几台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.
.DESCRIPTION
Adds some parameters. 
.PARAMETER Extension
Specifies the ping mode.
.INPUTS
None. You cannot pipe objects to ping.ps1.
.OUTPUTS
System.String. ping.ps1 returns a string with the extension or file name.
.EXAMPLE
C:\PS> C:\ping.ps1
DEMOSER01    Online!
DEMOSER02    Offline!
DEMOSER03    Online!
.EXAMPLE
C:\PS> C:\ping.ps1 -loop
DEMOSER01    Online!
DEMOSER02    Offline!
DEMOSER03    Online!
DEMOSER01    Online!
DEMOSER02    Offline!
DEMOSER03    Online!
...........................
.EXAMPLE
C:\PS> C:\ping.ps1 -online
DEMOSER01    Online!
DEMOSER03    Online!
.EXAMPLE
C:\PS> C:\ping.ps1 -offline
DEMOSER02    Offline!
.LINK
Contact: 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.ResponseTimeToLive

		if ($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 results
do
{	
	$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中断组合键停止

 

(base) C:\Users\YDQ>conda create -n labelme python=3.13 Collecting package metadata (current_repodata.json): failed # >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<< Traceback (most recent call last): File "D:\Anaconda\lib\site-packages\urllib3\response.py", line 444, in _error_catcher yield File "D:\Anaconda\lib\site-packages\urllib3\response.py", line 831, in read_chunked chunk = self._handle_chunk(amt) File "D:\Anaconda\lib\site-packages\urllib3\response.py", line 775, in _handle_chunk value = self._fp._safe_read(amt) File "D:\Anaconda\lib\http\client.py", line 632, in _safe_read raise IncompleteRead(data, amt-len(data)) http.client.IncompleteRead: IncompleteRead(6508 bytes read, 3732 more expected) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Anaconda\lib\site-packages\requests\models.py", line 816, in generate yield from self.raw.stream(chunk_size, decode_content=True) File "D:\Anaconda\lib\site-packages\urllib3\response.py", line 624, in stream for line in self.read_chunked(amt, decode_content=decode_content): File "D:\Anaconda\lib\site-packages\urllib3\response.py", line 816, in read_chunked with self._error_catcher(): File "D:\Anaconda\lib\contextlib.py", line 153, in __exit__ self.gen.throw(typ, value, traceback) File "D:\Anaconda\lib\site-packages\urllib3\response.py", line 461, in _error_catcher raise ProtocolError("Connection broken: %r" % e, e) urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(6508 bytes read, 3732 more expected)', IncompleteRead(6508 bytes read, 3732 more expected)) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Anaconda\lib\site-packages\conda\exceptions.py", line 1124, in __call__ return func(*args, **kwargs) File "D:\Anaconda\lib\site-packages\conda\cli\main.py", line 69, in main_subshell exit_code = do_call(args, p) File "D:\Anaconda\lib\site-packages\conda\cli\conda_argparse.py", line 91, in do_call return getattr(module, func_name)(args, parser) File "D:\Anaconda\lib\site-packages\conda\notices\core.py", line 109, in wrapper return func(*args, **kwargs) File "D:\Anaconda\lib\site-packages\conda\cli\main_create.py", line 41, in execute install(args, parser, 'create') File "D:\Anaconda\lib\site-packages\conda\cli\install.py", line 264, in install unlink_link_transaction = solver.solve_for_transaction( File "D:\Anaconda\lib\site-packages\conda\core\solve.py", line 132, in solve_for_transaction unlink_precs, link_precs = self.solve_for_diff(update_modifier, deps_modifier, File "D:\Anaconda\lib\site-packages\conda\core\solve.py", line 175, in solve_for_diff final_precs = self.solve_final_state(update_modifier, deps_modifier, prune, ignore_pinned, File "D:\Anaconda\lib\site-packages\conda\core\solve.py", line 280, in solve_final_state ssc = self._collect_all_metadata(ssc) File "D:\Anaconda\lib\site-packages\conda\common\io.py", line 84, in decorated return f(*args, **kwds) File "D:\Anaconda\lib\site-packages\conda\core\solve.py", line 447, in _collect_all_metadata index, r = self._prepare(prepared_specs) File "D:\Anaconda\lib\site-packages\conda\core\solve.py", line 1060, in _prepare reduced_index = get_reduced_index(self.prefix, self.channels, File "D:\Anaconda\lib\site-packages\conda\core\index.py", line 267, in get_reduced_index new_records = SubdirData.query_all(spec, channels=channels, subdirs=subdirs, File "D:\Anaconda\lib\site-packages\conda\core\subdir_data.py", line 124, in query_all result = tuple(chain.from_iterable(executor.map(subdir_query, channel_urls))) File "D:\Anaconda\lib\concurrent\futures\_base.py", line 621, in result_iterator yield _result_or_cancel(fs.pop()) File "D:\Anaconda\lib\concurrent\futures\_base.py", line 319, in _result_or_cancel return fut.result(timeout) File "D:\Anaconda\lib\concurrent\futures\_base.py", line 458, in result return self.__get_result() File "D:\Anaconda\lib\concurrent\futures\_base.py", line 403, in __get_result raise self._exception File "D:\Anaconda\lib\concurrent\futures\thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "D:\Anaconda\lib\site-packages\conda\core\subdir_data.py", line 113, in <lambda> subdir_query = lambda url: tuple( File "D:\Anaconda\lib\site-packages\conda\core\subdir_data.py", line 129, in query self.load() File "D:\Anaconda\lib\site-packages\conda\core\subdir_data.py", line 215, in load _internal_state = self._load() File "D:\Anaconda\lib\site-packages\conda\core\subdir_data.py", line 323, in _load raw_repodata_str = self._repo.repodata(mod_etag_headers) File "D:\Anaconda\lib\site-packages\conda\gateways\repodata\__init__.py", line 96, in repodata response: Response = session.get( File "D:\Anaconda\lib\site-packages\requests\sessions.py", line 600, in get return self.request("GET", url, **kwargs) File "D:\Anaconda\lib\site-packages\requests\sessions.py", line 587, in request resp = self.send(prep, **send_kwargs) File "D:\Anaconda\lib\site-packages\requests\sessions.py", line 745, in send r.content File "D:\Anaconda\lib\site-packages\requests\models.py", line 899, in content self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" File "D:\Anaconda\lib\site-packages\requests\models.py", line 818, in generate raise ChunkedEncodingError(e) requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(6508 bytes read, 3732 more expected)', IncompleteRead(6508 bytes read, 3732 more expected)) `$ D:\Anaconda\Scripts\conda-script.py create -n labelme python=3.13` environment variables: CIO_TEST=<not set> CONDA_DEFAULT_ENV=base CONDA_EXE=D:\Anaconda\condabin\..\Scripts\conda.exe CONDA_EXES="D:\Anaconda\condabin\..\Scripts\conda.exe" CONDA_PREFIX=D:\Anaconda CONDA_PROMPT_MODIFIER=(base) CONDA_PYTHON_EXE=D:\Anaconda\python.exe CONDA_ROOT=D:\Anaconda CONDA_SHLVL=1 CURL_CA_BUNDLE=<not set> HOMEPATH=\Users\YDQ LD_PRELOAD=<not set> PATH=D:\Anaconda;D:\Anaconda\Library\mingw- w64\bin;D:\Anaconda\Library\usr\bin;D:\Anaconda\Library\bin;D:\Anacond a\Scripts;D:\Anaconda\bin;D:\Anaconda\condabin;C:\Windows\system32;C:\ Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell \v1.0;C:\Windows\System32\OpenSSH;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA App\NvDLISR;C:\Program Files\dotnet;C:\Program Files\Bandizip;D:\pytho n3.13.5\Scripts;D:\python3.13.5;D:\Anaconda;D:\Anaconda\Library\mingw- w64\bin;D:\Anaconda\Library\usr\bin;D:\Anaconda\Library\bin;D:\Anacond a\Scripts;C:\Users\YDQ\AppData\Local\Microsoft\WindowsApps;D:\PyCharm\ PyCharm 2025.1.3.1\bin;. PSMODULEPATH=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\Windows PowerShell\v1.0\Modules REQUESTS_CA_BUNDLE=<not set> SSL_CERT_FILE=<not set> active environment : base active env location : D:\Anaconda shell level : 1 user config file : C:\Users\YDQ\.condarc populated config files : C:\Users\YDQ\.condarc conda version : 23.1.0 conda-build version : 3.23.3 python version : 3.10.9.final.0 virtual packages : __archspec=1=x86_64 __cuda=12.9=0 __win=0=0 base environment : D:\Anaconda (writable) conda av data dir : D:\Anaconda\etc\conda conda av metadata url : None channel URLs : https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/win-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/noarch https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/win-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/noarch https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/win-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/noarch https://repo.anaconda.com/pkgs/main/win-64 https://repo.anaconda.com/pkgs/main/noarch https://repo.anaconda.com/pkgs/r/win-64 https://repo.anaconda.com/pkgs/r/noarch https://repo.anaconda.com/pkgs/msys2/win-64 https://repo.anaconda.com/pkgs/msys2/noarch package cache : D:\Anaconda\pkgs C:\Users\YDQ\.conda\pkgs C:\Users\YDQ\AppData\Local\conda\conda\pkgs envs directories : D:\Anaconda\envs C:\Users\YDQ\.conda\envs C:\Users\YDQ\AppData\Local\conda\conda\envs platform : win-64 user-agent : conda/23.1.0 requests/2.28.1 CPython/3.10.9 Windows/10 Windows/10.0.26100 administrator : False netrc file : None offline mode : False An unexpected error has occurred. Conda has prepared the above report. If submitted, this report will be used by core maintainers to improve future releases of conda. Would you like conda to send this report to the core maintainers? [y/N]:怎么解决
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值