• Home /
  • Blog /
  • PowerShell: How to get execution folder
Powershell Get Execution Folder

PowerShell: How to get execution folder

Recently I explained how to install windows service using PowerShell. The problem with that code was that the path to binary file was hardcode 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'"
        $serviceToRemove.delete()
        "service removed"
    }
    else
    {
        "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"
Alex Shapovalov

Alex Shapovalov is a founder of Yaplex - an IT consulting and software development company, located in Mississauga, Ontario. Alex provides IT consulting and .NET software development services in Canada and the USA.

Yaplex - Freelance developer - white logo on black background

Yaplex ® is a custom software development company located in Mississauga, Ontario. Yaplex was founded in 2013 and provides website development, mobile development, and custom .NET software development services.

Contact Information

Mississauga, ON, Canada
Phone: +1 647 328 3809
Email: hello@yaplex.com