Get/Get-BcManagementModule.ps1
|
<#
.SYNOPSIS Imports the management module for a specific Business Central server instance. .DESCRIPTION This function allows you to import the management module for a specific Business Central server instance. It retrieves the path to the management module from the registry and imports it. For example, the function performs an import similar to: `Import-Module 'C:\Program Files\Microsoft Dynamics 365 Business Central\240\Service\Microsoft.Dynamics.Nav.Management.psm1'`. .PARAMETER ServerInstance The name of the server instance for which the management module will be imported. .PARAMETER RequiredCmdlet Cmdlets that must resolve after loading. Callers should pass the ones they actually use, so a narrowed cmdlet surface fails here instead of several steps later. #> function Get-BcManagementModule { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$ServerInstance, [string[]]$RequiredCmdlet = @('Get-NAVServerInstance', 'Get-NAVAppInfo') ) $registryPath = Join-Path -Path "HKLM:\SYSTEM\ControlSet001\Services" -ChildPath "MicrosoftDynamicsNavServer`$$ServerInstance" try { if (-not (Test-Path -Path $registryPath)) { throw "Registry path not found: $registryPath" } $imagePath = (Get-ItemProperty -Path $registryPath -Name ImagePath).ImagePath if ($imagePath -notmatch '^(.*?)\\Microsoft\.Dynamics\.Nav\.Server\.exe') { throw "Executable path not found in ImagePath. Extracted string: $imagePath" } $serverPath = $matches[1] -replace '"', '' $adminTool = @((Join-Path $serverPath 'NavAdminTool.ps1'), (Join-Path $serverPath 'Admin\NavAdminTool.ps1')) | Where-Object { Test-Path -Path $_ } | Select-Object -First 1 $legacyModule = Join-Path -Path $serverPath -ChildPath 'Microsoft.Dynamics.Nav.Management.psm1' if ($adminTool) { . $adminTool *>&1 | Out-Null $loadedFrom = $adminTool } elseif (Test-Path -Path $legacyModule) { Import-Module "$legacyModule" -ErrorAction Stop $loadedFrom = $legacyModule if (-not (Get-Command -Name 'Get-NAVAppInfo' -ErrorAction SilentlyContinue)) { $appsModule = Join-Path $serverPath 'Admin\Microsoft.BusinessCentral.Apps.Management.psd1' if (Test-Path -Path $appsModule) { Import-Module $appsModule -ErrorAction Stop } } } else { throw "No BC management entry point found under: $serverPath" } foreach ($web in @((Join-Path $serverPath 'Admin\NAVWebClientManagement.psm1'), (Join-Path $serverPath 'NAVWebClientManagement.psm1'))) { if (Test-Path -Path $web) { Import-Module $web -ErrorAction SilentlyContinue; break } } $bcModulePattern = '^(Microsoft\.Dynamics\.Nav|Microsoft\.BusinessCentral|NAVWebClientManagement)' $missingCmdlet = @($RequiredCmdlet | Where-Object { $cmd = Get-Command -Name $_ -ErrorAction SilentlyContinue -not $cmd -or $cmd.ModuleName -notmatch $bcModulePattern }) if ($missingCmdlet) { throw "BC cmdlets not available after loading '$loadedFrom': $($missingCmdlet -join ', ')" } Write-Host "Import-Module successful: $loadedFrom" } catch { throw } } |