简体   繁体   中英

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. Under this condition I would need the script to stop and run the else section. I only want this script to run if $service.Status returns nothing. Where am I going wrong here?

You may try putting $null on the left hand side of the comparison.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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