Patch/Cmdlets/NAV/Import-NavModule.ps1

<#
.SYNOPSIS
    Find and import Business Central powershell modules to current powershell session
.DESCRIPTION
    On some installations Business Central might be installed to path different than default.
    This functions searches system registry for propper path to dev as admin modules and imports them.
.PARAMETER Service
    Tells to import Business Central Administration module
.PARAMETER Development
    Tells to import Business Central Administration development module
.EXAMPLE
    Import-NavModule -Admin -Development
#>

function Import-NavModule {
    [alias("ipbcmo","Import-BCModule")]
    [CmdletBinding()]
    param (
        [Alias("Admin")]
        [switch]$Service,
        [switch]$Development
    )

    if(Test-Path 'c:\run\prompt.ps1'){ # module is runnint in container
        Push-Location # prompt.ps1 is ruining pocation
        & 'c:\run\prompt.ps1' -silent
        Pop-Location
        Get-Module -Name "*Microsoft.Dynamics*" | Import-Module -Scope Global -Force -wa SilentlyContinue # prompt.ps1 only loads modules to local scope, so I reimport them to global
    } else {
        $RegistryBasePath = "HKLM:\SOFTWARE\{0}\Microsoft\Microsoft Dynamics NAV\140\{1}"

        if ($Service) {
            if (-not (Get-Module Microsoft.Dynamics.Nav.Apps.Management)) {
                $ModulePath = Get-ItemProperty -Path ($RegistryBasePath -f "", 'Service') -Name "Path"
                Import-Module (Join-Path $ModulePath.Path 'Microsoft.Dynamics.Nav.Management.psd1') -Scope Global -Force -Verbose:$false -WarningAction "SilentlyContinue" *>$null
                Import-Module (Join-Path $ModulePath.Path 'Microsoft.Dynamics.Nav.Apps.Management.psd1') -Scope Global -Force -Verbose:$false -WarningAction "SilentlyContinue" *>$null
                Write-Verbose "Microsoft.Dynamics.Nav.Apps.Management loaded from path $($ModulePath.Path)"
            } else {
                Write-Verbose "Microsoft.Dynamics.Nav.Apps.Management already loaded"
            }
        }

        if ($Development) {
            if (-not (Get-Module Microsoft.Dynamics.Nav.Model.Tools)) {
                if ([Environment]::Is64BitProcess) {
                    $Wow6432Node = "Wow6432Node"
                }
                $ModulePath = Get-ItemProperty -Path ($RegistryBasePath -f $Wow6432Node, 'RoleTailored Client') -Name "Path"
                Import-Module (Join-Path $ModulePath.Path 'Microsoft.Dynamics.Nav.Model.Tools.psd1') -Scope Global -Force -Verbose:$false -WarningAction "SilentlyContinue" -ErrorAction Stop | Out-Null
                Write-Verbose "Microsoft.Dynamics.Nav.Model.Tools loaded from path $($ModulePath.Path)"
            } else {
                Write-Verbose "Microsoft.Dynamics.Nav.Model.Tools already loaded"
            }
        }
    }
}

Export-ModuleMember -Function "Import-NavModule" -Alias "ipbcmo", "Import-BCModule"