Module/Administration/Import-BCSDynamicsNavModules.ps1

<#
.SYNOPSIS
  Import NavAdminTool modules via a BC Server Instance
 
.DESCRIPTION
  Import NavAdminTool modules via a BC Server Instance, specify serverInstance to import modules for that specifict instance, specify bcVersion to import using a BC version, omit both to import NAV Modules for the highest version installed.
 
.PARAMETER serverInstance
  The Business Central Server Instance to import module from
 
.PARAMETER bcVersion
  The Business Central Server Instance version (e.g. 230)
 
.EXAMPLE
  Import-BCSDynamicsNavModules
  Import-BCSDynamicsNavModules -ServerInstance BC23QA
  Import-BCSDynamicsNavModules -bcVersion BC230
 
.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,
    [Parameter(ValueFromPipelineByPropertyName, Mandatory = $false)]
    [string]$bcVersion
  )

  begin {}

  process {
    if (-not [string]::IsNullOrEmpty($serverInstance)) {
      $ServicePath = (Get-WmiObject win32_service | Where-Object { $_.Name -eq "MicrosoftDynamicsNavServer`$${serverInstance}" } | Select-Object Name, DisplayName, @{Name = "Path"; Expression = { $_.PathName.split('"')[1] } }).Path
      $modulePath = Get-Item (Join-Path (Split-Path -Path $ServicePath -Parent) 'NavAdminTool.ps1')
      
      . $modulePath
     
      Write-Host "$modulePath has been imported using ServerInstance."
      return;
    }

    if (-not [string]::IsNullOrEmpty($bcVersion)) {
      $modulePath = Get-Item "C:\Program Files\Microsoft Dynamics 365 Business Central\$bcVersion\Service\NavAdminTool.ps1"
      
      . $modulePath
      
      Write-Host "$modulePath has been imported using BCVersion."
      return;
    }

    if ([String]::IsNullOrEmpty($serverInstance) -and [String]::IsNullOrEmpty($bcVersion)) {
      $modulePath = Get-Item 'C:\Program Files\Microsoft Dynamics 365 Business Central\*\Service\NavAdminTool.ps1'
      
      . $modulePath[-1]

      Write-Host "$($modulePath[-1]) has been imported."
      return;
    }

    Write-Host "No module has been imported."
  }

  end {
  }
}

Export-ModuleMember -Function Import-BCSDynamicsNavModules