简体   繁体   English

使用PowerShell检查Windows服务状态

[英]Check Windows Services status using PowerShell

By writing a script in PowerShell, I'd like to determine whether a Windows service is running or not running. 通过在PowerShell中编写脚本,我想确定Windows服务是否正在运行。 For this, I have constructed the following script: 为此,我构建了以下脚本:

#Variables

$winupdate = 'Windows Update'
$running = 'Running'

#Function

function CheckServiceStatus {
param($winupdate)
$getservice = Get-Service -Name $winupdate
if($getservice.Status -ne $running){
    Start-Service $winupdate 
    Write-host "Starting" $winupdate "service"|out-file "C:\Users\ArifSohM\Desktop\Stuff for PowerShell\results.txt"
    }
}

To interpret, what I've tried to do here is simply, create a function called "CheckServiceStatus". 为了解释,我在这里尝试做的只是创建一个名为“ CheckServiceStatus”的函数。 Within that function, I have created a parameter and placed the variable of the Windows service name within this parameter. 在该函数中,我创建了一个参数,并将Windows服务名称的变量放在该参数中。 Then, I have placed the "Get-Service" cmdlet into another variable called "$getservice". 然后,将“ Get-Service” cmdlet放入另一个名为“ $ getservice”的变量中。 I then went onto starting an IF statement that is supposed to check if the service is running, so what I've said here is, if the service is NOT running, start the service, create a text file and output a confirmation message into it. 然后,我开始执行一个IF语句,该语句应该检查该服务是否正在运行,所以我在这里说的是,如果该服务未运行,请启动该服务,创建一个文本文件并向其中输出一条确认消息。 。

After hitting run on the above script, nothing seems to happen. 按上述脚本运行后,似乎什么也没有发生。 Am I doing something wrong? 难道我做错了什么? Am I missing something? 我想念什么吗? Any help will be much appreciated! 任何帮助都感激不尽!

you are using service display name instead of service name. 您正在使用服务显示名称而不是服务名称。

the service name of windows update "wuauserv" change the winupdate variable part and you should be fine Windows更新“ wuauserv”的服务名称更改了winupdate变量部分,你应该很好

$winupdate = 'wuauserv'

function definition should be before calling that function and function call statement 函数定义应在调用该函数和函数调用语句之前

full code: 完整代码:

function CheckServiceStatus {
param($winupdate)
$getservice = Get-Service -Name $winupdate
if($getservice.Status -ne $running){
    Start-Service $winupdate 
    Write-output "Starting" $winupdate "service"|out-file "C:\Users\ArifSohM\Desktop\Stuff for PowerShell\results.txt"
    }
}

#Variables

$winupdate = 'wuauserv'
$running = 'Running'
CheckServiceStatus $winupdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM