Public/Select-NAVInstance.ps1

function Select-NAVInstance {
    <#
    .Synopsis
    Detect existing NAV instances and allow to select the target.
 
    .Description
    Will look for all NAV instances and propose to the user to select the good one for PlannerOne integration.
    If there is only one instance, it will be selected automaticaly.
    #>

    [cmdletbinding()]
    param (
    )
    Process
    {
        Initialize-NAVVersion 

        if ((Get-Command Get-NAVServerInstance -ErrorAction SilentlyContinue) -eq $null) {
            Import-Module $DynamicsNavManagementModule | Out-Null
        }

        $NAVInstances = Get-NAVServerInstance 

        if ($NAVInstances.GetType().IsArray) {
            $UsableInstances = Convert-NAVInstancesToArray $NAVInstances
            [string[]] $instanceNames = @() 
            foreach ($instance in $UsableInstances) {
                $instanceNames += $instance.InstanceName
            }

            $targetInstanceNumber = Show-Menu "Please choose the NAV instance in the following list" $instanceNames
            $NAVInstance = $NAVInstances[$targetInstanceNumber]            
            $targetInstance = $UsableInstances[$targetInstanceNumber]

        } else {
            $NAVInstance = $NAVInstances
            $xmlConfig = $NAVInstance | Get-NAVServerConfiguration -AsXml
            $values = $xmlConfig.configuration.appSettings.add
            $NAVServerInstance = ($values | Where-Object key -eq 'ServerInstance').value
            
            $targetInstance = Get-NAVParametersFromConfig $NAVServerInstance $global:NAVVersionCode
        }

        while ($targetInstance.SOAPServicesEnabled -ne $true -or $targetInstance.ServicesDefaultTimeZone -ne "Server Time Zone") {
            Write-Host $targetInstance.InstanceName
            Write-Host $targetInstance.SOAPServicesEnabled
            Write-Host $targetInstance.ServicesDefaultTimeZone
            Write-Warning "Modify the instance settings so that:"
            Write-Warning "- SOAP Services are enabled"
            Write-Warning "- Services Default Time Zone is set to Server Time Zone"
            Read-Host "Press enter when done"

            $targetInstance = Get-NAVParametersFromConfig $targetInstance.InstanceName $global:NAVVersionCode
        }

        Write-Host "This instance is ready for PlannerOne!"
        $global:NavInstance = $targetInstance.InstanceName

        Write-Context
    }
}