Select Page

Recently I explained how to install windows service using PowerShell. The problem with that code was that the path to the binary file was hardcoded in my sample, which is a bad practice. If you decide to use a different installation path, you need to remember to update the path to binaries.

There is a simple solution on how to get the execution path in PowerShell, which you can use. With that technique, it does not matter where the binaries of the service are located. You just run your install script, and it detects the execution folder automatically.

    # detect current execution directory
    $directorypath = Split-Path $MyInvocation.MyCommand.Path

The script with modification to get the execution folder using Powershell looks like this now.

    $serviceName = "MyService"
    if (Get-Service $serviceName -ErrorAction SilentlyContinue)
        $serviceToRemove = Get-WmiObject -Class Win32_Service -Filter "name='$serviceName'"
        "service removed"
        "service does not exists"
    "installing service"
    # current directory
    $directorypath = Split-Path $MyInvocation.MyCommand.Path
    $secpasswd = ConvertTo-SecureString "MyP@$$w0rd" -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential (".\MyUserName", $secpasswd)
    # you need hardcode application name anyway
    $binaryPath = $directorypath + "\ApplicationName.exe"
    New-Service -name $serviceName -binaryPathName $binaryPath -displayName $serviceName -startupType Automatic -credential $mycreds
    "installation completed"