Script not doing anything when ran as a service

Tool: Visual Studio Code
Version: 	2022.3.0

Hi all,

I’ve written a script which does some application metering. The basic premise is… Script reaches out to Powershell Universal, gets a list of applications to meter. It then creates some event subscriptions to find when the application is launched. It then hits a different API on my Powershell Universal server to upload the data. If I run it in a normal Powershell window, it works fine. When I package it as a service, it doesn’t work.

Below is the code.

(<# This function is called when the service is started. Once this function re - Pastebin.com)

I put in 3 start-transcripts within it, which all work when ran manually, but when done as a service it just returns that the transcript has started and nothing else. Additionally, the data doesn’t hit the server.

Are you compiling for Windows PowerShell or PS7?

Compiling for Windows Powershell

Ok. Thanks. I will take a look.

Hi Adam, just wanted to see if you had any luck one way or another with this.

Hey @Jori - Sorry for not circling back sooner. I tried creating a service and am not seeing issues with it running the script but I do wonder if it’s possible your script may be encountering errors while running.

One thing that might be a good idea would be to put a try catch around everything to rule out a terminating error throwing and causing the rest of the script to fail.

You should do somthing like:

function OnStart() { 
    try {
        RunScript()
   } catch {
       # Write exception to log file
   }
}

function RunScript() {
  # Your script here
}

Hi Adam,

I’ll give that a try. I haven’t had a problem with the service running… It runs fine, it just doesn’t detect when an application is launched when it’s running as a service. Running it just in a PowerShell window it does. I’ll try wrapping it with try catch though.

Hmm ok. I wonder if it’s some sort of permission thing. You’re running the service as local service?

Just tested that quick. It’s running as System, so I opened up a powershell window as SYSTEM using psexec. When ran as system (and not a service) it still works, so not a permission thing.

At this point my only thought is the service doesn’t like the WMIEvent subscription and FileWatcher for some reason…