L04D1NG
L04D1NG

Reputation: 23

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?

Upvotes: 1

Views: 329

Answers (2)

zett42
zett42

Reputation: 27756

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
}

Upvotes: 2

Doug Maurer
Doug Maurer

Reputation: 8868

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

Upvotes: 2

Related Questions