代码改变世界

PowerShell2.0之Windows排错(四)检查启动服务

2011-01-19 23:27  @天行健中国元素  阅读(1961)  评论(1编辑  收藏  举报

在Windows中有些服务随系统启动,如果其中的某个服务无法启动,则可能导致系统不稳定或其他不可预知的结果。如果服务出错,首先需要检查服务。将其按照启动类型排列。然后查找所有停止自动运行的服务,如图1所示。

image

图1 检查未启动的自动运行服务是排错的基本步骤

为了便于在脚本中查询未启动的自动运行服务,创建名为“AutoServiceNotRunning.ps1”的脚本,其代码如下:

param($computer="localhost", [switch]$help)

function funHelp()

{

$helpText=@"

DESCRIPTION:

NAME: AutoServicesNotRunning.ps1

Displays a listing of services that are set to automatic, but are not presently running

PARAMETERS:

-computer The name of the computer

-help prints help file

SYNTAX:

AutoServicesNotRunning.ps1 -computer WebServer

Displays a listing of all non running servicesthat are set to automatically start on a computer named WebServermunich

AutoServicesNotRunning.ps1

Displays a listing of all services that are set to automatic, but are not presently running on the local machine

AutoServicesNotRunning.ps1 -help ?

Displays the help topic for the script

"@

$helpText

exit

}

if($help){ "Obtaining help ..." ; funhelp }

$wmi = Get-WmiObject -Class win32_service -computername $computer `

-filter "state <> 'running' and startmode = 'auto'"

if($wmi -eq $null)

{ "No automatic services are stopped" }

Else

{

"There are $($wmi.count) automatic services stopped.

The list follows ... "

foreach($service in $wmi) { $service.name }

}

该脚本使用Get-WmiObject cmdlet查询Win32_Service WMI类,通过自定义仅返回设置为自动运行服务器的当前状态,输出信息说明其是否正常。通过指定-computername参数选择本地或远程计算机,使用-filter参数减少返回的Win32_Service类的实例数量。因为只需要知道启动类型设置为自动,但未运行的服务。需要判断查询WMI结果,如果$wmi变量值为空,则表示自动运行的服务正常;如果有未运行自动启动的服务,则输出其数量,然后使用foreach语句输出其名称。此脚本的执行结果如图2所示。

image

图2 执行结果

作者: 付海军
出处:http://fuhj02.cnblogs.com
版权:本文版权归作者和博客园共有
转载:欢迎转载,为了保存作者的创作热情,请按要求【转载】,谢谢
要求:未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
个人网站: http://txj.lzuer.com/