Public/Search-NAVBinaries.ps1

function Search-NAVBinaries {
    <#
    .Synopsis
    Search NAV binaries, by looking at windows services.
 
    .Description
    Will look for all services with Name like MicrosoftDynamicsNavServer, and extract executable paths.
    #>

    [cmdletbinding()]
    param (
    )
    Process
    {
        $NavServerBinaryName = 'Microsoft.Dynamics.Nav.Server.exe'
        $PathNamePattern = '*'+$NavServerBinaryName+'*'
        $NavPaths = Get-WmiObject win32_service | Where-Object {$_.PathName -like $PathNamePattern -and $_.State -eq 'Running'} | Select-Object -ExpandProperty PathName

        $DistinctVersions = @{}
        $numList = New-Object System.Collections.Generic.List[System.Object]
        foreach ($TestPath in $NavPaths) {
            $Length = $TestPath.indexof('\'+$NavServerBinaryName)
            $ServiceFolderPath = $TestPath.substring(1, $Length-1)

            $PathTokens = $ServiceFolderPath.split('\')

            $ServiceVersionCode = [int] $PathTokens[$PathTokens.count-2]
            if (-not $DistinctVersions.ContainsKey($ServiceVersionCode)) {
                $DistinctVersions.Add($ServiceVersionCode, $ServiceFolderPath)
            }

            $LengthNext = $TestPath.indexof('\'+$NavServerBinaryName)+$NavServerBinaryName.Length
            $ServiceFolderPathNext = $TestPath.substring(1, $LengthNext)            
            $fullNumber = (Get-ItemProperty "$ServiceFolderPathNext").VersionInfo.ProductVersion
            $number = $fullNumber.subString(0,4)
            if($number.substring(3)-eq '.'){$number=$number.substring(0,3)}
            $numList.Add($number)
        }

        Write-Verbose 'We have found the following versions of NAV running as services on this machine:'
        #Write-Verbose $($DistinctVersions | Out-String)
 
        $DistinctVersions.GetEnumerator() | ForEach-Object {            
            $NAVVersion=$global:SupportedNAVVersionCodes[$_.Key]
            Write-Verbose (" {0,3} / {2,-6} : {1}" -F $_.Key, $_.Value, $NAVVersion)
        }

        return $DistinctVersions
    }
}