$PSScriptRoot not set in Services created with PoshProTools

As different to a normal Executable created with this tool, where $PSScriptRoot is populated with the path of the executing program, when used in Services this variable is not set.

Considering that I am not able to receive Arguments in the OnStart function, I tried to overcome this by reading a Json file with my settings, however it is not possible to find that file, even though it is located in the same folder as the executable service.

Please advise. In the meantime I had to hard code the path, which is not an elegant solution.

This is a bug and I’ve opened a issue for it: https://github.com/ironmansoftware/poshtools-issues/issues/5

Are you including a fix to this bug as well in the newest version?

Please advise.

I found the same issue but got around it by using the below few lines.

$Global:EXEPath = Split-Path (Get-Process nameofserviceexe).path -Parent

E.G. Global:ErrorLog = "($Global:EXEPath)\Error.log" - Places the Error.log in the executable root folder.

You don’t have to use the $Global: I just used it make sure that the variable was available in all functions etc.

I just found a better one. You don’t need to know the Service EXE name. -Parent in Split-Path is not required either. Try this:

Split-Path ([System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName)