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
    {

        if ((Get-Command Get-NAVServerInstance -ErrorAction SilentlyContinue) -eq $null) {
            Initialize-NAVVersion 
        }

        $NAVInstances = Get-NAVServerInstance 

        if ($NAVInstances.GetType().IsArray) {
            $UsableInstances = Convert-NAVInstancesToArray $NAVInstances
            if($UsableInstances.length -lt 1){
                Write-Error "You haven't got a instance NAV compatible with your admin module version $global:NAVVersionCode"
            }
            if($UsableInstances.length -eq 1){                
                $targetInstance = $UsableInstances 
            }else{

                [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
        $global:TargetNavInstance = $targetInstance

        Write-Context
    }
}