简体   繁体   English

电源 Shell 获取服务问题

[英]Power Shell Get Service Issue

Hi I need to get a script that will do the following:嗨,我需要一个脚本来执行以下操作:

  1. Check if a service exists检查服务是否存在
  2. If the service doesn't exist run my script如果服务不存在运行我的脚本
  3. If the service exists do nothing如果服务存在,什么也不做

Here is what I have but it's not working for me:这是我所拥有的,但它对我不起作用:

    $service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
if($service.Status -eq $NULL)
{
$CLID = $inclid
New-Item -Path "c:\" -Name "folder" -ItemType "directory"
Invoke-WebRequest -Uri https://something.com\setup.exe -OutFile c:\folder\swibm#$CLID#101518#.exe
$installer = "swibm#$CLID#101518#.exe"
Start-Process -FilePath $installer -WorkingDirectory "C:\folder"
}
else
{
Write-Host "Client Already Installed"
}

If I run $service.Status alone I get an "OK" returned.如果我单独运行$service.Status我会得到一个“OK”返回。 Under this condition I would need the script to stop and run the else section.在这种情况下,我需要脚本停止并运行 else 部分。 I only want this script to run if $service.Status returns nothing.如果$service.Status什么都不返回,我只希望这个脚本运行。 Where am I going wrong here?我在哪里错了?

You may try putting $null on the left hand side of the comparison.您可以尝试将 $null 放在比较的左侧。

If($null -eq $services.status)

Here is a nice write up discussing it 是一篇很好的文章讨论它

Simpler way to check if service exists:检查服务是否存在的更简单方法:

if( Get-WmiObject -Class Win32_Service -Filter "Name='servicename'" ) {
    # Service exists
}
else {
    # Service doesn't exist
}

... or use the Get-Service cmdlet: ...或使用Get-Service cmdlet:

if( Get-Service -ErrorAction SilentlyContinue -Name servicename ) {
    # Service exists
}
else {
    # Service doesn't exist
}

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

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