D365FOLBDAdmin.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\D365FOLBDAdmin.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName D365FOLBDAdmin.Import.DoDotSource -Fallback $false
if ($D365FOLBDAdmin_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName D365FOLBDAdmin.Import.IndividualFiles -Fallback $false
if ($D365FOLBDAdmin_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'D365FOLBDAdmin' -Language 'en-US'

##CREDIT https://stackoverflow.com/questions/8800375/merging-hashtables-in-powershell-how
Function Merge-Hashtables([ScriptBlock]$Operator) {
    $Output = @{}
    ForEach ($Hashtable in $Input) {
        If ($Hashtable -is [Hashtable]) {
            ForEach ($Key in $Hashtable.Keys) {$Output.$Key = If ($Output.ContainsKey($Key)) {@($Output.$Key) + $Hashtable.$Key} Else  {$Hashtable.$Key}}
        }
    }
    If ($Operator) {ForEach ($Key in @($Output.Keys)) {$_ = @($Output.$Key); $Output.$Key = Invoke-Command $Operator}}
    $Output
}

function Add-D365LBDDatabaseDetailsandCert {
    <#
    .SYNOPSIS
   Adds the Encipherment Cert into the D365 Servers for the configuration of the local business data environment
   .DESCRIPTION
    Adds the Encipherment Cert into the D365 Servers for the configuration of the local business data environment
   .EXAMPLE
   Add-D365LBDDataEnciphermentCertConfig -Thumbprint "1243asd234213"
   Will get config from the local machine.
   .PARAMETER Thumbrint
   required string
    the thumbprint of the DataEncipherment certificate
   #>

    [alias("Add-D365DatabaseDetailsandCert")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [switch]$Clustered,
        [string[]]$DatabaseServerNames,
        [string]$Thumbprint,
        [psobject]$Config
  
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    }
    PROCESS {
        if (!$Config) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName 
        }

        foreach ($server in $Config.AllAppServerList) {
            if ($Clustered) {
                "Clustered" | Out-file \\$server\c$\ProgramData\SF\DatabaseDetailsandCert.txt -Force
                Write-PSFMessage -Level Verbose "Clustered Selected make sure you entered in all database server names in other parameter"
            }
            else {
                "NotClustered" | Out-file \\$server\c$\ProgramData\SF\DatabaseDetailsandCert.txt -Force
            }
            $Thumbprint | Out-file \\$server\c$\ProgramData\SF\DatabaseDetailsandCert.txt -append 
            $DatabaseServerNames | Out-file \\$server\c$\ProgramData\SF\DatabaseDetailsandCert.txt -append 
            
        }
        Write-PSFMessage -Level Verbose "c:\ProgramData\SF\DatabaseDetailsandCert.txt created/updated"
    }
    END {
      
    }
}

function Add-D365LBDDataEnciphermentCertConfig {
    <#
    .SYNOPSIS
   Adds the Encipherment Cert into the D365 Servers for the configuration of the local business data environment
   .DESCRIPTION
    Adds the Encipherment Cert into the D365 Servers for the configuration of the local business data environment
   .EXAMPLE
   Add-D365LBDDataEnciphermentCertConfig -Thumbprint "1243asd234213"
   Will get config from the local machine.
   .PARAMETER Thumbrint
   required string
    the thumbprint of the DataEncipherment certificate
   #>

    [alias("Add-D365DataEnciphermentCertConfig")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [string]$Thumbprint,
        [psobject]$Config
  
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    }
    PROCESS {
        if (!$Config) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName 
        }

        foreach ($server in $Config.AllAppServerList) {
            $Thumbprint | Out-file \\$server\c$\ProgramData\SF\DataEnciphermentCert.txt
        }
    }
    END {
      
    }
}

function Connect-ServiceFabricAutomatic {
    <#
   .SYNOPSIS
  todo not working yet
 
  .DESCRIPTION
   Connect-ServiceFabricAutomatic
 
  .EXAMPLE
  Connect-ServiceFabricAutomatic
 
  .EXAMPLE
  Connect-ServiceFabricAutomatic
 
  .PARAMETER Config
  optional custom object generated from Get-D365LBDConfig
  #>

    param
    (
        [Parameter(Mandatory = $false)]
        [psobject]$Config,
        [string]$SFServerCertificate,
        [string]$SFConnectionEndpoint

    )
    begin {}
    process {
        try {
            if (Get-Command Connect-ServiceFabricCluster -ErrorAction Stop) {
            }
            else {
                Write-PSFMessage -Level Error Message "Error: Service Fabric Powershell module not installed" 
            }
        }
        catch {
            Stop-PSFFunction -Message "Error: Service Fabric Powershell module not installed" -EnableException $true -Cmdlet $PSCmdlet
        }
        if ((!$Config) -and (!$SFServerCertificate) -and (!$SFConnectionEndpoint)) {
            Write-PSFMessage -Message "No paramters selected will try and get config" -Level Verbose
            $Config = Get-D365LBDConfig
            $SFConnectionEndpoint = $config.SFConnectionEndpoint
            $SFServerCertificate = $config.SFServerCertificate
        }  
        $SFServiceCert = Get-ChildItem "Cert:\localmachine\my" | Where-Object { $_.Thumbprint -eq $SFServerCertificate } 

        if (!$SFServiceCert) {
            $SFServiceCert = Get-ChildItem "Cert:CurrentUser\my" | Where-Object { $_.Thumbprint -eq $SFServerCertificate } 
            if ($SFServiceCert) {
                $CurrentUser = 'true'
            }
        }

        if (!$SFServiceCert) {
            Stop-PSFFunction -Message "Error: Can't Find SFServerCertificate $SFServerCertificate" -EnableException $true -Cmdlet $PSCmdlet
        }
        else {
            Write-PSFMessage -Level Verbose -Message "$SFServiceCert"
        }

        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $SFServerCertificate -ServerCertThumbprint $SFServerCertificate -StoreLocation LocalMachine -StoreName My
        if ($CurrentUser -eq 'true') {
            Write-PSFMessage -Message "Using Current User Certificate Store" -Level Verbose
            $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $SFServerCertificate -ServerCertThumbprint $SFServerCertificate -StoreLocation CurrentUser -StoreName My
        }
    
        if (!$connection) {
            $connection = Connect-ServiceFabricCluster
        }
        $connection
    }
    end {} 
}



function Disable-D365LBDSFAppServers {
    <#
    .SYNOPSIS
   Grabs the configuration of the local business data environment
   .DESCRIPTION
   Grabs the configuration of the local business data environment through logic using the Service Fabric Cluster XML,
   AXSF.Package.Current.xml and OrchestrationServicePkg.Package.Current.xml
   .EXAMPLE
   Get-D365LBDConfig
   Will get config from the local machine.
   .EXAMPLE
    Get-D365LBDConfig -ComputerName "LBDServerName" -verbose
   Will get the Dynamics 365 Config from the LBD server
   .PARAMETER ComputerName
   optional string
   The name of the Local Business Data Computer.
   If ignored will use local host.
   .PARAMETER ConfigImportFromFile
   optional string
   The name of the config file to import (if you are choosing to import rather than pull dynamically)
   .PARAMETER ConfigExportToFile
   optional string
   The name of the config file to export
   .PARAMETER CustomModuleName
   optional string
   The name of the custom module you will be using to caputre the version number
 
   #>

    [alias("Disable-D365SFAppServers")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [psobject]$Config
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {

       
    } 
    PROCESS {
        if (!$Config) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName 
        }

        $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
        $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $ConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My
        $AppNodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "AOSNodeType") } 
        $primarynodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "PrimaryNodeType") } 
        if ($primarynodes.count -gt 0) {
            Stop-PSFFunction -Message "Error: Primary Node configuration not supported" -EnableException -FunctionName $_
        }
        foreach ($AppNode in $AppNodes) {
            Disable-ServiceFabricNode -NodeName $AppNode.NodeName -Intent RemoveData -force -timeoutsec 30
        }
        Start-Sleep -Seconds 1

        $nodestatus = Get-serviceFabriceNode | Where-Object { $_.NodeStatus -eq 'Disabling' -and ($_.NodeType -eq "AOSNodeType") }
        do {
            $nodestatus = Get-serviceFabriceNode | Where-Object { $_.NodeStatus -eq 'Disabling' -and ($_.NodeType -eq "AOSNodeType") } 
            Start-Sleep -Seconds 5
        } until (!$nodestatus -or $nodestatus -eq 0)
        Write-PSFMessage -Message "All App Nodes Disabled" -Level VeryVerbose

    }
    END {}
}

function Enable-D365LBDSFAppServers {
    <#
    .SYNOPSIS
   Grabs the configuration of the local business data environment
   .DESCRIPTION
   Grabs the configuration of the local business data environment through logic using the Service Fabric Cluster XML,
   AXSF.Package.Current.xml and OrchestrationServicePkg.Package.Current.xml
   .EXAMPLE
   Get-D365LBDConfig
   Will get config from the local machine.
   .EXAMPLE
    Get-D365LBDConfig -ComputerName "LBDServerName" -verbose
   Will get the Dynamics 365 Config from the LBD server
   .PARAMETER ComputerName
   optional string
   The name of the Local Business Data Computer.
   If ignored will use local host.
   .PARAMETER ConfigImportFromFile
   optional string
   The name of the config file to import (if you are choosing to import rather than pull dynamically)
   .PARAMETER ConfigExportToFile
   optional string
   The name of the config file to export
   .PARAMETER CustomModuleName
   optional string
   The name of the custom module you will be using to caputre the version number
 
   #>

    [alias("Enable-D365SFAppServers")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [psobject]$Config
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
        $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $ConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My
        $AppNodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType") } 
        $primarynodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "PrimaryNodeType") } 
        if ($primarynodes.count -gt 0) {
            Stop-PSFFunction -Message "Error: Primary Node configuration not supported" -EnableException -FunctionName $_
        }
        foreach ($AppNode in $AppNodes) {
            Enable-ServiceFabricNode -NodeName $AppNode.NodeName 
        }
        Start-Sleep -Seconds 1

        $nodestatus = Get-serviceFabriceNode | Where-Object { $_.NodeStatus -eq 'Disabled' -and (($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType")) }
        do {
            $nodestatus = Get-serviceFabriceNode | Where-Object { $_.NodeStatus -eq 'Disabled' -and (($_.NodeType -eq "AOSNodeType")-or ($_.NodeType -eq "MRType")) } 
            Start-Sleep -Seconds 5
        } until (!$nodestatus -or $nodestatus -eq 0)
        Write-PSFMessage -Message "All App Nodes Enabled" -Level VeryVerbose
    }
    END{}
}

function Export-D365LBDAssetModuleVersion {
    <#
    .SYNOPSIS
   Looks inside the agent share extracts the version from the zip by using the custom module name. Puts an xml in root for easy idenitification
   .DESCRIPTION
    Exports
   .EXAMPLE
   Export-D365LBDAssetModuleVersion
  
   .EXAMPLE
    Export-D365LBDAssetModuleVersion
 
   .PARAMETER AgentShare
   optional string
    The location of the Agent Share
   .PARAMETER CustomModuleName
   optional string
   The name of the custom module you will be using to capture the version number
 
   #>

    [alias("Export-D365FOLBDAssetModuleVersion","Export-D365AssetModuleVersion")]
    param
    (
        [Parameter(Mandatory = $true)]
        [string]$AgentShare,
        [Parameter(Mandatory = $true)]
        [string]$CustomModuleName
    )
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $Filter = "*/Apps/AOS/AXServiceApp/AXSF/InstallationRecords/MetadataModelInstallationRecords/$ModuleName*.xml"
    $AssetFolders = Get-ChildItem "$AgentShare\assets" | Where-Object { $_.Name -ne "topology.xml" -and $_.Name -ne "chk" } | Sort-Object LastWriteTime 

    foreach ($AssetFolder in $AssetFolders ) {
        $versionfile = $null
        $versionfilepath = $AssetFolder.FullName + "\$ModuleName*.xml"
        $versionfile = Get-ChildItem -Path $versionfilepath
        if (($null -eq $versionfile) -or !($versionfile)) {
            ##SpecificAssetFolder which will be output
            $SpecificAssetFolder = $AssetFolder.FullName
            ##StandAloneSetupZip path to the zip that will be looked into for the module
            $StandaloneSetupZip = Get-ChildItem $SpecificAssetFolder\*\*\Packages\*\StandaloneSetup.zip

            $zip = [System.IO.Compression.ZipFile]::OpenRead($StandaloneSetupZip)
            $count = $($zip.Entries | Where-Object { $_.FullName -like $Filter }).Count

            if ($count -eq 0) {
                Write-PSFMessage -Level Verbose -Message "Invalid Zip file or Module name $StandaloneSetupZip"
            }
            else {
                $zip.Entries | 
                Where-Object { $_.FullName -like $Filter } |
                ForEach-Object { 
                    # extract the selected items from the ZIP archive
                    # and copy them to the out folder
                    $FileName = $_.Name
                    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, "$SpecificAssetFolder\$FileName") 
                }
                ##Closes Zip
                $zip.Dispose()
                $NewfileWithoutVersionPath = $SpecificAssetFolder + "\$ModuleName.xml"
                Write-PSFMessage -Message "$SpecificAssetFolder\$FileName exported" -Level Verbose

                $NewfileWithoutVersion = Get-ChildItem "$NewfileWithoutVersionPath"
                if (!$NewfileWithoutVersion) {
                    Write-PSFMessage -Message "Error Module not found" -ErrorAction Continue
                }
                [xml]$xml = Get-Content "$NewfileWithoutVersion"
                $Version = $xml.MetadataModelInstallationInfo.Version
                Rename-Item -Path $NewfileWithoutVersionPath -NewName "$ModuleName $Version.xml" -Verbose | Out-Null
                Write-PSFMessage -Message "$ModuleName $Version.xml exported" -Level Verbose
                Write-Output "$Version"
            }
        }
    }
}

function Export-D365LBDCertificates {
    <#
   .SYNOPSIS
  Looks inside the agent share extracts the version from the zip by using the custom module name.
  Puts an xml in root for easy idenitification.
  NOT working...
 
  .DESCRIPTION
   Exports
 
  .EXAMPLE
  Export-D365FOLBDAssetModuleVersion
 
  .EXAMPLE
  Export-D365FOLBDAssetModuleVersion
 
  .PARAMETER ExportLocation
  optional string
  The location where the certificates will export to.
 
  .PARAMETER Username
  optional string
  The username this will be protected to
 
  #>

    [alias("Export-D365Certificates")]
    param
    (
        [Parameter(Mandatory = $true)]
        [string]$CertThumbprint,
        [Parameter(Mandatory = $true)]
        [string]$ExportLocation,
        [string]$Username
    )
    BEGIN {
    }
    PROCESS {
   
        ##Export
        if (Test-Path -Path $ExportLocation -IsValid) {
        }
        else {
            mkdir $ExportLocation
        }
        if (!$Username) {
            $Username = whoami
        }
        try {
            Write-PSFMessage -Message "Trying to pull $CertThumbprint from LocalMachine My " -Level Verbose
            Get-ChildItem "Cert:\localmachine\my" | Where-Object { $_.Thumbprint -eq $CertThumbprint } | ForEach-Object -Process { Export-PfxCertificate -Cert $_ -FilePath $("$ExportLocation\" + $_.FriendlyName + ".pfx") -ProtectTo "$Username" }
        }
        catch {
            try {
                Write-PSFMessage -Message "Trying to pull $CertThumbprint from CurrentUser My " -Level Verbose
                Get-ChildItem "Cert:\CurrentUser\my" | Where-Object { $_.Thumbprint -eq $CertThumbprint } | ForEach-Object -Process { Export-PfxCertificate -Cert $_ -FilePath $("$ExportLocation\" + $_.FriendlyName + ".pfx") -ProtectTo "$Username" }
            }
            catch {
                Write-PSFMessage -Level Verbose "Can't Export Certificate"
                $_ 
            }
        }
    }
    END {
    }
} 

function Get-D365LBDCertsFromConfig {
    <#
       .SYNOPSIS
       Grabs the certificatedetails from the config for easier export/analysis
       .DESCRIPTION
       Grabs the certificatedetails from the config for easier export/analysis
       .EXAMPLE
       Get-D365CertDetails
       
       .EXAMPLE
        Get-D365CertDetails
     
       .PARAMETER Config
       optional psobject
       The configuration of D365 from the command Get-D365LBDConfig
       If ignored will use local host.
     
     
       #>

    [alias("Get-D365CertsFromConfig")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [string]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(Mandatory = $false)][psobject]$Config,
        [switch]$OnlyAdminCerts    
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    }
    PROCESS {
     
        $allCerts = $Config.PSObject.Properties | Where-Object { $_.name -like '*Cert*' -and  $_.name -notlike '*ExpiresAfter*'  } | Select-Object Name, value
    
        $admincerts = $allCerts | Where-Object { $_.name -eq "SFServerCertificate" -or $_.name -eq "SFClientCertificate" }
    
        if ($OnlyAdminCerts) {   
            $admincerts
        }
        else {
            $allcerts
        }
    }
    END {  
    }
}

function Get-D365LBDConfig {
    <#
    .SYNOPSIS
   Grabs the configuration of the local business data environment
   .DESCRIPTION
   Grabs the configuration of the local business data environment through logic using the Service Fabric Cluster XML,
   AXSF.Package.Current.xml and OrchestrationServicePkg.Package.Current.xml
   .EXAMPLE
   Get-D365LBDConfig
   Will get config from the local machine.
   .EXAMPLE
    Get-D365LBDConfig -ComputerName "LBDServerName" -verbose
   Will get the Dynamics 365 Config from the LBD server
   .PARAMETER ComputerName
   optional string
   The name of the Local Business Data Computer.
   If ignored will use local host.
   .PARAMETER ConfigImportFromFile
   optional string
   The name of the config file to import (if you are choosing to import rather than pull dynamically)
   .PARAMETER ConfigExportToFile
   optional string
   The name of the config file to export
   .PARAMETER CustomModuleName
   optional string
   The name of the custom module you will be using to caputre the version number
 
   #>

    [alias("Get-D365Config")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(Mandatory = $false)][string]$ConfigImportFromFile,
        [Parameter(Mandatory = $false)][string]$ConfigExportToFile,
        [Parameter(Mandatory = $false)][string]$CustomModuleName,
        [switch]$HighLevelOnly
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        Set-Location C:\
        if ($ConfigImportFromFile) {
            Write-PSFMessage -Message "Warning: Importing config this data may not be the most up to date" -Level Warning
            if (-not (Test-Path $ConfigImportFromFile)) {
                Stop-PSFFunction -Message "Error: This config file doesn't exist. Stopping" -EnableException $true -Cmdlet $PSCmdlet
            }
            $Properties = Import-clixml -path $ConfigImportFromFile
            [PSCustomObject]$Properties
        }
        else {
            if ($ComputerName.IsLocalhost) {
                Write-PSFMessage -Message "Looking for the clusterconfig (Cluster Manifest) on the localmachine as no ComputerName provided" -Level Warning 
                if ($(Test-Path "C:\ProgramData\SF\clusterManifest.xml") -eq $False) {
                    Stop-PSFFunction -Message "Error: This is not an Local Business Data server or no config is found (import config if you have to). Stopping" -EnableException $true -Cmdlet $PSCmdlet
                }
                $ClusterManifestXMLFile = get-childitem "C:\ProgramData\SF\clusterManifest.xml" 
            }
            else {
                Write-PSFMessage -Message "Connecting to admin share on $ComputerName for cluster config" -Level Verbose
                if ($(Test-Path "\\$ComputerName\C$\ProgramData\SF\clusterManifest.xml") -eq $False) {
                    Stop-PSFFunction -Message "Error: This is not an Local Business Data server. Can't find Cluster Manifest. Stopping" -EnableException $true -Cmdlet $PSCmdlet
                }
                $ClusterManifestXMLFile = get-childitem "\\$ComputerName\C$\ProgramData\SF\clusterManifest.xml"
            }
            if (!($ClusterManifestXMLFile)) {
                Stop-PSFFunction -Message "Error: This is not an Local Business Data server or the application is not installed. Can't find Cluster Manifest. Stopping" -EnableException $true -Cmdlet $PSCmdlet
            }
            if ($(test-path $ClusterManifestXMLFile) -eq $false) {
                Stop-PSFFunction -Message "Error: This is not an Local Business Data server. Can't find Cluster Manifest. Stopping" -EnableException $true -Cmdlet $PSCmdlet
            }
            Write-PSFMessage -Message "Reading $ClusterManifestXMLFile" -Level Verbose
            [xml]$xml = get-content $ClusterManifestXMLFile

            $OrchestratorServerNames = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'OrchestratorType' }).NodeName
            $AXSFServerNames = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'AOSNodeType' }).NodeName
            $ReportServerServerName = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'ReportServerType' }).NodeName 
            $ReportServerServerip = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'ReportServerType' }).IPAddressOrFQDN

            if (($null -eq $OrchestratorServerNames) -or (!$OrchestratorServerNames)) {
                $OrchestratorServerNames = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'PrimaryNodeType' }).NodeName
                $AXSFServerNames = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'PrimaryNodeType' }).NodeName
                $ReportServerServerName = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'ReportServerType' }).NodeName 
                $ReportServerServerip = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'ReportServerType' }).IPAddressOrFQDN
            }
            foreach ($OrchestratorServerName in $OrchestratorServerNames) {
                if (!$OrchServiceLocalAgentConfigXML) {
                    Write-PSFMessage -Message "Verbose: Connecting to $OrchestratorServerName for Orchestrator config" -Level Verbose
                    $OrchServiceLocalAgentConfigXML = get-childitem "\\$OrchestratorServerName\C$\ProgramData\SF\*\Fabric\work\Applications\LocalAgentType_App*\OrchestrationServicePkg.Package.Current.xml"
                }
                if (!$OrchServiceLocalAgentVersionNumber) {
                    Write-PSFMessage -Message "Verbose: Connecting to $OrchestratorServerName for Orchestrator Local Agent version" -Level Verbose
                    $OrchServiceLocalAgentVersionNumber = $(get-childitem "\\$OrchestratorServerName\C$\ProgramData\SF\*\Fabric\work\Applications\LocalAgentType_App*\OrchestrationServicePkg.Code.*\OrchestrationService.exe").VersionInfo.Fileversion
                }
                If (!$SFVersionNumber) {
                    try {
                        $SFVersionNumber = Invoke-Command -ScriptBlock { Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Service Fabric\' -Name FabricVersion } -ComputerName $OrchestratorServerName
                    }
                    Catch {
                        Write-PSFMessage -Message  "Warning: Can't get Service Fabric Version" -Level Warning
                    }
                }
            }
            if (!$OrchServiceLocalAgentConfigXML) {
                Stop-PSFFunction -Message "Error: Can't find any Local Agent file on the Orchestrator Node" -EnableException $true -Cmdlet $PSCmdlet
            }
            Write-PSFMessage -Message "Reading $OrchServiceLocalAgentConfigXML" -Level Verbose
            [xml]$xml = get-content $OrchServiceLocalAgentConfigXML

            $RetrievedXMLData = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -eq 'AAD' } 
            $LocalAgentCertificate = ($RetrievedXMLData.Parameter | Where-Object { $_.Name -eq "ServicePrincipalThumbprint" }).value

            $RetrievedXMLData = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -eq 'Data' } 
            $OrchDBConnectionString = $RetrievedXMLData.Parameter
    
            $RetrievedXMLData = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -eq 'Download' } 
            $downloadfolderLocation = $RetrievedXMLData.Parameter
    
            $RetrievedXMLData = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -eq 'ServiceFabric' } 
            $ServiceFabricConnectionDetails = $RetrievedXMLData.Parameter

            $ClientCert = $($ServiceFabricConnectionDetails | Where-Object { $_.Name -eq "ClientCertificate" }).value
            $ClusterID = $($ServiceFabricConnectionDetails | Where-Object { $_.Name -eq "ClusterID" }).value
            $ConnectionEndpoint = $($ServiceFabricConnectionDetails | Where-Object { $_.Name -eq "ConnectionEndpoint" }).value
            $ServerCertificate = $($ServiceFabricConnectionDetails | Where-Object { $_.Name -eq "ServerCertificate" }).value
    
            ## With Orch Server config get more details for automation
            [int]$count = 1
            $AXSFConfigServerName = $AXSFServerNames | Select-Object -First $count
            Write-PSFMessage -Message "Verbose: Reaching out to $AXSFConfigServerName for AX config" -Level Verbose
            
            $SFConfig = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Package.Current.xml"
            if (!$SFConfig) {
                $SFConfig = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Package.1.0.xml"
            }
            if (!$SFConfig) {
                do {
                    $AXSFConfigServerName = $AXSFServerNames | Select-Object -First 1 -Skip $count
                    Write-PSFMessage -Message "Verbose: Reaching out to $AXSFConfigServerName for AX config total servers $($AXSFServerNames.Count))" -Level Verbose
                    $SFConfig = get-childitem  "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Package.Current.xml"
                    if (!$SFConfig) {
                        $SFConfig = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Package.1.0.xml"
                    }
                    $count = $count + 1
                    Write-PSFMessage -Message "Count of servers tried $count" -Verbose
                } until ($SFConfig -or ($count -eq $AXSFServerNames.Count))
            } 
            
            if (!$SFConfig) {
                Write-PSFMessage -Message "Verbose: Can't find AX SF. App may not be installed. All values won't be grabbed" -Level Warning
            }
            else {
                [xml]$xml = get-content $SFConfig 

                $DataAccess = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -EQ 'DataAccess' }
                $AXDatabaseName = $($DataAccess.Parameter | Where-Object { $_.Name -eq 'Database' }).value
                $AXDatabaseServer = $($DataAccess.Parameter | Where-Object { $_.Name -eq 'DbServer' }).value
                $DataEncryptionCertificate = $($DataAccess.Parameter | Where-Object { $_.Name -eq 'DataEncryptionCertificateThumbprint' }).value
                $DataSigningCertificate = $($DataAccess.Parameter | Where-Object { $_.Name -eq 'DataSigningCertificateThumbprint' }).value

                $AAD = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -EQ 'Aad' }
                $ClientURL = $($AAD.Parameter | Where-Object { $_.Name -eq 'AADValidAudience' }).value + "namespaces/AXSF/"

                $Infrastructure = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -EQ 'Infrastructure' }
                $SessionAuthenticationCertificate = $($Infrastructure.Parameter | Where-Object { $_.Name -eq 'SessionAuthenticationCertificateThumbprint' }).value

                $SMBStorage = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -EQ 'SmbStorage' }
                $SharedAccessSMBCertificate = $($SMBStorage.Parameter | Where-Object { $_.Name -eq 'SharedAccessThumbprint' }).value
       
                $sb = New-Object System.Data.Common.DbConnectionStringBuilder
                $sb.set_ConnectionString($($OrchDBConnectionString.Value))
                $OrchDatabase = $sb.'initial catalog'
                $OrchdatabaseServer = $sb.'data source'
            }

            $AgentShareLocation = $downloadfolderLocation.Value
            $AgentShareWPConfigJson = Get-ChildItem "$AgentShareLocation\wp\*\StandaloneSetup-*\config.json" | Sort-Object { $_.CreationTime } | Select-Object -First 1

            if ($AgentShareWPConfigJson) {
                $jsonconfig = get-content $AgentShareWPConfigJson
                $LCSEnvironmentId = $($jsonconfig | ConvertFrom-Json).environmentid
                $TenantID = $($jsonconfig | ConvertFrom-Json).tenantid
                $LCSEnvironmentName = $($jsonconfig | ConvertFrom-Json).environmentName
            }
            else {
                Write-PSFMessage -Message "Warning: Can't Find Config in WP folder can't get Environment ID or TenantID. All values won't be grabbed" -Level Warning
                $LCSEnvironmentId = ""
                $TenantID = ""
                $LCSEnvironmentName = ""
            }
            try {
                $reportconfig = Get-ChildItem "\\$ReportServerServerName\C$\ProgramData\SF\*\Fabric\work\Applications\ReportingService_*\ReportingBootstrapperPkg.Package.current.xml"
                [xml]$xml = Get-Content $reportconfig.FullName
                $Reportingconfigdetails = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -EQ 'ReportingServices' }
                $ReportingSSRSCertificate = ($Reportingconfigdetails.parameter | Where-Object { $_.Name -eq "ReportingClientCertificateThumbprint" }).value
            }
            catch {
                try {
                    $reportconfig = Get-ChildItem "\\$ReportServerServerName\C$\ProgramData\SF\*\Fabric\work\Applications\ReportingService_*\ReportingBootstrapperPkg.Package.1.0.xml"
                    [xml]$xml = Get-Content $reportconfig.FullName
                    $Reportingconfigdetails = $xml.ServicePackage.DigestedConfigPackage.ConfigOverride.Settings.Section | Where-Object { $_.Name -EQ 'ReportingServices' }
                    $ReportingSSRSCertificate = ($Reportingconfigdetails.parameter | Where-Object { $_.Name -eq "ReportingClientCertificateThumbprint" }).value
                }
                catch {
                    Write-PSFMessage -Level Warning -Message "Warning: Can't gather information from the Reporting Server $ReportServerServerName"
                }
            }
            $CustomModuleVersion = ''
            if (($CustomModuleName)) {
                try {
                    $CustomModuleDll = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Code*\Packages\$CustomModuleName\bin\Dynamics.AX.$CustomModuleName.dll"
                    if (-not (Test-Path $CustomModuleDll)) {
                        Write-PSFMessage -Message "Warning: Custom Module not found; version unable to be found" -Level Warning
                    }
                    else {
                        $CustomModuleVersion = $CustomModuleDll.VersionInfo.FileVersion
                    }
                }
                catch {}
            }
            $AXServiceConfigXMLFile = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Code*\AXService.exe.config" | Sort-Object { $_.CreationTime } | Select-Object -First 1
            Write-PSFMessage -Message "Reading $AXServiceConfigXMLFile" -Level Verbose 
            if (!$AXServiceConfigXMLFile) {
                Write-PSFMessage -Message "Warning: AXSF doesnt seem installed; config cannot be found" -Level Warning
            }
            else {
                [xml]$AXServiceConfigXML = get-content $AXServiceConfigXMLFile
            }
            $AOSKerneldll = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Code*\bin\AOSKernel.dll"
            $AOSKernelVersion = $AOSKerneldll.VersionInfo.ProductVersion

            $jsonClusterConfig = get-content "\\$AXSFConfigServerName\C$\ProgramData\SF\clusterconfig.json"
            $SFClusterCertificate = ($jsonClusterConfig | ConvertFrom-Json).properties.security.certificateinformation.clustercertificate.Thumbprint
            $FinancialReportingCertificate = $($AXServiceConfigXML.configuration.claimIssuerRestrictions.issuerrestrictions.add | Where-Object { $_.alloweduserids -eq "FRServiceUser" }).name
           
            if (test-path \\$ComputerName\c$\ProgramData\SF\DataEnciphermentCert.txt) {
                Write-PSFMessage -Level Verbose -Message "Found DataEncipherment config"
                $DataEnciphermentCertificate = Get-Content \\$ComputerName\c$\ProgramData\SF\DataEnciphermentCert.txt
            }
            else {
                Write-PSFMessage -Level Warning -Message "Warning: No Encipherment Cert found run the function use Add-D365LBDDataEnciphermentCertConfig to add"
            }

            if (test-path \\$ComputerName\c$\ProgramData\SF\DatabaseDetailsandCert.txt) {
                $DatabaseDetailsandCertConfig = Get-Content \\$ComputerName\c$\ProgramData\SF\DatabaseDetailsandCert.txt
                Write-PSFMessage -Level Verbose -Message "Found DatabaseDetailsandCert config additional details added to config data"
                $DatabaseEncryptionCertificate = $DatabaseDetailsandCertConfig[1]
                $DatabaseClusteredStatus = $DatabaseDetailsandCertConfig[0]
                $DatabaseClusterServerNames = $DatabaseDetailsandCertConfig[2]
            }
            else {
                Write-PSFMessage -Level Warning -Message "Warning: No additional Database config Details found use Add-D365LBDDatabaseDetailsandCert to add"
            }
            ##checking for after deployment added servers
            try {
                $currentclustermanifestxmlfile = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\clustermanifest.current.xml" | Sort-Object { $_.CreationTime } | Select-Object -First 1
                [xml]$currentclustermanifestxml = Get-Content $currentclustermanifestxmlfile
                $AXSFServerListToCompare = $currentclustermanifestxml.clusterManifest.Infrastructure.NodeList.Node | Where-Object { $_.NodeTypeRef -eq 'AOSNodeType' -or $_.NodeTypeRef -eq 'PrimaryNodeType' }
                foreach ($Node in $AXSFServerListToCompare) {
                    if (($AXSFServerNames -contains $Node) -eq $false) {
                        $AXSFServerNames += $Node
                    }
                }
            }
            catch {
                Write-PSFMessage -Level Warning -Message "Warning: $_"
            }
            if ($HighLevelOnly) {
                Write-PSFMessage -Level Verbose -Message "High Level Only will not connect to service fabric"
            }
            else {
                try {
                    Write-PSFMessage -Message "Trying to connect to $ConnectionEndpoint using $ServerCertificate" -Level Verbose
                    $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                    $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $ConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My
                    $nodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "PrimaryNodeType") } 
                    Write-PSFMessage -message "Service Fabric connected. Grabbing nodes to validate status" -Level Verbose
                    $appservers = $nodes.NodeName | Sort-Object
                    $invalidsfnodes = get-servicefabricnode | Where-Object { ($_.NodeStatus -eq "Invalid") } 
                    $disabledsfnodes = get-servicefabricnode | Where-Object { ($_.NodeStatus -eq "Disabled") } 
                    $invalidnodes = $invalidsfnodes.NodeName | Sort-Object
                    $disablednodes = $disabledsfnodes.NodeName | Sort-Object
                    $invalidnodescount = $invalidnodes.count
                    if (!$invalidnodes -and $invalidnodescount -ne 0 ) {
                        Write-PSFMessage -Level Warning -Message "Warning: Invalid Node found. Suggest running Update-ServiceFabricD365ClusterConfig to help fix. $invalidnodes"
                    }
                }
                catch {
                    Write-PSFMessage -message "Can't connect to Service Fabric $_" -Level Verbose
                }
                $AXSFServersViaServiceFabricNodes = @()
                foreach ($NodeName in $appservers) {
                    $AXSFServersViaServiceFabricNodes += $NodeName  
                }
            
                $NewlyAddedAXSFServers = @()
                foreach ($Node in $AXSFServersViaServiceFabricNodes) {
                    if (($AXSFServerNames -contains $Node) -eq $false) {
                        Write-PSFMessage -Level Verbose -Message "Adding $Node to AXSFServerList "
                        $AXSFServerNames += $Node
                        $NewlyAddedAXSFServers += $Node
                    }
                }

                [System.Collections.ArrayList]$AXSFActiveNodeList = $AXSFServerNames
                [System.Collections.ArrayList]$AXOrchActiveNodeList = $OrchestratorServerNames
                foreach ($Node in $invalidnodes) {
                    if (($AXSFServerNames -contains $Node) -eq $true) {
                        foreach ($AXSFNode in $AXSFServerNames) {
                            Write-PSFMessage -Level Verbose -Message "Found the Invalid SF Node $Node in AXSFServerList. Removing from list. Use Update-ServiceFabricD365ClusterConfig to get a headstart on fixing. "
                            $AXSFActiveNodeList.Remove($node)
                        }
                    }
                    if (($OrchestratorServerNames -contains $Node) -eq $true) {
                        foreach ($AXSFNode in $OrchestratorServerNames) {
                            Write-PSFMessage -Level Verbose -Message "Found the Invalid Orchestrator Node $Node in OrchestratorServerNames. Removing from OrchestratorServerNames list"
                            $AXOrchActiveNodeList.Remove($node)
                        }
                    }
                }
                $AXSFServerNames = $AXSFActiveNodeList
                $OrchestratorServerNames = $AXOrchActiveNodeList
            }
            $AllAppServerList = @()
            foreach ($ComputerName in $AXSFServerNames) {
                if (($AllAppServerList -contains $ComputerName) -eq $false) {
                    $AllAppServerList += $ComputerName
                }
            }
            foreach ($ComputerName in $ReportServerServerName) {
                if (($AllAppServerList -contains $ComputerName) -eq $false) {
                    $AllAppServerList += $ComputerName
                }
            }
            foreach ($ComputerName in $OrchestratorServerNames) {
                if (($AllAppServerList -contains $ComputerName) -eq $false) {
                    $AllAppServerList += $ComputerName
                }
            }
            ##
            
            # Collect information into a hashtable Add any new field to Get-D365TestConfigData
            # Make sure to add Certification to Cert list below properties if adding cert
            $Properties = @{
                "AllAppServerList"                   = $AllAppServerList
                "OrchestratorServerNames"            = $OrchestratorServerNames
                "AXSFServerNames"                    = $AXSFServerNames
                "ReportServerServerName"             = $ReportServerServerName
                "ReportServerServerip"               = $ReportServerServerip
                "OrchDatabaseName"                   = $OrchDatabase
                "OrchDatabaseServer"                 = $OrchdatabaseServer
                "AgentShareLocation"                 = $AgentShareLocation
                "SFClientCertificate"                = $ClientCert
                "SFClusterID"                        = $ClusterID
                "SFConnectionEndpoint"               = $ConnectionEndpoint
                "SFServerCertificate"                = $ServerCertificate
                "SFClusterCertificate"               = $SFClusterCertificate
                "ClientURL"                          = $ClientURL
                "AXDatabaseServer"                   = $AXDatabaseServer
                "AXDatabaseName"                     = $AXDatabaseName
                "LCSEnvironmentID"                   = $LCSEnvironmentId
                "LCSEnvironmentName"                 = $LCSEnvironmentName
                "TenantID"                           = $TenantID
                "SourceComputerName"                 = $ComputerName
                "CustomModuleVersion"                = $CustomModuleVersion
                "DataEncryptionCertificate"          = $DataEncryptionCertificate 
                "DataSigningCertificate"             = $DataSigningCertificate
                "SessionAuthenticationCertificate"   = $SessionAuthenticationCertificate
                "SharedAccessSMBCertificate"         = $SharedAccessSMBCertificate
                "LocalAgentCertificate"              = $LocalAgentCertificate
                "DataEnciphermentCertificate"        = "$DataEnciphermentCertificate"
                "FinancialReportingCertificate"      = $FinancialReportingCertificate
                "ReportingSSRSCertificate"           = "$ReportingSSRSCertificate"
                "OrchServiceLocalAgentVersionNumber" = $OrchServiceLocalAgentVersionNumber
                "NewlyAddedAXSFServers"              = $NewlyAddedAXSFServers
                'SFVersionNumber'                    = $SFVersionNumber
                'InvalidSFServers'                   = $invalidnodes
                'DisabledSFServers'                  = $disablednodes
                'AOSKernelVersion'                   = $AOSKernelVersion
                'DatabaseEncryptionCertificate'      = $DatabaseEncryptionCertificate 
                'DatabaseClusteredStatus'            = $DatabaseClusteredStatus
                'DatabaseClusterServerNames'         = $DatabaseClusterServerNames
            }
            $certlist = ('SFClientCertificate', 'SFServerCertificate', 'DataEncryptionCertificate', 'DataSigningCertificate', 'SessionAuthenticationCertificate', 'SharedAccessSMBCertificate', 'LocalAgentCertificate', 'DataEnciphermentCertificate', 'FinancialReportingCertificate', 'ReportingSSRSCertificate', 'DatabaseEncryptionCertificate')
            $CertificateExpirationHash = @{}
            if ($HighLevelOnly) {
                Write-PSFMessage -Level Verbose -Message "High Level Only will not connect to service fabric"
            }
            else {
                foreach ($cert in  $certlist) {
                    $certthumbprint = $null 
                    $certthumbprint = $Properties.$cert
                    $certexpiration = $null
                    if ($certthumbprint) {
                        $value = $certthumbprint
                        try {
                            if ($cert -eq 'LocalAgentCertificate' -and !$certexpiration) {
                                $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\LocalMachine\my | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $OrchestratorServerName -ArgumentList $value
                                if (!$certexpiration) {
                                    $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\CurrentUser\my | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $OrchestratorServerName -ArgumentList $value
                                }
                            } if (!$certexpiration) {
                                $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\LocalMachine\my | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $AXSFConfigServerName -ArgumentList $value
                            }
                            if (!$certexpiration) {
                                $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\CurrentUser\my | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $AXSFConfigServerName -ArgumentList $value
                            }
                            if (!$certexpiration) {
                                $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\LocalMachine\Trust | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $AXSFConfigServerName -ArgumentList $value
                            }
                            if ($cert -eq 'DatabaseEncryptionCertificate' -and !$certexpiration) {
                                $DatabaseClusterServerName = $DatabaseClusterServerNames | Select-Object -First 1
                                try {
                                    $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\LocalMachine\my | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $DatabaseClusterServerName -ArgumentList $value -ErrorAction Stop
                                    if (!$certexpiration) {
                                        $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\CurrentUser\my | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $DatabaseClusterServerName -ArgumentList $value -ErrorAction Stop
                                    }
                                }
                                catch {
                                    Write-PSFMessage -Level Warning "Warning: Issue grabbing DatabaseEncryptionCertificate information. $_"
                                }

                            }
                            if ($certexpiration) {
                                Write-PSFMessage -Level Verbose -Message "$value expires at $certexpiration"
                            }
                            else {
                                Write-PSFMessage -Level Verbose -Message "Could not find Certificate $cert $value"
                            }
                        }
                        catch {
                            Write-PSFMessage -Level Warning -Message "$value $_ cant be found"
                        }
                    }
                    $name = $cert + "ExpiresAfter"
                
                    $currdate = get-date
                    if ($currdate -gt $certexpiration -and $certexpiration) {
                        Write-PSFMessage -Level Warning -Message "WARNING: Expired Certificate $name with an expiration of $certexpiration"
                    }
                    $hash = $CertificateExpirationHash.Add($name, $certexpiration)
                }
            }
            Function Merge-Hashtables([ScriptBlock]$Operator) {
                ##probably will put in internal to test
                $Output = @{}
                ForEach ($Hashtable in $Input) {
                    If ($Hashtable -is [Hashtable]) {
                        ForEach ($Key in $Hashtable.Keys) { $Output.$Key = If ($Output.ContainsKey($Key)) { @($Output.$Key) + $Hashtable.$Key } Else { $Hashtable.$Key } }
                    }
                }
                If ($Operator) { ForEach ($Key in @($Output.Keys)) { $_ = @($Output.$Key); $Output.$Key = Invoke-Command $Operator } }
                $Output
            }
            $FinalOutput = $CertificateExpirationHash, $Properties | Merge-Hashtables
            #$FinalOutput = $Properties, $CertificateExpirationHash
            ##Sends Custom Object to Pipeline
            [PSCustomObject] $FinalOutput
        }
    }
    END {
        if ($ConfigExportToFile) {
            $FinalOutput | Export-Clixml -Path $ConfigExportToFile
        }
    }
}

function Get-D365LBDDBEvents {
    [CmdletBinding()]
    [alias("Get-D365DBEvents")]
    param ([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [int]$NumberofEvents = 20,
        [psobject]$Config
    )
    if (!$Config) {
        $Config = Get-D365LBDConfig -ComputerName $ComputerName 
    }
    
    Foreach ($AXSFServerName in $config.AXSFServerNames) {
        try {
            $LatestEventinLog = $(Get-WinEvent -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -maxevents 1 -computername $AXSFServerName -ErrorAction Stop).TimeCreated
        }
        catch {
            Write-PSFMessage -Level VeryVerbose -Message "$AXSFServerName $_"
            if ($_.Exception.Message -eq "No events were found that match the specified selection criteria") {
                $LatestEventinLog = $null
            }
            if ($_.Exception.Message -eq "The RPC Server is unavailable") {
                {           
                    Write-PSFMessage -Level Verbose -Message "The RPC Server is Unavailable trying WinRM"       
                    $LatestEventinLog = Invoke-Command -ComputerName $AXSFServerName -ScriptBlock { $(Get-EventLog -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -maxevents 1 -computername $AXSFServerName).TimeCreated }
                }
            }
        }
        if (($LatestEventinLog -gt $LatestEventinAllLogs) -or (!$LatestEventinAllLogs)) {
            $LatestEventinAllLogs = $LatestEventinLog
            $ServerWithLatestLog = $AXSFServerName 
            Write-PSFMessage -Level Verbose -Message "Server with latest log updated to $ServerWithLatestLog with a date time of $LatestEventinLog"
        }
    }
    Write-PSFMessage -Level VeryVerbose -Message "Gathering from $ServerWithLatestLog"
    $events = Get-WinEvent -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -maxevents $NumberofEvents -computername $ServerWithLatestLog | 
    ForEach-Object -Process { `
            New-Object -TypeName PSObject -Property `
        @{'MachineName'        = $ServerWithLatestLog ;
            'EventMessage'     = $_.Properties[0].value;
            'EventDetails'     = $_.Properties[1].value; 
            'Message'          = $_.Message;
            'LevelDisplayName' = $_.LevelDisplayName;
            'TimeCreated'      = $_.TimeCreated;
            'TaskDisplayName'  = $_.TaskDisplayName
            'UserId'           = $_.UserId;
            'LogName'          = $_.LogName;
            'ProcessId'        = $_.ProcessId;
            'ThreadId'         = $_.ThreadId;
            'Id'               = $_.Id;
        }
     
        ##if ($events.Message -eq 'Database Synchronize Succeeded.')
    }
    $events
}

function Get-D365LBDOrchestrationLogs {
    [alias("Get-D365OrchestrationLogs")]
    param (
        [string]$ComputerName,
        [string]$ActiveSecondary,
        [int]$NumberofEvents = 5,
        [psobject]$Config
    )
    if (!$Config) {
        $Config = Get-D365LBDConfig -ComputerName $ComputerName 
    }
    
    $LatestEventInLog = $(Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents 1 -ComputerName $ComputerName).TimeCreated
    $primary = Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents $NumberofEvents -ComputerName $ComputerName | 
    ForEach-Object -Process { `
            New-Object -TypeName PSObject -Property `
        @{'MachineName'        = $_.Properties[0].value;
            'EventMessage'     = $_.Properties[1].value;
            'EventDetails'     = $_.Properties[2].value; 
            'Message'          = $_.Message;
            'LevelDisplayName' = $_.LevelDisplayName;
            'TimeCreated'      = $_.TimeCreated;
            'UserId'           = $_.UserId;
            'LogName'          = $_.LogName;
            'ProcessId'        = $_.ProcessId;
            'ThreadId'         = $_.ThreadId;
            'Id'               = $_.Id;
            'ReplicaType'      = 'Primary';
            'LatestEventInLog' = $LatestEventInLog;
        }
    }
    $LatestEventInLog = $(Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents 1 -ComputerName $ActiveSecondary).TimeCreated
    $secondary = Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents $NumberofEvents -ComputerName $ActiveSecondary | 
    ForEach-Object -Process { `
            New-Object -TypeName PSObject -Property `
        @{'MachineName'        = $_.Properties[0].value;
            'EventMessage'     = $_.Properties[1].value;
            'EventDetails'     = $_.Properties[2].value; 
            'Message'          = $_.Message;
            'LevelDisplayName' = $_.LevelDisplayName;
            'TimeCreated'      = $_.TimeCreated;
            'UserId'           = $_.UserId;
            'LogName'          = $_.LogName;
            'ProcessId'        = $_.ProcessId;
            'ThreadId'         = $_.ThreadId;
            'Id'               = $_.Id;
            'ReplicaType'      = 'ActiveSecondary';
            'LatestEventInLog' = $LatestEventInLog;
        }
    }
    $all = $Primary + $secondary | Sort-Object { $_.TimeCreated } -Descending | Select-Object -First $NumberofEvents
    return $all
}

##Get Primary and Secondary
function Get-D365LBDOrchestrationNodes {
    [alias("Get-D365OrchestrationNodes")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [string]$Thumbprint,
        [psobject]$Config)

    if (!$Config) {
        $Config = Get-D365LBDConfig -ComputerName $ComputerName 
    }

    try {
        $connection = Connect-ServiceFabricCluster -connectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $Config.SFServerCertificate -ServerCertThumbprint $Config.SFServerCertificate | Out-Null
    }
    catch {
        Stop-PSFFunction -Message "Can't Connect to Service Fabric $_" -EnableException $true -Cmdlet $PSCmdlet -ErrorAction Stop
    }
    $PartitionId = $(Get-ServiceFabricServiceHealth -ServiceName 'fabric:/LocalAgent/OrchestrationService').PartitionHealthStates.PartitionId
    $nodes = Get-ServiceFabricReplica -PartitionId "$PartitionId"
    $primary = $nodes | Where-Object { $_.ReplicaRole -eq "Primary" }
    $secondary = $nodes | Where-Object { $_.ReplicaType -eq "ActiveSecondary" }
    New-Object -TypeName PSObject -Property `
    @{'PrimaryNodeName'                              = $primary.NodeName;
        'SecondaryNodeName'                          = $secondary.NodeName;
        'PrimaryReplicaStatus'                       = $primary.Properties[2].value; 
        'SecondaryReplicaStatus'                     = $secondary.Message;
        'PrimaryLastInBuildStatusLevelDisplayName'   = $primary.LevelDisplayName;
        'SecondaryLastInBuildStatusLevelDisplayName' = $secondary.TimeCreated;
        'PrimaryHealthState'                         = $primary.UserId;
        'SecondaryHealthState'                       = $secondary.LogName;
        'PartitionId'                                = $PartitionId;
    }
}

function Get-D365LBDTestConfigData {
    <#
    .SYNOPSIS
   Made to test D365 Config functions without a test environment
   #>

    [alias("Get-D365TestConfigData")]
    [CmdletBinding()]
    param(        
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    }
    PROCESS {
        # Collect information into a hashtable
        $Properties = @{
            "AllAppServerList"                             = ('Server1', 'Server2', 'Server3', 'Server4', 'Server5')
            "OrchestratorServerNames"                      = ('Server1', 'Server2')
            "AXSFServerNames"                              = ('Server3', 'Server4', 'Server5')
            "ReportServerServerName"                       = 'Server5'
            "ReportServerServerip"                         = '1.1.1.1'
            "OrchDatabaseName"                             = 'Orchestrator'
            "OrchDatabaseServer"                           = 'OrchestratorDBServer'
            "AgentShareLocation"                           = '\\fileshare\share\agent'
            "SFClientCertificate"                          = 'A233E'
            "SFClusterID"                                  = 'D365SFCluster'
            "SFConnectionEndpoint"                         = '1.2.3.4:19000'
            "SFServerCertificate"                          = 'B12131233E'
            "SFClusterCertificate"                         = 'C12313233E'
            "ClientURL"                                    = 'https://ax.offandonit.com/namespaces/AXSF/'
            "AXDatabaseServer"                             = 'AXDBServer'
            "AXDatabaseName"                               = 'AXDB'
            "LCSEnvironmentID"                             = 'LCSEnvironmentID'
            "LCSEnvironmentName"                           = 'LCSEnvironmentID'
            "TenantID"                                     = '123912084123-123d0-1232-11234123'
            "SourceComputerName"                           = 'D365ManagementServer'
            "CustomModuleVersion"                          = '2020.1.28.1'
            "DataEncryptionCertificate"                    = 'E1231233E'
            "DataSigningCertificate"                       = 'F1231233E'
            "SessionAuthenticationCertificate"             = 'G1233123233E'
            "SharedAccessSMBCertificate"                   = 'H12331233E'
            "LocalAgentCertificate"                        = 'I2134213233E'
            "DataEnciphermentCertificate"                  = 'J12312233E'
            "FinancialReportingCertificate"                = 'K123113233E'
            "ReportingSSRSCertificate"                     = 'LASDSA233E'
            "OrchServiceLocalAgentVersionNumber"           = '2.3.0.0'
            "NewlyAddedAXSFServers"                        = 'Server4'
            'SFVersionNumber'                              = '7.1.465.9590'
            'InvalidSFServers'                             = 'Server5'
            'DisabledSFServers'                            = 'Server4'
            'AOSKernelVersion'                             = '7.0.6969.42069'
            'DatabaseEncryptionCertificate'                = 'ASES123113233E'
            'DatabaseClusteredStatus'                      = 'Clustered'
            'DatabaseClusterServerNames'                   = ('DatabaseServer1', 'DatabaseServer2')
            'SFClientCertificateExpiresAfter'              = '5/15/2022 8:24:06 PM'
            'SFServerCertificateExpiresAfter'              = '5/15/2022 8:24:06 PM'
            'DataEncryptionCertificateExpiresAfter'        = '5/15/2022 8:24:06 PM'
            'DataSigningCertificateExpiresAfter'           = '5/15/2022 8:24:06 PM'
            'SessionAuthenticationCertificateExpiresAfter' = '5/15/2022 8:24:06 PM'
            'SharedAccessSMBCertificateExpiresAfter'       = '5/15/2022 8:24:06 PM'
            'LocalAgentCertificateExpiresAfter'            = '5/15/2022 8:24:06 PM'
            'DataEnciphermentCertificateExpiresAfter'      = '5/15/2022 8:24:06 PM'
            'FinancialReportingCertificateExpiresAfter'    = '5/15/2022 8:24:06 PM'
            'ReportingSSRSCertificateExpiresAfter'         = '5/15/2022 8:24:06 PM'
            'DatabaseEncryptionCertificateExpiresAfter'    = '5/15/2022 8:24:06 PM'
        }
        ##Sends Custom Object to Pipeline
        [PSCustomObject]$Properties
    }

    END {
    }
}

function Import-D365LBDCertificates {
 <#
   .SYNOPSIS
  Looks inside the agent share extracts the version from the zip by using the custom module name. Puts an xml in root for easy idenitification
  .DESCRIPTION
   Exports
  .EXAMPLE
  Import-D365Certificates
 
  .EXAMPLE
   Import-D365Certificates
 
  .PARAMETER AgentShare
  optional string
   The location of the Agent Share
  .PARAMETER CustomModuleName
  optional string
  The name of the custom module you will be using to capture the version number
 
  #>

  [alias("Import-D365Certificates")]
    param
    (
        [Parameter(Mandatory = $false)]
        [string]$CertThumbprint,
        [Parameter(Mandatory = $false)]
        [string]$CertFolder,
        [switch]$Exportable

    )
    ##Import do to.. bythumbprint
    $certs = get-childitem "$CertFolder"
    foreach ($cert in $certs) {
        if ($Exportable){
            Import-PfxCertificate $cert.FullName -CertStoreLocation "Cert:\localmachine\my" -Exportable 
        }
        else {
            Import-PfxCertificate $cert.FullName -CertStoreLocation "Cert:\localmachine\my"
        }
        
    }
}

function New-D365LBDAXSFNode {
    <#
    .SYNOPSIS
   Can only be ran on the local machine not fully functional need to add fd and ud logic right now its just parameter
   #>

    [alias("New-D365AXSFNode")]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [string]$SFConnectionEndpoint,
        [Parameter(Mandatory = $true)]
        [string]$FaultDomain,
        [string]$UpdateDomain,
        [string]$SFClusterCertificate,
        [string]$SFClientCertificate,
        [string]$ServiceFabricInstallPath
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    }
    PROCESS {
        Write-PSFMessage -Message "Make sure pre reqs are installed including certificates" -Level Verbose
        $ipaddress = (Get-NetIPAddress | Where-Object { ($_.AddressFamily -eq "IPv4") -and ($_.IPAddress -ne "127.0.0.1") }).IPAddress
        Set-Location "$ServiceFabricInstallPath"
        .\AddNode.ps1 -NodeName $env:COMPUTERNAME -NodeType AOSNodeType -NodeIPAddressorFQDN $ipaddress -ExistingClientConnectionEndpoint $SFConnectionEndpoint  -UpgradeDomain $UpdateDomain -FaultDomain $FaultDomain -AcceptEULA -X509Credential -ServerCertThumbprint $SFClusterCertificate -StoreLocation LocalMachine -StoreName My -FindValueThumbprint $SFClientCertificate
        Write-PSFMessage -Level Warning -Message "Remember to run a cluster configuration update after all nodes are added (and during a change downtime). Use Update-ServiceFabricD365ClusterConfig to help. "
    }
}


function Remove-D365LBDStuckApps {##created for deployment bug when it cant clean properly
    [alias("Remove-D365StuckApps")]
    param (
        [string]$SFServerCertificate,
        [string]$SFConnectionEndpoint,
        [string]$AgentShareLocation,
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME"
    )
    if (!$Config) {
        $Config = Get-D365LBDConfig -ComputerName $ComputerName 
    }
    

    if (-not $($config.TenantID)) {
        $cachedconfigfile = Join-path $($config.AgentShareLocation) -ChildPath "scripts\config.xml" 
        $config = Get-D365LBDConfig -ConfigImportFromFile $cachedconfigfile
    }

    Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate

    $environmentwp = get-childitem $(Join-path $config.AgentShareLocation -ChildPath "\wp")
    $archivefolder = $(Join-path $config.AgentShareLocation -ChildPath "\archive")
    if ((Test-Path $archivefolder) -eq $false) {
        Write-PSFMessage -Message "Creating archive folder" -Level Verbose
        mkdir $archivefolder
    }
    else {
        Write-PSFMessage -Message "Archive folder already exists" -Level Verbose
        Get-ChildItem $environmentwp.FullName -Recurse | Remove-Item 
    }
    Move-Item -Path $environmentwp.FullName -Destination $archivefolder -Force -Verbose
    Write-PSFMessage -Message "Deleting applications" -Level Verbose

    $applicationNamesToIgnore = @('fabric:/LocalAgent', 'fabric:/Agent-Monitoring', 'fabric:/Agent-LBDTelemetry')
    $applicationTypeNamesToIgnore = @('MonitoringAgentAppType-Agent', 'LocalAgentType', 'LBDTelemetryType-Agent')
 
    Get-ServiceFabricApplication | `
        Where-Object { $_.ApplicationName -notin $applicationNamesToIgnore } | `
        Remove-ServiceFabricApplication -Force
 
    Get-ServiceFabricApplicationType | `
        Where-Object { $_.ApplicationTypeName -notin $applicationTypeNamesToIgnore } | `
        Unregister-ServiceFabricApplicationType -Force
    
    Write-PSFMessage -Level Verbose -Message "Trigger deployment/retry in LCS"
}

function Start-D365LBDDBSync {
    <#
    .SYNOPSIS
   Starts a Database Synchronization on a Dynamics 365 Finance and Operations Server
   .DESCRIPTION
   Starts a Database Synchronization on a Dynamics 365 Finance and Operations Server using the "Microsoft.Dynamics.AX.Deployment.Setup.exe" executable
   .EXAMPLE
   Start-D365FOLBDDBSync
    
   .EXAMPLE
    Start-D365FOLBDDBSync
    
   .PARAMETER AXSFServer
   Parameter
   string
   The name of the Local Business Data Computer that is runnign the AXSF role.
   If ignored will use local host.
   .PARAMETER AXDatabaseServer
   Parameter
   string
   The name of the Local Business Data SQL Database Computer
   .PARAMETER AXDatabaseName
   Parameter
   string
   The name of the Local Business Data SQL Database name.
   .PARAMETER SQLUser
   Parameter
   string
   The name of the user to login with SQL authentication
   .PARAMETER SQLUserPassword
   Parameter
   string
   The password of the user to login with SQL authentication
   .PARAMETER Timeout
   Parameter
   int
   The timeout period of the database synchronization
    
   #>

    [alias("Start-D365DBSync", "Start-D365FOLBDDBSync")]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $False)]
        [string]$AXSFServer, ## Remote execution needs to be tested and worked on use localhost until then
        [Parameter(Mandatory = $true)]
        [string]$AXDatabaseServer,
        [Parameter(Mandatory = $true)]
        [string]$AXDatabaseName,
        [Parameter(Mandatory = $true)]
        [string]$SQLUser,
        [Parameter(Mandatory = $true)]
        [string]$SQLUserPassword,
        [int]$Timeout = 60
    )
    
    begin {
    }
    process {
        if (($AXSFServer.IsLocalhost) -or ($AXSFServer -eq $env:COMPUTERNAME) -or ($AXSFServer -eq "$env:COMPUTERNAME.$env:UserDNSDOMAINNAME")) {
            Write-PSFMessage -Message "AXSF is local Server" -Level Verbose
            Write-PSFMessage -Message "Looking for the AX Process to find deployment exe and the packages folder to start the Database Synchronize" -Level Warning 
            $AXSFCodeFolder = Split-Path $(Get-Process | Where-Object { $_.name -eq "AXService" }).Path -Parent
            $AXSFCodePackagesFolder = Join-Path $AXSFCodeFolder "\Packages"
            $AXSFCodeBinFolder = Join-Path $AXSFCodeFolder "\bin"
            $D365DeploymentExe = Get-ChildItem $AXSFCodeBinFolder | Where-Object { $_.Name -eq "Microsoft.Dynamics.AX.Deployment.Setup.exe" }

            $CommandLineArgs = '-metadatadir {0} --bindir {1} --sqlserver {2} --sqldatabase {3} --sqluser {4} --sqlpwd {5} --setupmode sync --syncmode fullall --isazuresql false --verbose true' -f $AXSFCodePackagesFolder, $AXSFCodePackagesFolder, $AXDatabaseServer, $AXDatabaseName, $SQLUser, $SQLUserPassword
            $exelocation = $D365DeploymentExe.FullName
            Write-PSFMessage -Message "$exelocation $CommandLineArgs" -Level Verbose
            $DbSyncProcess = Start-Process -filepath $D365DeploymentExe.FullName -ArgumentList $CommandLineArgs -Verbose -PassThru -OutVariable out

            if ($DbSyncProcess.WaitForExit(60000 * $Timeout) -eq $false) {
                $DbSyncProcess.Kill()
                Stop-PSFFunction -Message "Error: Database Sync failed did not complete within $timeout minutes"  -EnableException $true -Cmdlet $PSCmdlet
            }
            else {
                return $true;
            }
        }
        else {
            Write-PSFMessage -Message "Connecting to admin share on $AXSFServer for cluster config" -Level Verbose
            if ($(Test-Path "\\$AXSFServer\C$\ProgramData\SF\clusterManifest.xml") -eq $false) {
                Stop-PSFFunction -Message "Error: This is not an Local Business Data server. Can't find Cluster Manifest. Stopping" -EnableException $true -Cmdlet $PSCmdlet
            }
            Write-PSFMessage -Message "Not running DB Sync locally due to not AXSF server will trigger via WinRM" -Level Verbose

            $process = Invoke-PSFCommand -ComputerName $AXSFServer -ScriptBlock { 
                Write-PSFMessage -Message "Looking for the AX Process to find deployment exe and the packages folder to start the Database Synchronize" -Level Warning 
                $AXSFCodeFolder = Split-Path $(Get-Process | Where-Object { $_.name -eq "AXService" }).Path -Parent
                $AXSFCodePackagesFolder = Join-Path $AXSFCodeFolder "\Packages"
                $AXSFCodeBinFolder = Join-Path $AXSFCodeFolder "\bin"
                $D365DeploymentExe = Get-ChildItem $AXSFCodeBinFolder | Where-Object { $_.Name -eq "Microsoft.Dynamics.AX.Deployment.Setup.exe" }
    
                ##Props to Microsoft for below technique in next few lines copied/learned from the 2012 deployment scripts https://gallery.technet.microsoft.com/scriptcenter/Build-and-deploy-for-b166c6e4
                $CommandLineArgs = '-metadatadir {0} --bindir {1} --sqlserver {2} --sqldatabase {3} --sqluser {4} --sqlpwd {5} --setupmode sync --syncmode fullall --isazuresql false --verbose true' -f $AXSFCodePackagesFolder, $AXSFCodePackagesFolder, $AXDatabaseServer, $AXDatabaseName, $SQLUser, $SQLUserPassword
                Write-PSFMessage -Level Verbose -Message "$D365DeploymentExe $CommandLineArgs"
                $DbSyncProcess = Start-Process -filepath $D365DeploymentExe.FullName -ArgumentList $CommandLineArgs
    
                if ($DbSyncProcess.WaitForExit(60000 * $Timeout) -eq $false) {
                    $DbSyncProcess.Kill()
                    return $false;
                    Stop-PSFFunction -Message "Error: Database Sync failed did not complete within $timeout minutes"  -EnableException $true -Cmdlet $PSCmdlet
                }
                else {
                    return $true;
                }
            } -Verbose
        }
    }
    end {
    }
}

function Start-D365LBDMonitorDeployment {
    <#
   .SYNOPSIS
  Looks inside the agent share extracts the version from the zip by using the custom module name. Puts an xml in root for easy idenitification
  .DESCRIPTION
   Exports
  .EXAMPLE
    Start-D365LBDMonitorDeployment
 
  .EXAMPLE
   Export-D365FOLBDAssetModuleVersion
 
  .PARAMETER AgentShare
  optional string
   The location of the Agent Share
  .PARAMETER CustomModuleName
  optional string
  The name of the custom module you will be using to capture the version number
 
  #>

    [alias("Start-D365MonitorDeployment")]
    param
    (
        [Parameter(Mandatory = $true)]
        [int]$Timeout
    )
    $propsToCompare = $Primary[0].psobject.properties.name

    $allnow = $Primary + $secondary | Sort-Object { $_.TimeCreated } -Descending | Select-Object -First $NumberofEventsToCheck
 
    if (Compare-Object -ReferenceObject $all -DifferenceObject  $allnow -Property  $propsToCompare) {
        $allnow
    }
    else {
        Write-Host "Nothing New"
    }
}

function Update-ServiceFabricD365ClusterConfig {
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(Mandatory = $false)]
        [psobject]$Config,
        [string]$Workingfolder = "C:\temp"
    )
    <#
   .SYNOPSIS
  todo not working yet
 
  .DESCRIPTION
   Connect-ServiceFabricAutomatic
 
  .EXAMPLE
  Connect-ServiceFabricAutomatic
 
  .EXAMPLE
  Connect-ServiceFabricAutomatic
 
  .PARAMETER Config
  optional custom object generated from Get-D365LBDConfig
  #>

        
    BEGIN {
        if ((!$Config)) {
            Write-PSFMessage -Message "No paramters selected will try and get config" -Level Verbose
            $Config = Get-D365LBDConfig -ComputerName $ComputerName
        }  
    }
    PROCESS {
        $SFNumber = $Config.SFVersionNumber

        [int]$count = 1
        $OrchestratorServerName = $config.OrchestratorServerNames | Select-Object -First $count
        Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName for service Fabric cab file version $SFNumber" -Level Verbose
        
        $SFFolder = get-childitem "\\$OrchestratorServerName\C$\ProgramData\SF\*\Fabric\work\Applications\__FabricSystem_App*\work\Store\*\$SFNumber"
      
        if (!$SFFolder) {
            do {
                $OrchestratorServerName = $config.OrchestratorServerNames | Select-Object -First $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName for service Fabric cab file"  -Level Verbose
                $SFFolder = get-childitem "\\$OrchestratorServerName\C$\ProgramData\SF\*\Fabric\work\Applications\__FabricSystem_App*\work\Store\*\$SFNumber"
                $count = $count ++
                Write-PSFMessage -Message "Count of servers tried $count" -Verbose
            } until ($SFFolder -or ($count -eq $OrchestratorServerNames.Count))
        } 
     
        $SFCab = Get-ChildItem $SFFolder.FullName
        Copy-Item -Path $SFCab.FullName -Destination $Workingfolder\MicrosoftAzureServiceFabric.cab -Verbose
        
        try {
            Write-PSFMessage -Message "Trying to connect to $($config.SFConnectionEndpoint) using $($config.SFServerCertificate)" -Level Verbose
            $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
            $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
            $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.sfServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
            Get-ServiceFabricClusterConfiguration -UseApiVersion -ApiVersion 10-2017 >$Workingfolder\ClusterConfig.json
            Write-PSFMessage -Level Verbose -Message "$Workingfolder\ClusterConfig.json Created Need to modify this JSON then run Start-ServiceFabricClusterConfigrationUpgrade"
            if ($config.InvalidSFServers) {
                Write-PSFMessage -Message "Warning: Suggest removing invalid Node(s) $($config.InvalidSFServers)" -Level Warning
                Write-PSFMessage -Message "Warning: Make sure to remove the ""WindowsIdentities"" $$id 3 area under security (if exists) " -Level Warning
            }

            $JSON = get-content $Workingfolder\ClusterConfig.json -raw | ConvertFrom-Json
            $versiontostring = $JSON.ClusterConfigurationVersion
            $version = [version]$versiontostring
            $versionincremented = [string][version]::new(
                $version.Major,
                $version.Minor,
                $version.Build + 1
            )
            Write-PSFMessage -Level Verbose -Message "Version updated from $versiontostring to $Versionincremented"
            foreach ($invalidnode in $config.InvalidSFServers) {
                $RemoveNodeJSON = @"
{
    "name":"NodesToBeRemoved",
    "value":"$invalidnode"
}
"@

                $JSON.ClusterConfigurationVersion = $versionincremented
                $parameters = $JSON.Properties.FabricSettings.Parameters
                $parametersnew = $parameters + (ConvertFrom-Json $RemoveNodeJSON)
                $JSON.Properties.FabricSettings | Add-Member -type NoteProperty -name "Parameters" -Value $parametersnew -Force
                Write-PSFMessage -Level Verbose -Message "NodesToBeRemoved $invalidnode added to JSON"
            }
            $JSON | ConvertTo-Json -Depth 32 | Set-Content  $Workingfolder\ClusterConfig.json 
            Write-PSFMessage -Level VeryVerbose -Message "$Workingfolder\ClusterConfig.json updated and ready to be used."
        }
        catch {
            Write-PSFMessage -message "Can't Connect to Service Fabric $_" -Level Verbose
        }
    }
    end {

    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'D365FOLBDAdmin' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'D365FOLBDAdmin' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'D365FOLBDAdmin' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'D365FOLBDAdmin.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "D365FOLBDAdmin.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name D365FOLBDAdmin.alcohol
#>


New-PSFLicense -Product 'D365FOLBDAdmin' -Manufacturer 'Stefan' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-11-12") -Text @"
Copyright (c) 2019 Stefan Land
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code