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.
#>


function Get-BcManagementModule {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ServerInstance
    )

    $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 '"', ''
        $managementModulePath = Join-Path -Path $serverPath -ChildPath "Microsoft.Dynamics.Nav.Management.psm1"

        if (-not (Test-Path -Path $managementModulePath)) {
            throw "Management module not found at path: $managementModulePath"
        }

        Import-Module "$managementModulePath" -ErrorAction Stop
        Write-Host "Import-Module successful"
    }
    catch {
        Write-Error "An error occurred: $_"
    }
}