Module/Administration/Import-BCSDynamicsNavModules.ps1

<#
.SYNOPSIS
 
.DESCRIPTION
 
.EXAMPLE
 
.NOTES
    Author: Mathias Stjernfelt
    Website: http://www.brightcom.se
#>

<#
.SYNOPSIS
 
.DESCRIPTION
 
.EXAMPLE
 
.NOTES
    Author: Mathias Stjernfelt
    Website: http://www.brightcom.se
#>

function Import-BCSDynamicsNavModules {
    Param (
        [Parameter(ValueFromPipelineByPropertyName, Mandatory = $false)]
        [string]$serverInstance
        )

    begin {}

    process {
        Remove-Module 'Microsoft.Dynamics.Nav.Management' -ErrorAction Ignore
        Remove-Module 'Microsoft.Dynamics.Nav.Apps.Management' -ErrorAction Ignore
        Remove-Module 'Microsoft.Dynamics.Nav.Apps.Tools' -ErrorAction Ignore

        if ([string]::IsNullOrEmpty($serverInstance)) {
            $nstRegistryPath = Get-ChildItem -path "HKLM:\SOFTWARE\Microsoft\Microsoft Dynamics NAV\" -recurse -ErrorAction SilentlyContinue | Select-Object Name | Where-Object Name -Match 'Service' | Sort-Object Name -Descending
            $nstRegistryPath = $nstRegistryPath[0].Name
            $nstRegistryPath = $nstRegistryPath.Replace("HKEY_LOCAL_MACHINE", "HKLM:")

            $nstPath = (Get-ItemProperty -Path $nstRegistryPath).Path
        }
        else {
            $serviceValues = Get-CimInstance win32_service | Where-Object{$_.Name -like "*$serverInstance"} | Select-Object Name, PathName
            $nstPath = Convert-Path $serviceValues.PathName.Split('"')[1]
            $nstPath = [System.IO.DirectoryInfo]$nstPath
            $nstPath = $nstPath.Parent.FullName
            }

        RegisterSnapIn -snapIn 'Microsoft.Dynamics.Nav.Management' -nstPath $nstPath
        RegisterSnapIn -snapIn 'Microsoft.Dynamics.Nav.Apps.Management' -nstPath $nstPath
        RegisterSnapIn -snapIn 'Microsoft.Dynamics.Nav.Apps.Tools' -nstPath $nstPath
    }

    end {
    }
}

function RegisterSnapIn($snapIn, $nstPath)
{
  if(Get-Module $snapIn)
  {
    return
  }

  $snapInAssembly = "$nstPath\$snapIn.psd1"

  if(!(Test-Path $snapInAssembly)) { $snapInAssembly = Join-Path (Get-ItemProperty -path $nstPath).Path "\$snapIn.dll" }

  Import-Module $snapInAssembly -ErrorAction SilentlyContinue -Global
}

Export-ModuleMember -Function Import-BCSDynamicsNavModules