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'

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 {} 
}



<# Source: https://stackoverflow.com/questions/8423541/how-do-you-run-a-sql-server-query-from-powershell
#>

function Invoke-SQL {
    param(
        [string] $dataSource = ".\SQLEXPRESS",
        [string] $database = "MasterData",
        [string] $sqlCommand = $(throw "Please specify a query.")
      )

    $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $connection.Open()
    
    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null
    
    $connection.Close()
    $dataSet.Tables

}

##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 Disable-D365LBDSFAppServers {
    <#
    .SYNOPSIS
    Disables all the D365 application servers inside of service fabric (not orchestrator nodes).
   .DESCRIPTION
   Connects to service fabric then disables all the D365 application servers inside of service fabric (not orchestrator nodes).
   To Enable after disable use the Enable-D365LBDSFAppServers command
   .EXAMPLE
   Disable-D365LBDSFAppServers
  Disables all the application servers on the local machines environment
   .EXAMPLE
    Disable-D365LBDSFAppServers -ComputerName "LBDServerName" -verbose
   Disables all the application servers on the specified servers environment
    .EXAMPLE
    $config = get-d365Config
    Disable-D365LBDSFAppServers -config $Config
   Disables all the application servers on the specified configs environment
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   #>

    [alias("Disable-D365SFAppServers")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [int]$Timeout = 600
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        [int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                }
                Write-PSFMessage -Message "-ConnectionEndpoint $($config.SFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
                $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            } until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count) -eq 0)
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
        }
        $AppNodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType") -or ($_.NodeType -eq "ReportServerType") } 
        $primarynodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "PrimaryNodeType") } 
        if ($primarynodes.count -gt 0) {
            Stop-PSFFunction -Message "Error: Primary Node configuration not supported with enable or disable due to architectural issues. Restart-D365LBDSFAppServers is what is recommended." -EnableException $true -FunctionName $_
        }
        foreach ($AppNode in $AppNodes) {
            Disable-ServiceFabricNode -NodeName $AppNode.NodeName -Intent RemoveData -force -timeoutsec 30
        }
        Start-Sleep -Seconds 1
        [int]$timeoutondisablecounter = 0
        $nodestatus = Get-serviceFabricNode | Where-Object { $_.NodeStatus -eq 'Disabling' -and ($_.NodeType -eq "AOSNodeType") }
        do {     
            $nodestatus = Get-serviceFabricNode | Where-Object { $_.NodeStatus -eq 'Disabling' -and ($_.NodeType -eq "AOSNodeType") } 
            $timeoutondisablecounter = $timeoutondisablecounter + 5
            Start-Sleep -Seconds 5
        } until (!$nodestatus -or $nodestatus -eq 0 -or ($timeoutondisablecounter -gt $Timeout))
        Write-PSFMessage -Message "All App Nodes Disabled" -Level VeryVerbose
    }
    END {}
}

function Enable-D365LBDSFAppServers {
    <#
      .SYNOPSIS
  Enables all the D365 application servers inside of service fabric (not orchestrator nodes)
   .DESCRIPTION
   Connects to service fabric then enables all the D365 application servers inside of service fabric (not orchestrator nodes).
   .EXAMPLE
   Enable-D365LBDSFAppServers
   Enables all the application servers on the local machines environment
   .EXAMPLE
    Enable-D365LBDSFAppServers -ComputerName "LBDServerName" -verbose
    Enables all the application servers on the specified servers environment
    .EXAMPLE
    $config = get-d365Config
   Enable-D365LBDSFAppServers -config $Config
    Enables all the application servers on the specified configurations environment
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
    .PARAMETER Timeout
    Integer
    Timeout in seconds for how long for the command to run has a default of 600 seconds
   #>

    [alias("Enable-D365SFAppServers")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [int]$Timeout = 600
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName
        }
        [int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                }
                Write-PSFMessage -Message "-ConnectionEndpoint $($config.SFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
                $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            }  until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count) -eq 0)
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric" -EnableException $true -FunctionName $_
            }
        }
        $AppNodes = Get-ServiceFabricNode | Where-Object { ($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType") -or ($_.NodeType -eq "ReportServerType") } 
        $primarynodes = Get-ServiceFabricNode | Where-Object { ($_.NodeType -eq "PrimaryNodeType") } 
        if ($primarynodes.count -gt 0) {
            Stop-PSFFunction -Message "Error: Primary Node configuration not supported with enable or disable. Restart-D365LBDSFAppServers is supported." -EnableException $true -FunctionName $_
        }
        foreach ($AppNode in $AppNodes) {
            Enable-ServiceFabricNode -NodeName $AppNode.NodeName 
        }
        Start-Sleep -Seconds 1
        [int]$timeoutondisablecounter = 0
        $nodestatus = Get-ServiceFabricNode | Where-Object { $_.NodeStatus -eq 'Disabled' -and (($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType")) }
        do {
            $nodestatus = Get-ServiceFabricNode | Where-Object { $_.NodeStatus -eq 'Disabled' -and (($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType")) } 
            $timeoutondisablecounter = $timeoutondisablecounter + 5
            Start-Sleep -Seconds 5
        } until (!$nodestatus -or $nodestatus -eq 0 -or ($timeoutondisablecounter -gt $Timeout))
        Write-PSFMessage -Message "All App Nodes Enabled" -Level VeryVerbose
    }
    END {}
}

function Export-D365LBDAssetModuleVersion {
    <#
    .SYNOPSIS
   Exports the version inside downloaded assets of the custom module name and also creates an xml in root for easy idenitification
   .DESCRIPTION
    Looks inside the agent share then extracts the version from the zip by using the custom module name.
   Exports the version and also creates an xml in root for easy idenitification.
   This is also a way to determine if a build has been fully prepped.
   .EXAMPLE
   Export-D365LBDAssetModuleVersion
 Exports all the assets in the agent share on the specified configurations environment
   .EXAMPLE
   $config = get-d365Config
    Export-D365LBDAssetModuleVersion -config $Config
    Exports all the assets in the agent share on the specified configurations environment
   .PARAMETER AgentShareLocation
   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
   .PARAMETER Timeout
    Integer
    Timeout in seconds for how long for the command to run has a default of 120 seconds
   #>

    [alias("Export-D365FOLBDAssetModuleVersion", "Export-D365AssetModuleVersion")]
    [CmdletBinding()]
    param
    (
        [Alias('AgentShare')]
        [string]$AgentShareLocation,
        [string]$CustomModuleName,
        [Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ValueFromPipeline = $True)]
        [psobject]$Config,
        [int]$Timeout = 120
        
    ) BEGIN {
    } 
    PROCESS {
        if ($Config) {
            $AgentShareLocation = $Config.AgentShareLocation
        }
        if (!$AgentShareLocation) {
            if ($CustomModuleName){
                Write-PSFMessage -Level VeryVerbose -Message "Connecting to $ComputerName to get config"
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly -custommoduleName $CustomModuleName
            }
            
            $AgentShareLocation = $Config.AgentShareLocation
        }
        if (!$CustomModuleName) {
            if ($Config.CustomModuleName) {
                $CustomModuleName = $Config.CustomModuleName
                if ($CustomModuleName){
                    Write-PSFMessage -Level VeryVerbose -Message "Found Custom Module Name $CustomModuleName in config"
                    if ($Config.SourceAXSFServer){
                    $Config = Get-D365LBDConfig -ComputerName $Config.SourceAXSFServer -HighLevelOnly -custommoduleName $CustomModuleName
                }
                    $AgentShareLocation = $Config.AgentShareLocation
                }
            }
            else {
                Stop-PSFFunction -Message "Error: Custom Module Name must be defined in parameter or in config." -EnableException $true -FunctionName $_
            }
        }
        Add-Type -AssemblyName System.IO.Compression.FileSystem
        $Filter = "*/Apps/AOS/AXServiceApp/AXSF/InstallationRecords/MetadataModelInstallationRecords/$CustomModuleName*.xml"
        $AssetFolders = Get-ChildItem "$AgentShareLocation\assets" | Where-Object { $_.Name -ne "topology.xml" -and $_.Name -ne "chk" } | Sort-Object LastWriteTime -Descending

        foreach ($AssetFolder in $AssetFolders ) {
            Write-PSFMessage -Message "Checking $AssetFolder" -Level Verbose
            $versionfile = $null
            $invalidfile = $false
            $versionfilepath = $AssetFolder.FullName + "\$CustomModuleName*.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
                $job = $null
                
                $job = start-job -ScriptBlock { Add-Type -AssemblyName System.IO.Compression.FileSystem; $zip = [System.IO.Compression.ZipFile]::OpenRead($using:StandaloneSetupZip) } -ErrorAction SilentlyContinue
           
                if (Wait-Job $job -Timeout $Timeout) { Receive-Job $job -ErrorAction SilentlyContinue }else {
                    Write-PSFMessage -Level VeryVerbose -message "Invalid Zip file $StandaloneSetupZip."
                    $invalidfile = $true
                    stop-job $job
                }
                if ($invalidfile -eq $false) {
                    $zip = [System.IO.Compression.ZipFile]::OpenRead($StandaloneSetupZip)
                    $count = $($zip.Entries | Where-Object { $_.FullName -like $Filter }).Count
                }
                else {
                    $count = 0
                }

                Remove-Job $job -Force
                
                if ($count -eq 0) {
                    Write-PSFMessage -Level Verbose -Message "Invalid Zip file or Module name $StandaloneSetupZip"
                }
                else {
                    try {
                        $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") 
                        } -ErrorAction Continue
                    }
                    catch {
                        Write-PSFMessage -Message "$_" -Level VeryVerbose
                    }
                    finally {
                        $zip.Dispose()
                    }
                    ##Closes Zip
                    $NewfileWithoutVersionPath = $SpecificAssetFolder + "\$CustomModuleName.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 "$CustomModuleName $Version.xml" -Verbose | Out-Null
                    Write-PSFMessage -Message "$CustomModuleName $Version.xml exported" -Level Verbose
                    Write-Output "$Version"
                    Write-PSFMessage -Message "Finished Prep at: $($StandaloneSetupZip.LastWriteTime)" -Level veryVerbose
                }
            }
        }
        if ($foundprepped -ne 1) {
            Write-PSFMessage -Level VeryVerbose -Message "No new version prepped trying to find latest" 
            $AssetFolders = Get-ChildItem "$AgentShareLocation\assets" | Where-Object { $_.Name -ne "topology.xml" -and $_.Name -ne "chk" } | Sort-Object CreationTime -Descending
            foreach ($Asset in $AssetFolders) {
                if ($foundprepped -ne 1) {
                    $versionlatest = Get-ChildItem "$($Asset.FullName)\$CustomModuleName*.xml"
                    if ($versionlatest) {
                        $StandaloneSetupZip = Get-ChildItem "$($Asset.FullName)\*\*\Packages\*\StandaloneSetup.zip"
                        Write-PSFMessage -Message "Last Version: $($versionlatest.BaseName) " -Level veryVerbose
                        Write-PSFMessage -Message "Finished Prep at: $($StandaloneSetupZip.LastWriteTime)" -Level veryVerbose
                        $foundprepped = 1
                    }
                }
            }
        }
    }
    END {}
}

function Export-D365LBDCertificates {
    <# TODO: Need to rethink approach doesnt work smoothly
   .SYNOPSIS
 
  .DESCRIPTION
   Exports
 
  .EXAMPLE
  Export-D365LBDCertificates
 
  .EXAMPLE
  Export-D365LBDCertificates -exportlocation "C:/certs" -username Stefan -certthumbprint 'A5234656'
 
  .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")]
    [CmdletBinding()]
    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 Export-D365LBDConfigReport {
    <#
    .SYNOPSIS
    Gathers data from the D365 environment for easy diagnostics and quicker onboarding for support tickets.
   .DESCRIPTION
    Gathers data from the D365 environment for easy diagnostics and quicker onboarding for support tickets.
   .EXAMPLE
    Export-D365LBDConfigReport -exportlocation "C:\ConfigreportBasicForLCSTicketsEnvironment.html" -CustomModuleName 'MOD'
    Creates a basic report at C:\ConfigreportBasicForLCSTicketsEnvironment.html based on local servers environment and a custom module name mod
   .EXAMPLE
   Export-D365LBDConfigReport -computername 'AXSFServer01' -detailed -exportlocation "C:\ConfigreportEnvironment.html" -CustomModuleName 'MOD'
  Creates a detailed report at C:\ConfigreportEnvironment.html based on server AXSFServer01's environment and a custom module name mod
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
.PARAMETER Detailed
    Switch
    if not selected the report will be basic with only details on issues. Less information for high level architecture without divulging any unneeded could be confidential config data.
.PARAMETER ExportLocation
    String Mandatory
    the file path to export the report to should end with a file extension of HTML
    .PARAMETER CustomModuleName
    String
    the name of the custom module name to gather more information of the environment such as build version
   #>

    [alias("Export-D365ConfigReport")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ValueFromPipeline = $True)]
        [psobject]$Config,
        [switch]$Detailed,
        [switch]$QueriesandEvents,
        [Parameter(Mandatory = $True)]
        [string]$ExportLocation, ##mandatory should end in html
        [string]$CustomModuleName
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            if ($CustomModuleName) {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName
            }
            else {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName
            }
        }
        Write-PSFMessage -Level VeryVerbose -Message "Running Environment Health Check"
        $Health = Get-D365LBDEnvironmentHealth -config $config
        $HealthGroups = $($Health.Group | Select-Object -unique)
        Write-PSFMessage -Level VeryVerbose -Message "Running Dependency Health Check"
        $DependencyCheck = Get-D365LBDDependencyHealth -Config $config
        $DependencyGroups = $($DependencyCheck.Group | Select-Object -unique)
        $HealthText = "<p class=""Success""><b>D365 Health looks great</b></p>"
        if ($Health.State -contains "Down") {
            $HealthText = "<p class=""issue""><b>D365 Health issues:</b></p>"
            $healthissues = $Health | Where-Object { $_.State -eq "Down" }
        }
        $html = "<html> <body>"
        if ($Detailed) {
            $html += "<h1><a href = ""$($Config.ClientURL)"">$($Config.LCSEnvironmentName)</a> </h1>"
        }
        else {
            $html += "<h1>$($Config.LCSEnvironmentName)</h1>"
        }  
        if (!$CustomModuleName) {
            $CustomModuleName = $Config.CustomModuleName
        }
        if ($CustomModuleName) {
            $html += "<p><b>Custom Code $CustomModuleName Version:</b></p> $($Config.CustomModuleVersion)"
        }
        $html += "<p><b>AX Kernel Version:</b></p> $($Config.AOSKernelVersion)"
        $html += "<p><b>LCS Project and Environment ID:</b></p> $($config.LCSProjectID) - <a href=""$($config.LCSEnvironmentURL)""> $($config.LCSEnvironmentID)</a> "
      
        if ($Config.AXDatabaseRestoreDate) {
            $html += "<p><b>Database Refresh/Restore Date:</b></p> $($Config.AXDatabaseRestoreDate) "
            if ($Detailed) {
                $html += "<p><b>Database Refresh/Restore file:</b></p> $($Config.AXDatabaseBackupFileUsedForRestore) "
            }
        }
        $html += "<p><b>Number of Apps in Healthy State:</b></p> <a href=""$($config.SFExplorerURL)""> $($Config.NumberOfAppsinServiceFabric) </a> "
        $html += "$HealthText"
        if ($healthissues) {
            foreach ($healthissue in $healthissues) {
                $html += "<p><b>Check:</b> $($healthissue.Name) <b>Source:</b> $($healthissue.Source) <b>Details:</b> $($healthissue.Details) <b>Additional Info:</b> $($healthissue.ExtraInfo) </p>"
            }
        }
        $html += "<b><p>Health Check Groups: </b></p> <ul>"
        foreach ($HealthGroup in $HealthGroups) {
            $html += "<li>$HealthGroup</li>"
        }
        $html += "</ul>"
        if ($DependencyCheck.Count -gt 0) {
            $DependencyCheckText = "<p class=""Success""><b>D365 Environment Dependencies Health looks great.</b></p>"
            if ($DependencyCheck.State -contains "Down") {
                $DependencyCheckText = "<p class=""issue""><b>D365 Dependency Health issues:</b></p>"
                $DependencyCheckissues = $DependencyCheck | Where-Object { $_.State -eq "Down" }
            }
            $html += "$DependencyCheckText"
            if ($DependencyCheckissues) {
                foreach ($DependencyCheckissue in $DependencyCheckissues) {
                    $html += "<p><b>Check:</b> $($DependencyCheckissue.Name) <b>Source:</b> $($DependencyCheckissue.Source) <b>Details:</b> $($DependencyCheckissue.Details) <b>Additional Info:</b> $($DependencyCheckissue.ExtraInfo) </p></p> "
                }
            }
            $html += "<b><p>Dependency Groups: </b></p> <ul>"
            foreach ($DependencyGroup in $DependencyGroups) {
                $html += "<li>$DependencyGroup</li>"
            }
            $html += "</ul>"
        }
        $html += "<p><b>Orchestrator Job State:</b> $($Config.OrchestratorJobState) <b>Last Ran Orchestrator Job ID:</b> $($Config.LastOrchJobId) </p>"
        $html += "<p><b>Run Book Task State:</b> $($Config.OrchestratorJobRunBookState) <b>Last Ran Run Book Task ID:</b> $($Config.LastRunbookTaskId) </p>"
        $CountofAXServerNames = $Config.AXSFServerNames.Count
        $html += "<p><b>Number of AX SF Servers:</b></p> $($CountofAXServerNames)"
        if ($Detailed) {
            $html += "<b><p>AX SF Servers: </b></p> <ul>"
            foreach ($axsfserver in $Config.AXSFServerNames) {
                $html += "<li>$axsfserver</li>"
            }
            $html += "</ul>"
        }
        $html += "<p><b>Number of Orchestrator Servers: </b> </p>$($Config.OrchestratorServerNames.Count)</p>"
        if ($Detailed) {
            $html += "<p><b>Orchestrator Servers:</b></p> <ul>"
            foreach ($AXOrchServerName in $Config.OrchestratorServerNames) {
                $html += "<li>$AXOrchServerName</li>"
            }
            $html += "</ul>"
        }
        if ($Detailed) {  
            $html += "<p><b>AX Database Connection Endpoint:</b></p> $($Config.AXDatabaseServer)"
        }
        $html += "<p><b>AX database is $($Config.DatabaseClusteredStatus)</b></p>"
        $DBCount = $Config.DatabaseClusterServerNames.Count
        if ($DBCount -gt 1) {
            $html += "<p><b>Number of Database servers:</b></p> $($Config.DatabaseClusterServerNames.Count)"
            if ($Detailed) {
                $html += "<p><b>Database server(s):</b></p> <ul>"
                foreach ($AXDBServerName in $($Config.DatabaseClusterServerNames)) {
                    $html += "<li>$AXDBServerName</li>"
                }
                $html += "</ul>"
            }
        }
        $html += "<p><b>Number of SSRS Report Servers: </b> </p>$($Config.SSRSClusterServerNames.Count)</p>"
        if ($Detailed) {
            $html += "<p><b>SSRS Servers:</b></p> <ul>"
            foreach ($SSRSClusterServerName in $Config.SSRSClusterServerNames) {
                $html += "<li>$SSRSClusterServerName</li>"
            }
            $html += "</ul>"
        }
        if ($Config.ComponentsinSetupModule -contains "financialreporting") {  
            $html += "<p><b>Number of Management Reporter Servers: </b> </p>$($Config.ManagementReporterServers.Count)</p>"
            if ($Detailed) {
                $html += "<p><b>Management Reporter Servers:</b></p> <ul>"
                foreach ($ManagementReporterServer in $Config.ManagementReporterServers) {
                    $html += "<li>$ManagementReporterServer</li>"
                }
                $html += "</ul>"
            }
        }
        $html += "<p><b>Local Agent Version:</b></p> $($Config.OrchServiceLocalAgentVersionNumber)</p>"
        $html += '<table style="width:100%" class="Thumbprints"><tr><th>Certificate</th>'
        if ($Detailed) {
            $html += '<th>Thumbprint</th>'
        }
        $html += '<th>Expiration Date</th></tr>'

        $html += '<tr><td>SF Client</td> '
        if ($Detailed) {
            $html += "<td> $($Config.SFClientCertificate)</td>"
        }
        $html += "<td> $($Config.SFClientCertificateExpiresAfter)</td></tr>"
        if ($(!$Config.SFClientCertificateExpiresAfter)) {
            Write-PSFMessage -Level VeryVerbose -Message "Make sure config was not run only high level if you want expirations"
        }
        $html += '<tr><td>SF Server</td> '
        if ($Detailed) {
            $html += "<td>$($Config.SFServerCertificate)</td>"
        }
        $html += "<td> $($Config.SFServerCertificateExpiresAfter)</td></tr>"

        $html += '<tr><td>Data Encryption</td> '
        if ($Detailed) {
            $html += "<td> $($Config.DataEncryptionCertificate)</td>"
        }
        $html += "<td> $($Config.DataEncryptionCertificateExpiresAfter)</td></tr>"

        $html += '<tr><td>Data Signing</td> '
        if ($Detailed) {
            $html += "<td>$($Config.DataSigningCertificate)</td>"
        }
        $html += "<td>$($Config.DataSigningCertificateExpiresAfter)</td></tr>"

        $html += '<tr><td>Session Authentication</td> '
        if ($Detailed) {
            $html += "<td>$($Config.SessionAuthenticationCertificate)</td>"
        }
        $html += "<td>$($Config.SessionAuthenticationCertificateExpiresAfter)</td></tr>"

        $html += '<tr><td>Shared Access</td> '
        if ($Detailed) {
            $html += "<td>$($Config.SharedAccessSMBCertificate)</td>"
        }
        $html += "<td>$($Config.SharedAccessSMBCertificateExpiresAfter)</td></tr>"


        if ($Config.DataEnciphermentCertificateExpiresAfter) {
            $html += '<tr><td>Data Encipherment</td> '
            if ($Detailed) {
                $html += "<td>$($Config.DataEnciphermentCertificate)</td>"
            }
            $html += "<td>$($Config.DataEnciphermentCertificateExpiresAfter)</td></tr>"
        }
        else {
            Write-PSFMessage -Level Warning -Message "DataEncipherment likely not configured in xml"
        }
        $html += '<tr><td>Financial Reporting (MR)</td> '
        if ($Detailed) {
            $html += "<td>$($Config.FinancialReportingCertificate)</td>"
        }
        $html += "<td>$($Config.FinancialReportingCertificateExpiresAfter)</td></tr>"

        $html += '<tr><td>Reporting SSRS </td> '
        if ($Detailed) {
            $html += "<td>$($Config.ReportingSSRSCertificate)</td>"
        }
        $html += "<td>$($Config.ReportingSSRSCertificateExpiresAfter)</td></tr>"
        if ($Config.DatabaseEncryptionCertificates) {
            foreach ($DatabaseEncryptionCertificate in $Config.DatabaseEncryptionCertificates) {

                $html += '<tr><td>Database Connection Configured Encryption </td> '
                if ($Detailed) {
                    $html += "<td>$($DatabaseEncryptionCertificate)</td>"
                }
                if ($Config.DatabaseEncryptionCertificatesExpiresAfter) {
                    $html += "<td>$($Config.DatabaseEncryptionCertificatesExpiresAfter)</td></tr>"
                }
                else {
                    $html += "<td>Can't get Expiration (Permissions on SQL OS level)</td></tr>"
                }
            }
        }
        else {
            Write-PSFMessage -Level Warning -Message "Database Encryption not configured in xml or access issues to Database server"
        }
        $html += '<tr><td>Local Agent</td> '
        if ($Detailed) {
            $html += "<td>$($Config.LocalAgentCertificate)</td>"
        }
        $html += "<td>$($Config.LocalAgentCertificateExpiresAfter)</td></tr>"
        $html += "</table>"
        if ($Detailed) {
            $guids = Get-D365LBDAXSFGUIDS -Config $Config
            $html += "<p></p><table style=""width:100%"" class=""GUIDS""> <tr> <th>Server</th> <th>GUID</th> <th>Endpoint</th> </tr>"
            
            foreach ($guid in $guids) {
                $html += "<tr><td>$($guid.Source)</td><td>$($guid.Details)</td><td><a href=""$($guid.ExtraInfo)"">$($guid.ExtraInfo)</a></td></tr>"
            }
            $html += "</table>"
        }
        
        if ($QueriesandEvents) {
            <# Source: https://stackoverflow.com/questions/8423541/how-do-you-run-a-sql-server-query-from-powershell
#>

            function Invoke-SQL {
                param(
                    [string] $dataSource = ".\SQLEXPRESS",
                    [string] $database = "MasterData",
                    [string] $sqlCommand = $(throw "Please specify a query.")
                )

                $connectionString = "Data Source=$dataSource; " +
                "Integrated Security=SSPI; " +
                "Initial Catalog=$database"

                $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
                $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)
                $connection.Open()
    
                $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
                $dataset = New-Object System.Data.DataSet

                $adapter.Fill($dataSet) | Out-Null
                $connection.Close()
                $dataSet.Tables
            }

            $SqlQueryToGetRunningSQL = "SELECT stext.TEXT,req.total_elapsed_time,req.session_id,req.status,req.command FROM sys.dm_exec_requests req CROSS APPLY sys.dm_exec_sql_text(sql_handle) stext" 
            $AXDatabaseName = $Config.AXDatabaseName
            $AXDatabaseServer = $Config.AXDatabaseServer
            $SqlresultsToGetRunningSQL = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SqlQueryToGetRunningSQL 
            $html += "<h2>Running Queries </h2>"
            $html += "<p></p><table style=""width:100%"" class=""SQLQueries""> <tr> <th>Command Type</th> <th>Command</th> <th>Elapsed Time</th> <th>Session ID</th> <th>Status</th> </tr>"
            
            foreach ($SQLResult in $SqlresultsToGetRunningSQL) {
    
                $html += "<tr><td>$($SQLResult.command)</td><td>$($SQLResult.TEXT)</td><td>$($SQLResult.total_elapsed_time)</td><td>$($SQLResult.session_id)</td><td>$($SQLResult.status)</td></tr>"
            }
            $html += "</table>"
            $SFissues = Get-D365LBDSFErrorDetails -Config $Config

            if ($SFissues){
                "<h2>Errors found in Service Fabric use Get-D365LBDSFErrorDetails</h2>"
            }
            else{
                $html += "<h2>No Errors found in Service Fabric</h2>"
            }

            $html += "<h2>Last Orchestrator Events: </h2>"
            $orchevents = Get-D365OrchestrationLogs -config $Config -NumberofEvents 10
            $html += "<p></p><table style=""width:100%"" class=""OrchLogs""> <tr> <th>Server</th> <th>MessageType</th> <th>DateTime</th> <th>EventMessage</th><th>EventDetails</th> </tr>"
            
            foreach ($orchevent in $orchevents) {
    
                $html += "<tr><td>$($orchevent.MachineName)</td><td>$($orchevent.Message)</td><td>$($orchevent.TimeCreated)</td><td>$($orchevent.EventMessage)</td><td>$($orchevent.EventDetails)</td></tr>"
            }
            $html += "</table>"

            $html += "<h2>Last Database Synchronize Events: </h2>"
            $dbevents = Get-D365DBEvents -config $Config -NumberofEvents 10
            $html += "<p></p><table style=""width:100%"" class=""OrchLogs""> <tr> <th>Server</th> <th>MessageType</th> <th>DateTime</th> <th>EventMessage</th><th>EventDetails</th> </tr>"
            foreach ($dbevent in $dbevents) {
    
                $html += "<tr><td>$($dbevent.MachineName)</td><td>$($dbevent.Message)</td><td>$($dbevent.TimeCreated)</td><td>$($dbevent.EventMessage)</td><td>$($dbevent.EventDetails)</td></tr>"
            }
            $html += "</table>"


        }
        $html += "</body></html>"
        $html |  Out-File "$ExportLocation"  -Verbose
    }
    END {}
}

function Get-D365LBDADFSSID {
    <#
    .SYNOPSIS
Loads Microsofts Dynamics Dll and gathers the SID based on the combination of Username and ADFS identifier
   .DESCRIPTION
Loads Microsofts Dynamics Dll and gathers the SID based on the combination of Username and ADFS identifier
   .EXAMPLE
Get-D365LBDADFSSID -Usernamewithemail 'fakeemail@offandonit.com' -ADFSIdentifier 'https://FakeADFS.Fakewebsite1231284u913.com/adfs/services/trust' -computername 'axserver01'
   .EXAMPLE
Get-D365LBDADFSSID -Usernamewithemail 'fakeemail@offandonit.com' -ADFSIdentifier 'https://FakeADFS.Fakewebsite1231284u913.com/adfs/services/trust' -config $config
   .PARAMETER ComputerName
   String
 
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
     
   #>

    [CmdletBinding()]
    [alias("Get-D365ADFSSID")]
    param ([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [string]$UsernamewithEmail,
        [Parameter(ValueFromPipeline = $True)]
        [psobject]$Config,
        [string]$ADFSIdentifier
    )
    BEGIN {
    } 
    PROCESS {
        if (!$Config) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        if (!$ADFSIdentifier) {
            $ADFSIdentifier = $Config.ADFSIdentifier
            Write-PSFMessage -Level VeryVerbose -Message "Using $ADFSIdentifier as ADFS Identifier"
        }
            
        if (!$ADFSIdentifier) {
            Stop-PSFFunction -Message "Error: Please define ADFS Identifier"  -EnableException $true -Cmdlet $PSCmdlet
        }
        if (!$Config) {
            Stop-PSFFunction -Message "Error: Cannot find AX environment"  -EnableException $true -Cmdlet $PSCmdlet
        }
        $codepath = (get-item $Config.RunningAXCodeFolder).FullName
        $DLL = Join-Path $codepath "\bin\Microsoft.Dynamics>AX.Security.SidGenerator.DLL"
        $SourceAXServer = $config.SourceAXSFServer

        $Session = New-PSSession -ComputerName $SourceAXServer
        $ADFSSID = invoke-command -Session $Session -ScriptBlock { 
            $DLLFileName = $using:DLL
            $UsernamewithEmail = $using:UsernamewithEmail
            $ADFSIdentifier = $using:ADFSIdentifier
            $ADFSIdentifier = $ADFSIdentifier.trim('')
            Write-Verbose "Loading $DLLFileName on $env:Computername "
            Add-Type -path $DLLFileName
            try {
                $ADFSSID = [Microsoft.Dynamics.Ax.Security.SidGenerator]::Generate("$UsernamewithEmail", $ADFSIdentifier, 'sha1')
            }
            catch {}
        }
        if (!$ADFSSID) {
            $ADFSSID = invoke-command -Session $Session -ScriptBlock { 
                try {
                    $ADFSSID = [Microsoft.Dynamics.Ax.Security.SidGenerator]::Generate("$UsernamewithEmail", $ADFSIdentifier)
                }
                catch {}
            }
        }
        if ($ADFSSID) {
            write-PSFMessage -Level VeryVerbose -Message "SID for $UsernamewithEmail created using $ADFSIdentifier."
            write-PSFMessage -Level VeryVerbose -Message "SID: $ADFSSID"
            $ADFSSID
        }
        else {
            write-PSFMessage -Level Error -Message "SID cannot be generated"
        }
    }
    END {
        if ($Session ) {
            Remove-PSSession -Session $Session   
        }
    }
}

function Get-D365LBDAXSFGuids {
    <#
   .SYNOPSIS
    Gathers Each AXSF Endpoint details includes its GUID (used for single server issue diagnostics), https endpoint and its current status.
  .DESCRIPTION
    Gathers Each AXSF Endpoint details includes its GUID (used for single server issue diagnostics), https endpoint and its current status.
  .EXAMPLE
  $config = get-d365Config
  Get-D365LBDAXSFGuids -config $Config
 Gathers Each AXSF Endpoint details based on the configuration that was gathered
  .EXAMPLE
  Get-D365LBDAXSFGuids
 Gathers Each AXSF Endpoint details based on the the local machines environment
  .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
    .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
  #>

    [alias("Get-D365AXSFGuids")]
    [CmdletBinding()]
    param
    (
        [psobject]$Config,
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME"
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName
        }
        [int]$count = 0
        $OutputList = @()
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                }
                Write-PSFMessage -Message "-ConnectionEndpoint $($config.SFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
                $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            }  until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count) -eq 0)
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
        }
        $nodes = get-servicefabricnode | Where-Object { ($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "PrimaryNodeType") } 
        $ServiceFabricPartitionIdForAXSF = $(get-servicefabricpartition -servicename 'fabric:/AXSF/AXService').PartitionId
        foreach ($node in $nodes) {
            $nodename = $node.Nodename
            $replicainstanceIdofnode = $(get-servicefabricreplica -partition $ServiceFabricPartitionIdForAXSF | Where-Object { $_.NodeName -eq "$NodeName" }).InstanceId
            $ReplicaDetails = Get-Servicefabricdeployedreplicadetail -nodename $nodename -partitionid $ServiceFabricPartitionIdForAXSF -ReplicaOrInstanceId $replicainstanceIdofnode -replicatordetail
            $endpoints = $ReplicaDetails.deployedservicereplicainstance.address | ConvertFrom-Json
            $deployedinstancespecificguid = $($endpoints.Endpoints | Get-Member | Where-Object { $_.MemberType -eq "NoteProperty" }).Name
            $httpsurl = $endpoints.Endpoints.$deployedinstancespecificguid
            Write-PSFMessage -Level VeryVerbose -Message "$NodeName is accessible via $httpsurl with a guid $deployedinstancespecificguid"

            if ($httpsurl.Length -gt 3){
                $Status = "Operational"
            }
            else{
                $Status = "Down"
            }
            $Properties = @{'Name' = "AXSFGUIDEndpoint"
                'Details'          = "$deployedinstancespecificguid"
                'Status'           = "$Status" 
                'ExtraInfo'        = "$httpsurl"
                'Source'           = $NodeName 
                'Group'            = 'ServiceFabric'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output

        }
        [PSCustomObject] $OutputList | Sort-Object {$_.Source}
        
    }
    END {
        if ($SFModuleSession) {
            Remove-PSSession -Session $SFModuleSession  
        }
    }
} 

function Get-D365LBDCertsFromConfig {
<# TODO: Need to rethink approach of certs
    .SYNOPSIS
    Grabs the certificatedetails from the config for easier export/analysis
    .DESCRIPTION
    Grabs the certificatedetails from the config for easier export/analysis
    .EXAMPLE
    Get-D365LBDCertsFromConfig
     
    .EXAMPLE
    Get-D365LBDCertsFromConfig -OnlyAdminCerts
     
    .PARAMETER Config
    optional psobject
    The configuration of D365 from the command Get-D365LBDConfig
    If ignored will use local host.
    .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
       #>

    [alias("Get-D365CertsFromConfig")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [string]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [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 Also loads this modules custom XML (AdditionalEnvironmentDetails.xml) if configured
   .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
   .EXAMPLE
   $Config = Get-D365LBDConfig -ConfigImportFromFile "C:\XMLExports\EnvironmentConfig.xml"
   This will import the config
   .EXAMPLE
   Get-D365LBDConfig -ConfigExportToFile "C:\XMLExports\EnvironmentConfig.xml" -CustomModuleName 'CUS'
   This will export the config
   .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 capture the version number
   .PARAMETER HighLevelOnly
   optional switch
   for quicker runs grab the config without verifying or grabbing additional details from the service fabric cluster
   #>

    [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" 
                if (Test-path "C:\ProgramData\SF\$env:COMPUTERNAME\ClusterManifest.current.xml") {
                    $ClusterManifestXMLFile = "C:\ProgramData\SF\$env:COMPUTERNAME\ClusterManifest.current.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

            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
            $ManagementReporterServerName = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'MRType' }).NodeName 
            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
                    }
                }
            }
            $fabricfolder = get-childitem "\\$OrchestratorServerName\C$\ProgramData\SF\*\Fabric" | Sort-Object { $_.LastWriteTime }  -Descending | Select-Object -First 1
            if ($(Test-Path "$fabricfolder\clusterManifest.current.xml") -eq $True) {
                Write-PSFMessage -Message "Gathering Current Manifest from $ComputerName as it exists"
                $ClusterManifestXMLFile = get-childitem "$fabricfolder\clusterManifest.current.xml"
                
            }
            [xml]$xml = get-content $ClusterManifestXMLFile
            Write-PSFMessage -Message "Reading $ClusterManifestXMLFile" -Level Verbose ##
            $AXSFServerNames = $($xml.ClusterManifest.Infrastructure.WindowsServer.NodeList.Node | Where-Object { $_.NodeTypeRef -contains 'AOSNodeType' -or $_.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
            $SFClusterCertificate = $(($($xml.ClusterManifest.FabricSettings.Section | Where-Object { $_.Name -eq "Security" })).Parameter | Where-Object { $_.Name -eq "ClusterCertThumbprints" }).value
            $ServerCertificate = $SFClusterCertificate | Select-Object -First 1
            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
            $sb = New-Object System.Data.Common.DbConnectionStringBuilder
            $sb.set_ConnectionString($($OrchDBConnectionString.Value))
            $OrchDatabase = $sb.'initial catalog'
            $OrchdatabaseServer = $sb.'data source'
    
            $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
            if (!$ServerCertificate) {
                $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' }
                $ADFSIdentifier = $($AAD.Parameter | Where-Object { $_.Name -eq 'ADFSIdentifier' }).value 
                $ClientURL = $($AAD.Parameter | Where-Object { $_.Name -eq 'AADValidAudience' }).value + "namespaces/AXSF/"
                $SFExplorerURL = $($ClientURL.Replace('//ax.', '//sf.')).Replace('/namespaces/AXSF/', ':19080')

                $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
       
            }

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

            if ($AgentShareWPConfigJson) {
                Write-PSFMessage -Message "Verbose: Using AgentShare config at $AgentShareWPConfigJson to get Environment ID, EnvironmentName and TenantID." -Level Verbose
                $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 = ""
            }
            $LCSProjectID = $($($(Get-ChildItem $AgentShareLocation\assets\*\*\*\packages | Sort-Object { $_.CreationTime } -Descending | Where-Object { $_.Name -ne "chk" -and $_.Name -ne "topology.xml" -and $_.Name -ne "ControlFile.txt" } | Select-Object -First 1).Parent).Parent).Name
            if ($LCSProjectID -and $LCSEnvironmentId) {
                $LCSEnvironmentURL = "https://lcs.dynamics.com/v2/EnvironmentDetailsV3New/$LCSProjectID" + "?" + "EnvironmentId=$LCSEnvironmentId"
            }
            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"
                }
            }
            
            $AXServiceConfigXMLFile = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\work\Applications\AXSFType_App*\AXSF.Code*\AXService.exe.config" | Sort-Object { $_.CreationTime } -Descending | 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

            $FinancialReportingCertificate = $($AXServiceConfigXML.configuration.claimIssuerRestrictions.issuerrestrictions.add | Where-Object { $_.alloweduserids -eq "FRServiceUser" }).name

            if (test-path $AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml) {
                Write-PSFMessage -Level Verbose -Message "Found AdditionalEnvironmentDetails config"
                $EnvironmentAdditionalConfig = get-childitem  "$AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml"
            }
            else {
                Write-PSFMessage -Message "Warning: Can't find additional Environment Config. Not needed but recommend making one" -level warning  
            }

            if ($EnvironmentAdditionalConfig) {
                Write-PSFMessage -Message "Reading $EnvironmentAdditionalConfig" -Level Verbose
                [xml]$EnvironmentAdditionalConfigXML = get-content  $EnvironmentAdditionalConfig
                $EnvironmentType = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentType.'#text'.Trim()
                
                if (!$CustomModuleName) {
                    if ($($EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.CustomModuleName.'#text')) {
                        $CustomModuleNameinConfig = $($EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.CustomModuleName.'#text').TrimStart()
                    }
                    else {
                        if ($($EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.CustomModuleName)) {
                            $CustomModuleNameinConfig = $($EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.CustomModuleName).TrimStart()
                        }
                    }
                    if ($CustomModuleNameinConfig.Length -gt 0) {
                        $CustomModuleNameinConfig = $CustomModuleNameinConfig.TrimEnd()
                        $CustomModuleName = $CustomModuleNameinConfig
                    }
                }
            }
            $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 {}
            }
           
            ##checking for after deployment added servers
            try {
                $currentclustermanifestxmlfile = get-childitem "\\$AXSFConfigServerName\C$\ProgramData\SF\*\Fabric\clustermanifest.current.xml" | Sort-Object { $_.CreationTime } -Descending | Select-Object -First 1
                [xml]$currentclustermanifestxml = Get-Content $currentclustermanifestxmlfile
                $AXSFServerListToCompare = $currentclustermanifestxml.clusterManifest.Infrastructure.NodeList.Node | Where-Object { $_.NodeTypeRef -eq 'AOSNodeType' -or $_.NodeTypeRef -eq 'PrimaryNodeType' }
                $SFClusterCertificate = $(($($currentclustermanifestxml.ClusterManifest.FabricSettings.Section | Where-Object { $_.Name -eq "Security" })).Parameter | Where-Object { $_.Name -eq "ClusterCertThumbprints" }).value
                $ServerCertificate = $SFClusterCertificate | Select-Object -First 1
                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
                    <#NewConnection logic start#>
                    $count = 0
                    if (!$connection) {
                        do {
                            $OrchestratorServerName = $OrchestratorServerNames | Select-Object -First 1 -Skip $count
                            Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                            $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                            if (!$module) {
                                $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                            }
                            $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $ConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My
                            if ($connection) {
                                Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $ConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                            }
                            if (!$connection) {
                                $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                                $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My
                                if ($connection) {
                                    Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                                }
                            }
                            if (!$connection) {
                                $connection = Connect-ServiceFabricCluster
                                if ($connection) {
                                    Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster"
                                }
                            }
                            $count = $count + 1
                            if (!$connection) {
                                Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                            }
                            
                        } until ($connection -or ($count -eq $($OrchestratorServerNames).Count) -or ($($OrchestratorServerNames).Count) -eq 0)
                    }
                    <#NewConnection logic end#>
                   
                    $NumberOfAppsinServicefabric = $($(get-servicefabricclusterhealth | select ApplicationHealthStates).ApplicationHealthStates.Count) - 1
                    if ($NumberOfAppsinServicefabric -eq -1) {
                        $NumberOfAppsinServicefabric = $null
                    }
                    $AggregatedSFState = $(get-servicefabricclusterhealth | select AggregatedHealthState).AggregatedHealthState
                    $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"
                    }

                    try {
                        $ServiceFabricPartitionIdForAXSF = $(get-servicefabricpartition -servicename 'fabric:/AXSF/AXService' -ErrorAction Stop).PartitionId
                    }
                    catch {
                    }
                    if (!$ServiceFabricPartitionIdForAXSF) {
                        Write-PSFMessage -Level VeryVerbose -Message "Warning: AXSF Partition not found cannot gather node details as AXSF is not installed"
                    }
                    else {
                        foreach ($node in $nodes) {
                            $nodename = $node.Nodename
                            $replicainstanceIdofnode = $(get-servicefabricreplica -partition $ServiceFabricPartitionIdForAXSF | Where-Object { $_.NodeName -eq "$NodeName" }).InstanceId
                            $ReplicaDetails = Get-Servicefabricdeployedreplicadetail -nodename $nodename -partitionid $ServiceFabricPartitionIdForAXSF -ReplicaOrInstanceId $replicainstanceIdofnode -replicatordetail
                            $endpoints = $ReplicaDetails.deployedservicereplicainstance.address | ConvertFrom-Json
                            if ($endpoints.Endpoints) {
                                $deployedinstancespecificguid = $($endpoints.Endpoints | Get-Member | Where-Object { $_.MemberType -eq "NoteProperty" }).Name
                                $httpsurl = $endpoints.Endpoints.$deployedinstancespecificguid
                                Write-PSFMessage -Level VeryVerbose -Message "$NodeName is accessible via $httpsurl with a guid $deployedinstancespecificguid "
                            }
                            else {
                                Write-PSFMessage -Level VeryVerbose -Message "Warning: $nodename doesnt have an endpoint. Likely AXSF is down on that node"
                            }
                        }
                    }
                }
                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
                }
            }
            foreach ($ComputerName in $ManagementReporterServerName) {
                if (($AllAppServerList -contains $ComputerName) -eq $false) {
                    $AllAppServerList += $ComputerName
                }
            }
            $AllAppServerList = $AllAppServerList | select -Unique
            ##
            <# Source: https://stackoverflow.com/questions/8423541/how-do-you-run-a-sql-server-query-from-powershell
#>

            function Invoke-SQL {
                param(
                    [string] $dataSource = ".\SQLEXPRESS",
                    [string] $database = "MasterData",
                    [string] $sqlCommand = $(throw "Please specify a query.")
                )

                $connectionString = "Data Source=$dataSource; " +
                "Integrated Security=SSPI; " +
                "Initial Catalog=$database"

                $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
                $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)
                $connection.Open()
                
                $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
                $dataset = New-Object System.Data.DataSet

                $adapter.Fill($dataSet) | Out-Null
                $connection.Close()
                $dataSet.Tables
            }
            try {
                if ($CustomModuleName) {
                    $path = Get-ChildItem "$agentsharelocation\wp\*\StandaloneSetup-*\Apps\AOS\AXServiceApp\AXSF\InstallationRecords\MetadataModelInstallationRecords" | Sort-Object { $_.CreationTime } -Descending | Select-Object -first 1 -ExpandProperty FullName
                    $pathtoxml = "$path\$CustomModuleName.xml"
                    if ($path) {
                        [xml]$xml = Get-Content $pathtoxml
                        $CustomModuleVersioninAgentShare = $xml.MetadataModelInstallationInfo.Version
                    }
                    else {
                        Write-PSFMessage -Level Warning -Message "Can't find $path\$CustomModuleName.xml to get Version in Agent Share "
                    }
                }
            }
            catch {}
            if (!$AXDatabaseName) {
                $AXDatabaseName = "AXDB"
            }
            $SQLQueryToGetRefreshinfo = " Select top 1 [rh].[destination_database_name], [sd].[create_date], [bs].[backup_start_date], [rh].[restore_date], [bmf].[physical_device_name] as 'backup_file_used_for_restore'
from msdb..restorehistory rh
inner join msdb..backupset bs on [rh].[backup_set_id] = [bs].[backup_set_id]
inner join msdb..backupmediafamily bmf on [bs].[media_set_id] = [bmf].[media_set_id]
inner join sys.databases sd on [sd].[name] = [rh].[destination_database_name]
where [rh].[destination_database_name] = '$AXDatabaseName'
ORDER BY [rh].[restore_date] DESC"

            if ($AXDatabaseServer) {
                try {
                    $SqlresultsToGetRefreshinfo = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQueryToGetRefreshinfo
                }
                catch {}
                if ($SqlresultsToGetRefreshinfo.Count -eq 0) {
                    $whoami = whoami
                    Write-PSFMessage -Level VeryVerbose -Message "Can't find SQL results with query. Check if database is up and permissions are set for $whoami. Server: $AXDatabaseServer - DatabaseName: $AXDatabaseName."
                }
                else {
                    $AXDatabaseRestoreDateSQL = $SqlresultsToGetRefreshinfo | Select-Object restore_date
                    [string]$AXDatabaseRestoreDate = $AXDatabaseRestoreDateSQL
                    $AXDatabaseRestoreDate = $AXDatabaseRestoreDate.Trim("@{restore_date=")
                    $AXDatabaseRestoreDate = $AXDatabaseRestoreDate.Substring(0, $AXDatabaseRestoreDate.Length - 1)

                    $AXDatabaseCreationDateSQL = $SqlresultsToGetRefreshinfo | Select-Object create_date
                    [string]$AXDatabaseCreationDate = $AXDatabaseCreationDateSQL
                    $AXDatabaseCreationDate = $AXDatabaseCreationDate.Trim("@{create_date=")
                    $AXDatabaseCreationDate = $AXDatabaseCreationDate.Substring(0, $AXDatabaseCreationDate.Length - 1)

                    $AXDatabaseBackupStartDateSQL = $SqlresultsToGetRefreshinfo | Select-Object backup_start_date
                    [string]$AXDatabaseBackupStartDate = $AXDatabaseBackupStartDateSQL 
                    $AXDatabaseBackupStartDate = $AXDatabaseBackupStartDate.Trim("@{backup_start_date=")
                    $AXDatabaseBackupStartDate = $AXDatabaseBackupStartDate.Substring(0, $AXDatabaseBackupStartDate.Length - 1)

                    $AXDatabaseBackupFileUsedForRestoreSQL = $SqlresultsToGetRefreshinfo | Select-Object backup_file_used_for_restore
                    [string]$AXDatabaseBackupFileUsedForRestore = $AXDatabaseBackupFileUsedForRestoreSQL
                    $AXDatabaseBackupFileUsedForRestore = $AXDatabaseBackupFileUsedForRestore.Trim("@{backup_file_used_for_restore=")
                    $AXDatabaseBackupFileUsedForRestore = $AXDatabaseBackupFileUsedForRestore.Substring(0, $AXDatabaseBackupFileUsedForRestore.Length - 1)

                    $SQLQueryToGetConfigMode = "select * from SQLSYSTEMVARIABLES Where PARM = 'CONFIGURATIONMODE'"
                    try {
                        $SqlresultsToGetConfigMode = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQueryToGetConfigMode
                    }
                    catch {}
                    $ConfigurationModeSQL = $SqlresultsToGetConfigMode | Select-Object value
                    [string]$ConfigurationModeString = $ConfigurationModeSQL
                    $ConfigurationModeString = $ConfigurationModeString.Trim("@{value=")
                    $ConfigurationModeString = $ConfigurationModeString.Trim("VALUE=")
                    $ConfigurationModeString = $ConfigurationModeString.Substring(0, $ConfigurationModeString.Length - 1)
                    [int]$configurationmode = $ConfigurationModeString 
                    if ($configurationmode -eq 1) {
                        Write-PSFMessage -Level VeryVerbose -Message "Warning: Found that Maintenance Mode is On"
                        $ConfigurationModeEnabledDisabled = 'Enabled'
                    }
                    if ($configurationmode -eq 0)
                    { $ConfigurationModeEnabledDisabled = 'Disabled' }
                }
            }
            else {
                Write-PSFMessage "$AXDatabaseServer not found so cant get database details" -Level Verbose
                if (!$AXDatabaseServer) {
                    $AXDatabaseServer = $DatabaseClusterServerNames | select -First 1
                }
                
                if (!$AXDatabaseServer) {
                    $AXDatabaseServer = $OrchdatabaseServer 
                }
            }
            $SQLQueryToGetOrchestratorDataOrchestratorJob = "select top 1 State, QueuedDateTime, LastProcessedDateTime, EndDateTime,JobId, DeploymentInstanceId from OrchestratorJob order by ScheduledDateTime desc"
            $SQLQueryToGetOrchestratorDataRunBook = "select top 1 RunBookTaskId, Name, Description, State, StartDateTime, EndDateTime, OutputMessage from RunBookTask order by StartDateTime desc"
            try {
                $SqlresultsToGetOrchestratorDataOrchestratorJob = invoke-sql -datasource $OrchdatabaseServer -database $OrchDatabase -sqlcommand $SQLQueryToGetOrchestratorDataOrchestratorJob
            }
            catch {}
            try {
                $SqlresultsToGetOrchestratorDataRunBook = invoke-sql -datasource $OrchdatabaseServer -database $OrchDatabase -sqlcommand $SQLQueryToGetOrchestratorDataRunBook
            }
            catch {}
            if ($SqlresultsToGetOrchestratorDataRunBook.Count -eq 0) {
                $whoami = whoami
                Write-PSFMessage -Level VeryVerbose -Message "Can't find SQL results with query. Check if database is up and permissions are set for $whoami. Server: $OrchdatabaseServer - DatabaseName: $OrchDatabase."
            }
            else {
                $OrchestratorJobSQL = $SqlresultsToGetOrchestratorDataOrchestratorJob | Select-Object State
                [string]$OrchestratorDataOrchestratorJobStateString = $OrchestratorJobSQL
                $OrchestratorDataOrchestratorJobStateString = $OrchestratorDataOrchestratorJobStateString.Trim("@{State=")
                $OrchestratorDataOrchestratorJobStateString = $OrchestratorDataOrchestratorJobStateString.Trim("State=")
                $OrchestratorDataOrchestratorJobStateString = $OrchestratorDataOrchestratorJobStateString.Substring(0, $OrchestratorDataOrchestratorJobStateString.Length - 1)
                [int]$OrchestratorDataOrchestratorJobStateInt = $OrchestratorDataOrchestratorJobStateString

                $RunBookSQL = $SqlresultsToGetOrchestratorDataRunBook | Select-Object State
                [string]$OrchestratorDataRunBookStateString = $RunBookSQL
                $OrchestratorDataRunBookStateString = $OrchestratorDataRunBookStateString.Trim("@{State=")
                $OrchestratorDataRunBookStateString = $OrchestratorDataRunBookStateString.Trim("State=")
                $OrchestratorDataRunBookStateString = $OrchestratorDataRunBookStateString.Substring(0, $OrchestratorDataRunBookStateString.Length - 1)
                [int]$OrchestratorDataRunBookStateInt = $OrchestratorDataRunBookStateString

                switch ($OrchestratorDataOrchestratorJobStateInt ) {
                    0 { $OrchestratorJobState = 'Not Started' }
                    1 { $OrchestratorJobState = 'In Progress' }
                    2 { $OrchestratorJobState = 'Successful' }
                    3 { $OrchestratorJobState = 'Failed' }
                    4 { $OrchestratorJobState = 'Cancelled' }
                    5 { $OrchestratorJobState = 'Unknown Status' }
                }
                switch ( $OrchestratorDataRunBookStateInt) {
                    0 { $OrchestratorJobRunBookState = 'Not Started' }
                    1 { $OrchestratorJobRunBookState = 'In Progress' }
                    2 { $OrchestratorJobRunBookState = 'Successful' }
                    3 { $OrchestratorJobRunBookState = 'Failed' }
                    4 { $OrchestratorJobRunBookState = 'Cancelled' }
                    5 { $OrchestratorJobRunBookState = 'Unknown Status' }
                }
                $OrchJobQuery = 'select top 1 JobId,State from OrchestratorJob order by ScheduledDateTime desc'
                $RunBookQuery = 'select top 1 RunbookTaskId, State,Name from RunBookTask order by StartDateTime desc'
                $OrchJobQueryResults = Invoke-SQL -dataSource $OrchDatabaseServer -database $OrchDatabase -sqlCommand $OrchJobQuery
                $RunBookQueryResults = Invoke-SQL -dataSource $OrchDatabaseServer -database $OrchDatabase -sqlCommand $RunBookQuery 
                $LastOrchJobId = $($OrchJobQueryResults | select JobId).JobId
                $LastRunbookTaskId = $($RunBookQueryResults | select RunbookTaskId).RunbookTaskId
                $LastRunbookName = $($RunBookQueryResults | select Name).Name
            }

            $SQLQueryToGetAlwaysOn = " WITH AGStatus AS(
                SELECT name as AGName,
                replica_server_name,
                AGDatabases.database_name AS Databasename
                FROM master.sys.availability_groups Groups
                INNER JOIN master.sys.availability_replicas Replicas ON groups.group_id = Replicas.group_id
                INNER JOIN sys.availability_databases_cluster AGDatabases ON groups.group_id = AGDatabases.group_id
                INNER JOIN master.sys.dm_hadr_availability_group_states States ON Groups.group_id = States.group_id
                )
                SELECT DISTINCT
                [Replica_server_name] FROM AGStatus
                WHERE
                [databasename] = '$AXDatabaseName'"

            try {
                $SQLQueryToGetAlwaysOnResults = Invoke-SQL -dataSource $AXDatabaseServer -database 'master' -sqlCommand $SQLQueryToGetAlwaysOn
            }
            catch {}
            $listofsqlservers = @()
            if ($SQLQueryToGetAlwaysOnResults.Count -eq 0) {
                Write-PSFMessage -Level VeryVerbose -Message "Looks like always on is not set up in the database $AXDatabaseName Source: $AXDatabaseServer "
                $DatabaseClusteredStatus = "NonClustered"
                $listofsqlservers = $AXDatabaseServer
                $DatabaseClusterServerNames = $listofsqlservers 
            }
            else {
                $DatabaseClusteredStatus = "Clustered"
                foreach ($SQLQueryToGetAlwaysOnResult in $($SQLQueryToGetAlwaysOnResults | select replica_server_name)) {
                    $listofsqlservers += $SQLQueryToGetAlwaysOnResult.Replica_server_name
                }
                $DatabaseClusterServerNames = $listofsqlservers 
            }

            if ($EnvironmentAdditionalConfigXML) {
                if (!$DatabaseClusterServerNames) {
                    $DatabaseClusterServerNames = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.SQLDetails.SQLServer | ForEach-Object -Process { New-Object -TypeName psobject -Property `
                        @{'DatabaseClusterServerNames' = $_.ServerName } }
                    $DatabaseEncryptionThumbprints = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.SQLDetails.SQLServer | ForEach-Object -Process { New-Object -TypeName psobject -Property `
                        @{'DatabaseEncryptionCertificates' = $_.DatabaseEncryptionThumbprint } }
                    $DatabaseEncryptionThumbprints = $DatabaseEncryptionThumbprints.DatabaseEncryptionCertificates
                    $DatabaseClusterServerNames = $DatabaseClusterServerNames.DatabaseClusterServerNames
                    $DataEnciphermentCertificate = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.DataEnciphermentCertThumbprint
                    if ($DatabaseClusterServerNames.Count -gt 1) {
                        $DatabaseClusteredStatus = 'Clustered'
                    }
                    else {
                        $DatabaseClusteredStatus = 'NonClustered'
                    }
                }
            }
            $listofsqlcerts = @()
            foreach ($sqlserver in $DatabaseClusterServerNames) {
                try {
                    $ProductVersionSQLResults = Invoke-SQL -dataSource $sqlserver -database 'master' -sqlCommand 'SELECT SERVERPROPERTY(''Productversion'') as ''Productversion'' '
                    [string]$SQLMajorVersionNumber = $($ProductVersionSQLResults | select Productversion).Productversion
                    $SQLMajorVersionNumber = $SQLMajorVersionNumber.Substring(0, 2)
                }
                catch {}
                try {
                    $InstanceNameSQLResults = Invoke-SQL -dataSource $sqlserver -database 'master' -sqlCommand 'SELECT @@SERVICENAME as ''Servicename'' '
                }
                catch {}
                $InstanceName = $($InstanceNameSQLResults | select Servicename).Servicename
                $SQLVersionandInstance = 'MSSQL' + $SQLMajorVersionNumber + '.' + $InstanceName
                Write-PSFMessage -Level VeryVerbose -Message "Connecting to Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\$SQLVersionandInstance\MSSQLSERVER\SuperSocketNetLib"

                try {
                    $SQLCert = invoke-command -ScriptBlock {
                        if (!$SQLVersionandInstance) {
                            $SQLVersionandInstance = $using:SQLVersionandInstance
                        }
                        $cert = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\$SQLVersionandInstance\MSSQLSERVER\SuperSocketNetLib"
                        $cert.Certificate.ToUpper()
                    } -ComputerName $sqlserver -ErrorAction Stop
                }                
                catch {
                    $whoami = whoami
                    Write-PSFMessage -Level Warning -Message "Warning: Can't connect to $SqlServer with account $whoami to gather SQL Cert Encryption details"
                }
                $listofsqlcerts += $SQLCert      
            }
            $DatabaseEncryptionThumbprints = $listofsqlcerts 


            if ($CustomModuleName) {
                $newassets = Export-D365FOLBDAssetModuleVersion -AgentShare $AgentShareLocation -CustomModuleName $CustomModuleName
                if ($newassets) {
                    foreach ($newasset in $newassets) {
                        Write-PSFMessage -Level VeryVerbose -Message "Found new prepped asset $newasset"
                    }
                    $NewPreppedAsset = $newassets | select -First 1
                }
                
                $assets = Get-ChildItem -Path "$AgentShareLocation\assets" | Where-object { ($_.Name -ne "chk") -and ($_.Name -ne "topology.xml") } | Sort-Object { $_.CreationTime } -Descending
                $versions = @()
                foreach ($asset in $assets) {
                    $versionfile = (Get-ChildItem $asset.FullName -File | Where-Object { $_.Name -like "$CustomModuleName*" }).Name
                    $version = ($versionfile -replace $CustomModuleName) -replace ".xml"
                    $versions += $version
                }
                $versions = $versions | Where-Object { $_ }
                $CustomModuleVersionFullPreppedinAgentShare = $versions | Sort-Object { $_.CreationTime } -Descending | Select-Object -First 1
                if ($CustomModuleVersionFullPreppedinAgentShare) {
                    $CustomModuleVersionFullPreppedinAgentShare = $CustomModuleVersionFullPreppedinAgentShare.trim()
                }
            }
            ##Getting DB Sync Status using winevent Start
            Foreach ($AXSFServerName in $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 database synchronization log updated to $ServerWithLatestLog with a date time of $LatestEventinLog"
                }
            }
            if (!$HighLevelOnly) {
                ##Found which server is getting the latest database sync using winevent end
                Write-PSFMessage -Level VeryVerbose -Message "Gathering Database Logs from $ServerWithLatestLog"
                try {
                    $events = Get-WinEvent -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -computername $ServerWithLatestLog -maxevents 100
                }
                catch {}
                if (!$events) {
                    Write-PSFMessage -Level Warning -Message "Warning: Having troubles grabbing DatabaseSynchronize from $ServerWithLatestLog "
                }
                else {
                    try {
                        $events = Get-WinEvent -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -computername $ServerWithLatestLog -maxevents 100  | 
                        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;
                            }
                        }
                    }
                    catch {}

                    $SyncStatusFound = $false
                    foreach ($event in $events) {
                        if ((($event.message -contains "Table synchronization failed.") -or ($event.message -contains "Database Synchronize Succeeded.") -or ($event.message -contains "Database Synchronize Failed.")) -and $SyncStatusFound -eq $false) {
                            if (($event.message -contains "Table synchronization failed.") -or ($event.message -contains "Database Synchronize Failed.")) {
                                Write-PSFMessage -Message "Found a DB Sync failure $event" -Level Verbose
                                $DBSyncStatus = "Failed"
                                $DBSyncTimeStamp = $event.TimeCreated
                            }
                            if ($event.message -contains "Database Synchronize Succeeded.") {
                                Write-PSFMessage -Message "Found a DB Sync Success $event" -Level Verbose
                                $DBSyncStatus = "Succeeded"
                                $DBSyncTimeStamp = $event.TimeCreated
                            }
                            $SyncStatusFound = $true
                        }
                    }
                }
            }
            $AssetFolders = Get-ChildItem "$AgentShareLocation\assets" | Where-Object { $_.Name -ne "topology.xml" -and $_.Name -ne "chk" } | Sort-Object CreationTime -Descending 
            $latestfound = 0
            foreach ($Asset in $AssetFolders) {
                $versionlatest = Get-ChildItem "$($Asset.FullName)\$CustomModuleName*.xml"
                if ($versionlatest -and $latestfound -ne 1) {
                    $StandaloneSetupZip = Get-ChildItem "$($Asset.FullName)\*\*\Packages\*\StandaloneSetup.zip"
                    Write-PSFMessage -Message "Last Version: $($versionlatest.BaseName) " -Level veryVerbose
                    Write-PSFMessage -Message "Finished Prep at: $($StandaloneSetupZip.LastWriteTime)" -Level veryVerbose
                    $LastFullyPreppedCustomModuleAsset = $versionlatest.BaseName
                    $LastFullyPreppedCustomModuleAsset = $LastFullyPreppedCustomModuleAsset -replace "$CustomModeName",""
                    $LastFullyPreppedCustomModuleAsset = $LastFullyPreppedCustomModuleAsset.trim()
                    $latestfound = 1
                }
            }
            $WPAssetIDTXT = Get-ChildItem $AgentShareLocation\wp\*\AssetID.txt |  Sort-Object LastWriteTime -Descending | Select-Object -First 1
            if ($WPAssetIDTXT) {
                $WPAssetIDTXTContent = Get-Content $WPAssetIDTXT.FullName
                $DeploymentAssetIDinWPFolder = $WPAssetIDTXTContent[0] -replace "AssetID: ", ""
            }
            try {
                Write-PSFMessage -Level Verbose -Message "Looking for process AXService $AXSFConfigServerName to get the running folder"
                $RunningAXCodeFolder = Invoke-Command -ComputerName $AXSFConfigServerName -ScriptBlock { $($process = Get-Process | Where-Object { $_.Name -eq "AXService" }; if ($process) { split-path $($process | Select-Object *).Path -Parent }) }
                $RunningAXCodeFolderLastWriteTime = $(Invoke-Command -ComputerName $AXSFConfigServerName -ScriptBlock { get-childitem $using:RunningAXCodeFolder -directory | select LastWriteTime -First 1 }).LastWriteTime
            }
            catch {

            }
            $WPFolder = join-path $AgentShareLocation "wp\$LCSEnvironmentName"
            $SetupJson = Get-ChildItem "$WPFolder\StandaloneSetup-*\setupmodules.json" | Select-Object -First 1
            $json = Get-Content $SetupJson.FullName -Raw | ConvertFrom-Json 
            $componentsinsetupmodule = $json.components.name
            $SSRSClusterServerNames = $ReportServerServerName
            # 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
                'DatabaseEncryptionCertificates'             = $DatabaseEncryptionThumbprints
                'DatabaseClusteredStatus'                    = $DatabaseClusteredStatus
                'DatabaseClusterServerNames'                 = $DatabaseClusterServerNames
                'SourceAXSFServer'                           = $AXSFConfigServerName
                'CustomModuleVersioninAgentShare'            = $CustomModuleVersioninAgentShare
                'AXDatabaseRestoreDate'                      = $AXDatabaseRestoreDate
                'AXDatabaseCreationDate'                     = $AXDatabaseCreationDate
                'AXDatabaseBackupStartDate'                  = $AXDatabaseBackupStartDate
                'AXDatabaseBackupFileUsedForRestore'         = $AXDatabaseBackupFileUsedForRestore
                'CustomModuleVersionFullPreppedinAgentShare' = $CustomModuleVersionFullPreppedinAgentShare
                'DBSyncStatus'                               = $DBSyncStatus
                'DBSyncTimeStamp'                            = $DBSyncTimeStamp
                'DBSyncServerWithLatestLog'                  = $ServerWithLatestLog 
                'ConfigurationModeEnabledDisabled'           = $ConfigurationModeEnabledDisabled
                'DeploymentAssetIDinWPFolder'                = $DeploymentAssetIDinWPFolder
                'OrchestratorJobRunBookState'                = $OrchestratorJobRunBookState
                'OrchestratorJobState'                       = $OrchestratorJobState
                'D365FOLBDAdminEnvironmentType'              = $EnvironmentType
                'ManagementReporterServers'                  = $ManagementReporterServerName 
                'SSRSClusterServerNames'                     = $SSRSClusterServerNames
                'RunningAXCodeFolder'                        = $RunningAXCodeFolder 
                'AggregatedSFState'                          = $AggregatedSFState
                'NumberOfAppsinServicefabric'                = $NumberOfAppsinServicefabric
                'LastOrchJobId'                              = $LastOrchJobId
                'LastRunbookTaskId'                          = $LastRunbookTaskId
                'ComponentsinSetupModule'                    = $componentsinsetupmodule
                'LCSProjectID'                               = $LCSProjectID 
                'LCSEnvironmentURL'                          = $LCSEnvironmentURL
                'SFExplorerURL'                              = $SFExplorerURL
                'CustomModuleName'                           = $CustomModuleName
                'LastFullyPreppedCustomModuleAsset'          = $LastFullyPreppedCustomModuleAsset
                'ADFSIdentifier'                             = $ADFSIdentifier
                "FoundNewPreppedAsset"                       = $NewPreppedAsset
                'RunningAXCodeFolderLastWriteTime'           = $RunningAXCodeFolderLastWriteTime
                'LastRunbookName'                            = $LastRunbookName
            }

            $certlist = ('SFClientCertificate', 'SFServerCertificate', 'DataEncryptionCertificate', 'DataSigningCertificate', 'SessionAuthenticationCertificate', 'SharedAccessSMBCertificate', 'LocalAgentCertificate', 'DataEnciphermentCertificate', 'FinancialReportingCertificate', 'ReportingSSRSCertificate', 'DatabaseEncryptionCertificates')
            $CertificateExpirationHash = @{}
            if ($HighLevelOnly) {
                if ($messagecount -eq 0) {
                    Write-PSFMessage -Level Verbose -Message "High Level Only will not connect to service fabric"
                    $messagecount = $messagecount + 1
                }
            }
            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 'DatabaseEncryptionCertificates' -and !$certexpiration) {
                                try {
                                    foreach ($DatabaseClusterServerName in $DatabaseClusterServerNames) {
                                        if (!$certexpiration -and $value) {
                                            $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 -and $value) {
                                            $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\CurrentUser\my | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $DatabaseClusterServerName -ArgumentList $value -ErrorAction Stop
                                        }
                                        if (!$certexpiration -and $value) {
                                            $certexpiration = invoke-command -scriptblock { param($value) $(Get-ChildItem Cert:\LocalMachine\Root | Where-Object { $_.Thumbprint -eq "$value" }).NotAfter } -ComputerName $AXSFConfigServerName -ArgumentList $value -ErrorAction Stop
                                        }
                                    }
                                }
                                catch {
                                    Write-PSFMessage -Level Warning "Warning: Issue grabbing DatabaseEncryptionCertificate $value information. $_"
                                }
                            }
                            if ($certexpiration) {
                                
                                Write-PSFMessage -Level Verbose -Message "$value expires at $certexpiration"
                            }
                            else {
                                if ($value -eq 'DatabaseEncryptionCertificate' -or $value -eq '') {

                                }
                                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"
                        if ($name -eq "DatabaseEncryptionCertificate" -or $name -eq 'DataEnciphermentCertificate') {
                            Write-PSFMessage -Level Warning -Message "Note: Expired Certificate $name is not dynamically pulled so this could be a false negative"
                        }
                    }
                    $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
            ##Sends Custom Object to Pipeline
            if ($SFModuleSession) {
                Remove-PSSession -Session $SFModuleSession  
            }
            [PSCustomObject] $FinalOutput
        }
    }
    
    END {
        if ($ConfigExportToFile) {
            $FinalOutput | Export-Clixml -Path $ConfigExportToFile
        }
        if ($SFModuleSession) {
            Remove-PSSession -Session $SFModuleSession  
        }
    }
}

function Get-D365LBDConfigTemplate {
    <# TODO: Need to rethink this command
    .SYNOPSIS
   #>

    [CmdletBinding()]
    [alias("Get-D365ConfigTemplate")]
    param ([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [Parameter(ParameterSetName = 'InfrastructurePath',
            ValueFromPipeline = $True)]
        [string]$infrastructurescriptspath,
        [switch]$CreateCopy
    )
    BEGIN {
    } 
    PROCESS {
        if (!$Config -and !$infrastructurescriptspath) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        if ((!$Config -or $Config.OrchestratorServerNames.Count -eq 0) -and !$infrastructurescriptspath) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        $path = Join-Path $infrastructurescriptspath -ChildPath "Configtemplate.xml"
        [xml]$Configtemplatexml = get-content $path
        $Certs = $Configtemplatexml.Config.Certificates.Certificate
        foreach ($Cert in $Certs) {
            $parent = $Cert.ParentNode
            $CertNameinConfig = $parent.Certificate | Where-Object { $_.Thumbprint -eq $Cert.Thumbprint }
            $CertName = $CertNameinConfig.Name
            Write-PSFMessage -Level VeryVerbose -Message "Looking for $CertName with a thumbprint of $Cert"
            $CertinStore = Get-ChildItem "Cert:\Currentuser\My" | Where-Object { $_.Thumbprint -eq $Cert.Thumbprint }
            if (!$CertinStore) {
                Write-PSFMessage -Level VeryVerbose "Can't find Cert $Cert in CurrentUser Checking local machine"
                $CertinStore = Get-ChildItem "Cert:\LocalMachine\My" | Where-Object { $_.Thumbprint -eq $Cert.Thumbprint }
            }
            if ($CertinStore) {
                if ($CertinStore.NotAfter -lt $(get-date)) {
                    Write-PSFMessage -Level Warning -Message "$CertName with Thumbprint $($Cert.Thumbprint) is expired! $($Cert.PSPath)"
                }
                $CertinStore | Select-Object FriendlyName, Thumbprint, NotAfter
            }
            else {
                $parent = $Cert.ParentNode
                $parent.Cert
                Write-PSFMessage -Level VeryVerbose "Warning: Can't find the Thumbprint $Cert on specific machine for $CertName"
            }
        }
        IF ($Createcopy) {
            ##Create Archive folder inside of config template
            If (!(Test-path $infrastructurescriptspath/Archive)) {
                New-Item -ItemType Directory -Force -Path $infrastructurescriptspath/Archive
            }
            $name = "Config$((Get-Date).ToString('yyyy-MM-dd')).xml"
            Copy-Item $path -Destination "$infrastructurescriptspath/Archive/$name"
        }
    }
    END {
    }
}

function Get-D365LBDDBEvents {
    <#
    .SYNOPSIS
   Checks the event viewer of the for the latest Database Synchronization events.
   .DESCRIPTION
   Checks the event viewer of the for the latest Database Synchronization events.
   .EXAMPLE
   Get-D365LBDDBEvents
   Gets the latest Database Synchronization events on the application servers on the local machines environment
   .EXAMPLE
    Get-D365LBDDBEvents -ComputerName "LBDServerName" -verbose
   Gets the latest Database Synchronization events on the application servers on the specified machines environment
    .EXAMPLE
    $config = get-d365Config
    Get-D365DBEvents -config $config -numberofevents 3
    Gets the latest Database Synchronization events on the application servers on the specified configuration's environment
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER NumberofEvents
   Integer
   Number of Events to be pulled defaulted to 20 (suggest grabbing less for reading easy)
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   #>

    [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,
        [Parameter(ValueFromPipeline = $True)]
        [psobject]$Config,
        [string]$OnlyThisDBServer
    )
    BEGIN {
    } 
    PROCESS {
        if ($OnlyThisDBServer) {
            $events = Get-WinEvent -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -maxevents $NumberofEvents -computername $OnlyThisDBServer | 
            ForEach-Object -Process { `
                    New-Object -TypeName PSObject -Property `
                @{'MachineName'        = $OnlyThisDBServer ;
                    '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;
                }
                $SyncStatusFound = $false
                foreach ($event in $events) {
                    if ((($event.message -contains "Table synchronization failed.") -or ($event.message -contains "Database Synchronize Succeeded.")) -and $SyncStatusFound -eq $false) {
                        if ($event.message -contains "Table synchronization failed.") {
                            Write-PSFMessage -Message "Found a DB Sync Failure $($event.ServerWithLatestLog) ($($event.TimeCreated)" -Level Verbose
                        }
                        if ($event.message -contains "Database Synchronize Succeeded.") {
                            Write-PSFMessage -Message "Found a DB Sync Success $($event.ServerWithLatestLog) ($($event.TimeCreated)" -Level Verbose
                        }
                        $SyncStatusFound = $true
                    }
                }        
            }
        }
        else {
            if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
                Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
            }
    
            Foreach ($AXSFServerName in $config.AXSFServerNames) {
                try {
                    Write-PSFMessage -Level Verbose -Message "Reaching out to $AXSFServerName to look for DB logs"
                    $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 database sync events 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;
                }
                $SyncStatusFound = $false
                foreach ($event in $events) {
                    if ((($event.message -contains "Table synchronization failed.") -or ($event.message -contains "Database Synchronize Succeeded.")) -and $SyncStatusFound -eq $false) {
                        if ($event.message -contains "Table synchronization failed.") {
                            Write-PSFMessage -Message "Found a DB Sync Failure $($event.ServerWithLatestLog) ($($event.TimeCreated)" -Level Verbose
                        }
                        if ($event.message -contains "Database Synchronize Succeeded.") {
                            Write-PSFMessage -Message "Found a DB Sync Success $($event.ServerWithLatestLog) ($($event.TimeCreated)" -Level Verbose
                        }
                        $SyncStatusFound = $true
                    }
                }        
            }
        }
        $events
    }
    END {
    }
}

function Get-D365LBDDependencyHealth {
    <#
    .SYNOPSIS
   Checks and validates the dependencies configured in the AdditionalEnvironmentDetails.xml
   .DESCRIPTION
    Checks and validates the dependencies configured in the AdditionalEnvironmentDetails.xml This can check web addresses, services running, processes open, and databases being accessible.
    This is recommended to be ran from the environment itself as some dependencies are better ran from the required environment.
   .EXAMPLE
    Get-D365LBDDependencyHealth
   Checks and validates the dependencies configured in the AdditionalEnvironmentDetails.xml on the local server's environment
   .EXAMPLE
   Get-D365LBDDependencyHealth -config $Config
   Checks and validates the dependencies configured in the AdditionalEnvironmentDetails.xml on the defined configuration's environment
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   .PARAMETER CustomModuleName
   optional string
   The name of the custom module you will be using to capture the version number
   .PARAMETER WebsiteChecksOnly
   switch
   If you want to only check the website dependencies
   .PARAMETER SendAlertIfIssue
    switch
   If you want to only to send alerts when there is a found issue with a dependency
   .PARAMETER SMTPServer
   string
   Email smtp server to email the alerts if issue (that switch must be on as well)
   .PARAMETER MSTeamsURI
   string
   MSTeams URI smtp server to email the alerts if issue (that switch must be on as well)
   #>

    [alias("Get-D365DependencyHealth")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [string]$CustomModuleName,
        [switch]$WebsiteChecksOnly,
        [switch]$SendAlertIfIssue,
        [string]$SMTPServer,
        [string]$MSTeamsURI
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            if ($CustomModuleName) {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName -highlevelonly
            }
            else {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -highlevelonly
            }
        }
        $AgentShareLocation = $config.AgentShareLocation 
        $OutputList = @()
        $EnvironmentAdditionalConfig = get-childitem  "$AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml"
        if (!$EnvironmentAdditionalConfig) {
            Stop-PSFFunction -Message "Error: AdditionalEnvironmentDetails.xml not configured at $AgentShareLocation\scripts\D365FOLBDAdmin" -EnableException $true -FunctionName $_
        }
        [xml]$EnvironmentAdditionalConfigXML = get-content $EnvironmentAdditionalConfig.FullName

        ##checking WebURLS
        $EnvironmentAdditionalConfigXML.D365LBDEnvironment.Dependencies.CustomWebURLDependencies.CustomWebURL | ForEach-Object -Process { 
            $Note = $_.Note
            if ($_.Type.'#text'.Trim() -eq 'Basic') {
                ##Basic WebURL Start
                $results = Invoke-WebRequest -Uri $_.uri -UseBasicParsing
                if ($results.statusCode -eq 200 -or $results.statusCode -eq 203 -or $results.statusCode -eq 204 ) {
                    $Output = New-Object -TypeName PSObject -Property `
                    @{'Source'      = $env:COMPUTERNAME ;
                        'Name'      = $_.uri ;
                        'State'     = "Operational";
                        'ExtraInfo' = $results.Statuscode
                        'Group'     = 'Web Service/Page Web Basic'
                    }
                    $OutputList += $Output
                }
                else {
                    $Output += New-Object -TypeName PSObject -Property `
                    @{'Source'      = $env:COMPUTERNAME ;
                        'Name'      = $_.uri ;
                        'State'     = "Down";
                        'ExtraInfo' = $results.Statuscode
                        'Group'     = 'Web Service/Page Web Basic'
                    }
                }
            }
            else {
                ##Advanced Weburl start
                $childnodes = $($_.AdvancedCustomSuccessResponse | Select-Object childnodes).childnodes
                $properties = $childnodes | Get-Member -MemberType Property
                $propertiestocheck = $properties.Name
                [int]$countofproperties = $propertiestocheck.count
                $results = Invoke-RestMethod -Uri $_.uri -UseBasicParsing
                if ($countofproperties -eq 0 -or $countofproperties -eq 1 ) {
                    ##only one or 0 child items start
                    $diff = Compare-Object $results -DifferenceObject $($childnodes.'#text'.Trim())
                    if ($diff) {
                        Write-PSFMessage -message "Found differences $diff" -Level VeryVerbose
                        $Output = New-Object -TypeName PSObject -Property `
                        @{'Source'      = $env:COMPUTERNAME ;
                            'Name'      = $_.uri ;
                            'State'     = "Down";
                            'ExtraInfo' = $Note
                            'Group'     = 'Web Service/Page Web Advanced'
                        }
                        $OutputList += $Output
                    }
                    else {
                        ##no differences found so success
                        $Output = New-Object -TypeName PSObject -Property `
                        @{'Source'      = $env:COMPUTERNAME ;
                            'Name'      = $_.uri ;
                            'State'     = "Operational";
                            'ExtraInfo' = $Note
                            'Group'     = 'Web Service/Page Web Advanced'
                        }
                        $OutputList += $Output
                    }  ##only one or 0 child items end
                }##multiple items to check start
                else {
                    foreach ($property in $propertiestocheck) {
                        $diff = compare-object $results.data.$property -DifferenceObject $childnodes.$property.trim()
                        if ($diff) {
                            Write-PSFMessage -message "Found differences $diff" -Level VeryVerbose
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $env:COMPUTERNAME ;
                                'Name'      = $_.uri ;
                                'State'     = "Down";
                                'ExtraInfo' = $results.Statuscode
                                'Group'     = 'Web Service/Page Web Advanced'
                            }
                            $OutputList += $Output
                        }
                        else {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $env:COMPUTERNAME ;
                                'Name'      = $_.uri ;
                                'State'     = "Operational";
                                'ExtraInfo' = $results.Statuscode;
                                'Group'     = 'Web Service/Page Web Advanced'
                            }
                            $OutputList += $Output
                        }
                    }
                } 
            } ## Advanced Weburl End
        }##End of All Custom WebURL
        if ($WebsiteChecksOnly) {
            Write-PSFMessage -Level VeryVerbose -Message "Only Checking Websites"
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Checking for server dependencies"
            $servicestovalidate = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.Dependencies.ServerDependencies.Dependency | Where-Object { $_.Type.'#text'.Trim() -eq "service" }
            foreach ($servicetovalidate in $servicestovalidate) {
                ##Services Start
                if ($servicestovalidate.locationType.'#text'.Trim() -eq 'AXSF') {
                    foreach ($AXSfServerName in $Config.AXSFServerNames) {
                        $servicetovalidateName = $servicetovalidate.Name
                        $results = Invoke-Command -ComputerName $AXSfServerName -ScriptBlock { Get-service $Using:servicetovalidateName } 
                        if ($results.Status -eq "Running") {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $AXSfServerName ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Operational";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'AXSFService'
                                }
                                $OutputList += $Output
                            }
                        } ##Operational start
                        else {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $AXSfServerName ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Down";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'AXSFService'
                                }
                                $OutputList += $Output
                            }
                        }##Failure end
                    }
                }
                if ($servicestovalidate.locationType.'#text'.Trim() -eq 'SSRS') {
                    foreach ($SSRSClusterServerName in $Config.SSRSClusterServerNames) {
                        $results = Invoke-Command -ComputerName $SSRSClusterServerName -ScriptBlock { Get-service $Using:servicetovalidateName } 
                        if ($results.Status -eq "Running") {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $SSRSClusterServerName ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Operational";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'SSRSService'
                                }
                                $OutputList += $Output
                            }
                        } ##Operational start
                        else {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $SSRSClusterServerName ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Down";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'SSRSService'
                                }
                                $OutputList += $Output
                            }
                        }##Failure end
                    }
                }
                if ($servicestovalidate.locationType.'#text'.Trim() -eq 'SQLDB') {
                    foreach ($DatabaseClusterServerName in $config.DatabaseClusterServerNames) {
                        $results = Invoke-Command -ComputerName $DatabaseClusterServerName -ScriptBlock { Get-service $Using:servicetovalidateName } 
                        if ($results.Status -eq "Running") {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $DatabaseClusterServerName ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Operational";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'SQLDBService'
                                }
                                $OutputList += $Output
                            }
                        } ##Operational start
                        else {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $DatabaseClusterServerName ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Down";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'SQLDBService'
                                }
                                $OutputList += $Output
                            }
                        }##Failure end
                    }
                }
                if ($servicestovalidate.locationType.'#text'.Trim() -eq 'ManagementReporter') {
                    foreach ($ManagementReporterServer in $ManagementReporterServers) {
                        $results = Invoke-Command -ComputerName $ManagementReporterServer -ScriptBlock { Get-service $Using:servicetovalidateName } 
                        if ($results.Status -eq "Running") {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $ManagementReporterServer ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Operational";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'ManagementReporterService'
                                }
                                $OutputList += $Output
                            }
                        } ##Operational start
                        else {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $ManagementReporterServer ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Down";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'ManagementReporterService'
                                }
                                $OutputList += $Output
                            }
                        }##Failure end
                    }
                }
                if ($servicestovalidate.locationType.'#text'.Trim() -eq 'All') {
                    foreach ($AppServer in $Config.AllAppServerList) {
                        $results = Invoke-Command -ComputerName $AppServer -ScriptBlock { Get-service $Using:servicetovalidateName } 
                        if ($results.Status -eq "Running") {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $AppServer ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Operational";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'AllServersService'
                                }
                                $OutputList += $Output
                            }
                        } ##Operational start
                        else {
                            $results | ForEach-Object -Process { `
                                    $Output = New-Object -TypeName PSObject -Property `
                                @{'Source'      = $AppServer ;
                                    'Name'      = "$servicetovalidateName"; 
                                    'State'     = "Down";
                                    'ExtraInfo' = $_.StartType;
                                    'Group'     = 'AllServersService'
                                }
                                $OutputList += $Output
                            }
                        }##Failure end
                    }
                }
            }##Services End

            $processestovalidate = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.Dependencies.ServerDependencies.Dependency | Where-Object { $_.Type.'#text'.Trim() -eq "process" }
            ##Process
            foreach ($processtovalidate in $processestovalidate) {
                $ProcessName = $processtovalidate.name
                if ($processtovalidate.locationType.'#text'.Trim() -eq 'AXSF') {
                    foreach ($AXSfServerName in $Config.AXSFServerNames) {
                        $results = Invoke-Command -ComputerName $AXSfServerName -ScriptBlock { Get-process | where-object { $_.Name -eq $Using:ProcessName } | Select-Object -First 1 } 
                        if ($results) {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $AXSfServerName ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Operational";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'AXServerProcess'
                            }
                        }
                        else {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $AXSfServerName ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Down";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'AXServerProcess'
                            }
                        }
                        $OutputList += $Output
                    }
                }
            
                if ($processtovalidate.locationType.'#text'.Trim() -eq 'SSRS') {
                    foreach ($SSRSClusterServerName in $Config.SSRSClusterServerNames) {
                        $results = Invoke-Command -ComputerName $SSRSClusterServerName -ScriptBlock { Get-process | where-object { $_.Name -eq $Using:ProcessName }  | Select-Object -First 1 } 
                        if ($results) {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $SSRSClusterServerName ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Operational";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'SSRSServerProcess'
                            }
                        }
                        else {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $SSRSClusterServerName ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Down";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = '$SSRSServerProcess'
                            }
                        }
                        $OutputList += $Output
                    }
                }
                if ($processtovalidate.locationType.'#text'.Trim() -eq 'SQLDB') {
                    foreach ($DatabaseClusterServerName in $config.DatabaseClusterServerNames) {
                        $results = Invoke-Command -ComputerName $DatabaseClusterServerName -ScriptBlock { Get-process | where-object { $_.Name -eq $Using:ProcessName } | Select-Object -First 1 } 
                        if ($results) {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $DatabaseClusterServerName ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Operational";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'DatabaseClusterServerProcess'
                            }
                        }
                        else {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $DatabaseClusterServerName ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Down";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'DatabaseClusterServerProcess'
                            }
                        }
                        $OutputList += $Output
                    }
                }
            
                if ($processtovalidate.locationType.'#text'.Trim() -eq 'ManagementReporter') {
                    foreach ($ManagementReporterServer in $ManagementReporterServers) {
                        $results = Invoke-Command -ComputerName $ManagementReporterServer -ScriptBlock { Get-process | where-object { $_.Name -eq $Using:ProcessName } | Select-Object -First 1 } 
                        if ($results) {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $ManagementReporterServer ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Operational";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'ManagementReporterProcess'
                            }
                        }
                        else {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $ManagementReporterServer ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Down";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'ManagementReporterProcess'
                            }
                        }
                        $OutputList += $Output
                    } 
                }
                if ($processtovalidate.locationType.'#text'.Trim() -eq 'All') {
                    foreach ($AppServer in $Config.AllAppServerList) {
                        $results = Invoke-Command -ComputerName $AppServer -ScriptBlock { Get-process | where-object { $_.Name -eq $Using:ProcessName }  | Select-Object -First 1 } 
                        if ($results) {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $AppServer ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Operational";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'AllProcess'
                            }
                        }
                        else {
                            $Output = New-Object -TypeName PSObject -Property `
                            @{'Source'      = $AppServer ;
                                'Name'      = "$ProcessName"; 
                                'State'     = "Down";
                                'ExtraInfo' = $_.StartType;
                                'Group'     = 'AllProcess'
                            }
                        }
                        $OutputList += $Output
                    }
                }
            }
            ##Database
        }
        $FoundIssue = $false
        foreach ($scanneditem in $Output) {
            if ($scanneditem.State -eq "Down") {
                Write-PSFMessage -Message "Found an item down: $Scanneditem" -Level VeryVerbose
                $FoundIssue = $True
                if ($SendAlertIfIssue) {
                    $EnvironmentOwnerEmail = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.EnvironmentAdditionalConfig.EnvironmentOwnerEmail
                    if ($SMTPServer) {
                        Write-PSFMessage -Level VeryVerbose -Message "Sending email to $EnvironmentOwnerEmail using $SMTPServer"
                        Send-MailMessage -to "$EnvironmentOwnerEmail" -Body "$scanneditem is down for $($Config.LCSEnvironmentName) " -Verbose -SmtpServer "$SMTPServer" -Subject "D365 Found issue with $($Config.LCSEnvironmentName)"
                    }
                    else {
                        Write-PSFMessage -Level VeryVerbose -Message "WARNING: Configure SMTP Server to send emails"

                    }
                    if ($MSTeamsURI) {
                        Send-D365LBDUpdateMSTeams -messageType "StatusReport" -MSTeamsURI "$MSTeamsURI"
                    }
                    else {
                        $MSTEAMSURLS = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.Communication.Webhooks.Webhook | Where-Object { $_.type.'#text'.trim() -eq "MSTEAMS" } | select ChannelWebHookURL
                        foreach ($MSTEAMSURL in $MSTEAMSURLS) {
                            Send-D365LBDUpdateMSTeams -messageType "StatusReport" -MSTeamsURI "$MSTEAMSURL" -config $Config
                        }
                    }
                }
            }
        }
        [PSCustomObject] $OutputList
    }
    END {
        if ($SFModuleSession) {
            Remove-PSSession -Session $SFModuleSession  
        }
    }
}



function Get-D365LBDEnvironmentHealth {
    <#
   .SYNOPSIS
   Checks and validates the health of the D365 environment.
  .DESCRIPTION
    Checks and validates the health of the D365 environment. This includes checking for AXSF endpoints, D365 system databases (including ssrs), Certificates being valid and hard drive space.
  .EXAMPLE
    Get-D365LBDEnvironmentHealth
   Checks and validates the health of the D365 environment on the local machines environment
  .EXAMPLE
  $config = get-d365Config
   Get-D365LBDEnvironmentHealth -config $config
   Checks and validates the health of the D365 environment on the specified configurations environment
  .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   .PARAMETER CustomModuleName
   optional string
   The name of the custom module you will be using to capture the version number
   .PARAMETER CheckForHardDriveDetails
   switch
   When gathering the health of the environment to iterate through each server to check for hard drives being full
   .PARAMETER HDWarningValue
   integer
   Value in percentage that would be considered a warning in free space. Example if set to 5 if hard drive is less than 5% free it would result in a warning. if not defined will try using additional config.
   .PARAMETER HDErrorValue
   integer
   Value in percentage that would be considered a error in free space. Example if set to 2 if hard drive is less than 2% free it would result in a error. if not defined will try using additional config.
   .PARAMETER CertWarningValue
   integer
   Value in days that would be considered a warning in days until the certificate is no longer valid. Example if set to 30 the cert expires in less than 30 days it would result in a warning. Default of 30.
   .PARAMETER CertErrorValue
   integer
   Value in days that would be considered a error in days until the certificate is no longer valid. Example if set to 5 the cert expires in less than 5 days it would result in a error. Default of 5.
  #>

    [alias("Get-D365EnvironmentHealth")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [int]$Timeout = 120,
        [psobject]$Config,
        [string]$CustomModuleName,
        [switch]$CheckForHardDriveDetails,
        [int]$HDWarningValue, ## integer that checks percentage
        [int]$HDErrorValue, ## integer that checks percentage
        [int]$CertWarningValue = 30, ##in Days
        [int]$CertErrorValue = 5 ## in Days
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            if ($CustomModuleName) {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName
            }
            else {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName 
            }
        }
        $OutputList = @()
        $ReportServerServerName = $Config.ReportServerServerName
        $AXDatabaseServer = $Config.AXDatabaseServer
        $SourceAXSFServer = $Config.SourceAXSFServer
         
        $AssemblyList = "Microsoft.SqlServer.Management.Common", "Microsoft.SqlServer.Smo", "Microsoft.SqlServer.Management.Smo"
        foreach ($Assembly in $AssemblyList) {
            $AssemblyLoad = [Reflection.Assembly]::LoadWithPartialName($Assembly) 
        }
        if (!$ReportServerServerName) {
            $ReportServerServerName = $using:ReportServerServerName
        }
        $SQLSSRSServer = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $ReportServerServerName 
        Write-PSFMessage -Level Verbose -Message "Connecting to $ReportServerServerName for SSRS Database and its system dbs"
        $SystemDatabasesWithIssues = 0
        $SystemDatabasesAccessible = 0

        if ($SQLSSRSServer) {
            Write-PSFMessage -Level VeryVerbose -Message "Connected to $SQLSSRSServer for SSRS Database and its system dbs $($SQLSSRSServer.Databases)"
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Having issues connecting to $SQLSSRSServer for SSRS Database and its system dbs"
        }
        try {
            foreach ($database in $SQLSSRSServer.Databases) {
            }
        }
        catch {
            if ($_.Exception -like "*Failed to connect to server *") {
                Write-Warning -Message "Can't Verify if SQL Server $ReportServerServerName is up because can't connect. Check permissions "
                $CantConnect = 'True'
            }
        }
        if ($CantConnect -eq 'True') {
            $whoami = whoami
            $Properties = @{'Name' = "SSRSSystemDatabasesDatabase"
                'Details'          = "$whoami can't connect to the databases. Check permissions"
                'State'            = "Down" 
                'ExtraInfo'        = ""
                'Source'           = $ReportServerServerName
                'Group'            = 'Database'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output
        }
        else {
            foreach ($database in $SQLSSRSServer.Databases) {
                switch ($database) {
                    { @("[model]", "[master]", "[msdb]", "[tempdb]") -contains $_ } {
                        if ($database.IsAccessible) {
                            $SystemDatabasesAccessible = $SystemDatabasesAccessible + 1
                        }
                        else {
                            $SystemDatabasesWithIssues = $SystemDatabasesWithIssues + 1
                        }
                    }
                    ("[DynamicsAxReportServer]", "[ReportServer]") {
                        switch ($database.IsAccessible) {
                            "True" { $dbstatus = "Operational" }
                            "False" { $dbstatus = "Down" }
                        }
                        $Properties = @{'Name' = "SSRSDatabase"
                            'Details'          = $database.name
                            'State'            = "$dbstatus" 
                            'Source'           = $ReportServerServerName
                        }
                        $Output = New-Object -TypeName psobject -Property $Properties
                        $OutputList += $Output
                    }
                    ("[DynamicsAxReportServerTempDB]", "[ReportServerTempDB]") {
                        switch ($database.IsAccessible) {
                            "True" { $dbstatus = "Operational" }
                            "False" { $dbstatus = "Down" }
                        }
                        $Properties = @{'Name' = "SSRSTempDBDatabase"
                            'Details'          = $database.name
                            'State'            = "$dbstatus" 
                            'ExtraInfo'        = ""
                            'Source'           = $ReportServerServerName
                            'Group'            = 'Database'
                        }
                        $Output = New-Object -TypeName psobject -Property $Properties
                        $OutputList += $Output
                    }
                    Default {}
                }
            }
            if ($SystemDatabasesWithIssues -eq 0) {
                $Properties = @{'Name' = "SSRSSystemDatabasesDatabase"
                    'Details'          = "$SystemDatabasesAccessible databases are accessible"
                    'State'            = "Operational" 
                    'ExtraInfo'        = ""
                    'Source'           = $ReportServerServerName
                    'Group'            = 'Database'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "SSRSSystemDatabasesDatabase"
                    'Details'          = "$SystemDatabasesAccessible databases are accessible. $SystemDatabasesWithIssues are not accessible"
                    'State'            = "Down" 
                    'ExtraInfo'        = ""
                    'Source'           = $ReportServerServerName
                    'Group'            = 'Database'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }

        
        ##DB AX
        $CantConnect = 'False'
        if (!$AXDatabaseServer) {
            $AXDatabaseServer = $using:AXDatabaseServer
        }
        $AXDatabaseServerConnection = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $AXDatabaseServer
        Write-PSFMessage -Level Verbose -Message "Connecting to $AXDatabaseServer for AXDB Database and its system dbs"
        $SystemDatabasesWithIssues = 0
        $SystemDatabasesAccessible = 0
        if ($AXDatabaseServerConnection) {
            Write-PSFMessage -Level VeryVerbose -Message "Connected to $AXDatabaseServerConnection for AXDB Database and its system dbs $($AXDatabaseServerConnection.Databases)"
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Having issues connecting to $AXDatabaseServerConnection for AXDB Database and its system dbs"
        }

        try {
            foreach ($database in $AXDatabaseServerConnection.Databases) {
            }
        }
        catch {
            if ($_.Exception -like "*Failed to connect to server *") {
                Write-Warning -Message "Can't Verify if SQL Server $AXDatabaseServer is up because can't connect. Check permissions "
                $CantConnect = 'True'
            }
        }
        if ($CantConnect -eq 'True') {
            $whoami = whoami
            $Properties = @{'Name' = "AXDBSystemDatabasesDatabase"
                'Details'          = "$whoami can't connect to the databases. Check permissions"
                'State'            = "Down" 
                'ExtraInfo'        = ""
                'Source'           = $AXDatabaseServer
                'Group'            = 'Database'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output
        }

        foreach ($database in $AXDatabaseServerConnection.Databases) {
            switch ($database) {
                { @("[model]", "[master]", "[msdb]", "[tempdb]") -contains $_ } {
                    if ($database.IsAccessible) {
                        $SystemDatabasesAccessible = $SystemDatabasesAccessible + 1
                    }
                    else {
                        $SystemDatabasesWithIssues = $SystemDatabasesWithIssues + 1
                    }
                }
                "[AXDB]" {
                    switch ($database.IsAccessible) {
                        "True" { $dbstatus = "Operational" }
                        "False" { $dbstatus = "Down" }
                    }
                    $Properties = @{'Name' = "AXDatabase"
                        'Details'          = $database.name
                        'State'            = "$dbstatus" 
                        'ExtraInfo'        = ""
                        'Source'           = $AXDatabaseServer
                        'Group'            = 'Database'
                    }
                    $Output = New-Object -TypeName psobject -Property $Properties
                    $OutputList += $Output
                }
                Default {}
            }
        }
        if ($SystemDatabasesWithIssues -eq 0) {
            $Properties = @{'Name' = "AXDBSystemDatabasesDatabase"
                'Details'          = "$SystemDatabasesAccessible databases are accessible"
                'State'            = "Operational" 
                'ExtraInfo'        = ""
                'Source'           = $AXDatabaseServer
                'Group'            = 'Database'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output
        }
        else {
            $Properties = @{'Name' = "AXDBSystemDatabasesDatabase"
                'Details'          = "$SystemDatabasesAccessible databases are accessible. $SystemDatabasesWithIssues are not accessible"
                'State'            = "Down" 
                'ExtraInfo'        = ""
                'Source'           = $AXDatabaseServer
                'Group'            = 'Database'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output
        }


        $AgentShareLocation = $config.AgentShareLocation
        $CheckedHardDrives = "false"
        $ServerswithHDIssues = @()
        if (test-path $AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml) {
            ##additional details start
            Write-PSFMessage -Level Verbose -Message "Found AdditionalEnvironmentDetails config"
 
            [xml]$XMLAdditionalConfig = Get-Content "$AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml"
            [string]$CheckForHardDriveDetails = $XMLAdditionalConfig.d365LBDEnvironment.Automation.CheckForHealthIssues.CheckAllHardDisks.Enabled
            if (!$HDErrorValue) {
                $HDErrorValue = $CheckForHardDriveDetails.HardDriveError
            }
            if (!$HDWarningValue) {
                $HDWarningValue = $CheckForHardDriveDetails.HardDriveWarning
            }
            
            $foundHardDrivewithIssue = $false
            if ($CheckForHardDriveDetails -eq "true") {
                $CheckedHardDrives = "true"
                ##check HD Start
                Write-PSFMessage -Message "Checking Hard drive free space" -Level Verbose
                foreach ($ApplicationServer in $config.AllAppServerList.ComputerName) {
                    $HardDrives = Get-WmiObject -Class "Win32_LogicalDisk" -Namespace "root\CIMV2" -Filter "DriveType = '3'" -ComputerName $ApplicationServer
                    if (!$HardDrives) {
                        Write-PSFMessage -Level Verbose -Message " Having trouble accessing drives on $ApplicationServer"
                    }
                    foreach ($HardDrive in $HardDrives) {
                        $FreeSpace = (($HardDrive.freespace / $HardDrive.size) * 100)
                        Write-PSFMessage -Level Verbose -Message " $ApplicationServer - $($HardDrive.DeviceID) has $FreeSpace %"
                        if (!$HDErrorValue) {
                            $HDErrorValue = 2
                        }
                        if ($FreeSpace -lt $HDErrorValue) {
                            Write-PSFMessage -Message "ERROR: $($HardDrive.DeviceId) on $ApplicationServer has only $freespace percentage" -Level Warning
                            $Properties = @{'Name' = "Hard Disk Space"
                                'Details'          = $HardDrive.DeviceId
                                'State'            = "Down" 
                                'ExtraInfo'        = "Free Space Percentage: $freespace"
                                'Source'           = $ApplicationServer
                            }
                            $Output = New-Object -TypeName psobject -Property $Properties
                            $OutputList += $Output
                            $foundHardDrivewithIssue = $true
                            $ServerswithHDIssues += "$ApplicationServer"

                        }
                        elseif ($FreeSpace -lt $HDWarningValue) {
                            Write-PSFMessage -Message "WARNING: $($HardDrive.DeviceId) on $ApplicationServer has only $freespace percentage" -Level Warning
                        }
                        else { 
                            Write-PSFMessage -Message  "VERBOSE: $($HardDrive.DeviceId) on $ApplicationServer has only $freespace percentage" -Level VeryVerbose
                        }
                    }
                }
                if ($foundHardDrivewithIssue -eq $false) {
                    $Properties = @{'Name' = "Hard Disk Space"
                        'Details'          = $config.AllAppServerList
                        'State'            = "Operational" 
                        'ExtraInfo'        = ""
                        'Source'           = $config.AllAppServerList
                        'Group'            = 'OS'
                    }
                    $Output = New-Object -TypeName psobject -Property $Properties
                    $OutputList += $Output
                }
            }##Check HD end
        }##additional details end
        else {
            Write-PSFMessage -Message "Warning: Can't find additional environment Config. Not needed but recommend making one" -level warning  
        }

        if ($CheckedHardDrives -eq "false" -and ($CheckForHardDriveDetails -eq $true)) {
            $foundHardDrivewithIssue = $false
            foreach ($ApplicationServer in $config.AllAppServerList.ComputerName) {
                $HardDrives = Get-WmiObject -Class "Win32_LogicalDisk" -Namespace "root\CIMV2" -Filter "DriveType = '3'" -ComputerName $ApplicationServer
                foreach ($HardDrive in $HardDrives) {
                    $FreeSpace = (($HardDrive.freespace / $HardDrive.size) * 100)
                    Write-PSFMessage -Level Verbose -Message "$ApplicationServer - $($HardDrive.DeviceID) has $FreeSpace %"
                    if (!$HDErrorValue) {
                        $HDErrorValue = 2
                    }
                    if ($FreeSpace -lt $HDErrorValue) {
                        Write-PSFMessage -Message "ERROR: $($HardDrive.DeviceId) on $ApplicationServer has only $freespace percentage" -Level Warning
                        $Properties = @{
                            'Source'    = $ApplicationServer ;
                            'Name'      = "Hard Disk Space"
                            'Details'   = $HardDrive.DeviceId
                            'State'     = "Down" 
                            'ExtraInfo' = "$ServerswithHDIssues";
                            'Group'     = 'OS'
                               
                        }
                        $Output = New-Object -TypeName psobject -Property $Properties
                        $OutputList += $Output
                        $foundHardDrivewithIssue = $true
                        $ServerswithHDIssues += "$ApplicationServer"
                    }
                    elseif ($FreeSpace -lt $HDWarningValue) {
                        Write-PSFMessage -Message "WARNING: $($HardDrive.DeviceId) on $ApplicationServer has only $freespace percentage" -Level Warning
                        $Properties = @{
                            'Source'    = $ApplicationServer ;
                            'Name'      = "Hard Disk Space"
                            'Details'   = $HardDrive.DeviceId
                            'State'     = "Operational" 
                            'ExtraInfo' = "$ServerswithHDIssues";
                            'Group'     = 'OS'
                               
                        }
                        $Output = New-Object -TypeName psobject -Property $Properties
                        $OutputList += $Output
                    }
                    else {
                        Write-PSFMessage -Message  "VERBOSE: $($HardDrive.DeviceId) on $ApplicationServer has only $freespace percentage" -Level VeryVerbose
                        $Properties = @{
                            'Source'    = $ApplicationServer ;
                            'Name'      = "Hard Disk Space"
                            'Details'   = $HardDrive.DeviceId
                            'State'     = "Operational" 
                            'ExtraInfo' = "$ServerswithHDIssues";
                            'Group'     = 'OS'
                               
                        }
                        $Output = New-Object -TypeName psobject -Property $Properties
                        $OutputList += $Output
                    }
                }
            }

            if ($foundHardDrivewithIssue -eq $true) {
                $issuelist = $OutputList | Where-Object { $_.Operational -eq "Down" -and $_.Name -eq "Hard Disk Space" }
                Write-PSFMessage -Level Error -Message "Error: Found Hard Drive Issues on $issuelist"
            }
        }##Check HD end

        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName
        }
        [int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                }
                Write-PSFMessage -Message "-ConnectionEndpoint $($config.SFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
                $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            } until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or (($($Config.OrchestratorServerNames).Count) -eq 0))
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
        }
        $TotalApplications = (Get-ServiceFabricApplication).Count
        $HealthyApps = (Get-ServiceFabricApplication | Where-Object { $_.HealthState -eq "OK" }).Count

        if ($TotalApplications -eq $HealthyApps) {
            Write-PSFMessage -Message "All Service Fabric Applications are healthy $HealthyApps / $TotalApplications" -Level VeryVerbose
            $Properties = @{'Name' = "ServiceFabricApplications"
                'Details'          = "Healthy: $HealthyApps / Total: $TotalApplications"
                'State'            = "Operational" 
                'ExtraInfo'        = "$TotalApplications"
                'Source'           = $OrchestratorServerName
                'Group'            = 'ServiceFabric'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output
        }
        else {
            $NotHealthyApps = Get-ServiceFabricApplication | Where-Object { $_.HealthState -ne "OK" }
            Write-PSFMessage -Message "Warning: Not all Service Fabric Applications are healthy $HealthyApps / $TotalApplications " -Level VeryVerbose
            Write-PSFMessage -Message "Issue App:" -Level VeryVerbose
            $HealthIssueString = ''
            foreach ($NotHealthyApp in $NotHealthyApps) {
                $HealthReport = Get-ServiceFabricApplicationHealth -ApplicationName $NotHealthyApp.ApplicationName
                Write-PSFMessage -Message "$HealthReport" -Level VeryVerbose
                $HealthIssueString = $HealthIssueString + "$($NotHealthyApp.ApplicationName) : " + "$($HealthReport.UnhealthyEvaluations)"
            }
            $Properties = @{'Name' = "ServiceFabricApplications"
                'Details'          = "Healthy: $HealthyApps / Total: $TotalApplications"
                'State'            = "Down" 
                'ExtraInfo'        = "$HealthIssueString"
                'Source'           = $OrchestratorServerName
                'Group'            = 'ServiceFabric'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output
        }
        
        $ServiceFabricPartitionIdForAXSF = $(get-servicefabricpartition -servicename 'fabric:/AXSF/AXService').PartitionId
        foreach ($node in $nodes) {
            $nodename = $node.Nodename
            $replicainstanceIdofnode = $(get-servicefabricreplica -partition $ServiceFabricPartitionIdForAXSF | Where-Object { $_.NodeName -eq "$NodeName" }).InstanceId
            $ReplicaDetails = Get-Servicefabricdeployedreplicadetail -nodename $nodename -partitionid $ServiceFabricPartitionIdForAXSF -ReplicaOrInstanceId $replicainstanceIdofnode -replicatordetail
            $endpoints = $ReplicaDetails.deployedservicereplicainstance.address | ConvertFrom-Json
            if ($endpoints.Endpoints )
            {
                $deployedinstancespecificguid = $($endpoints.Endpoints | Get-Member | Where-Object { $_.MemberType -eq "NoteProperty" }).Name
                Write-PSFMessage -Level VeryVerbose -Message "$NodeName is accessible via $httpsurl with a guid $deployedinstancespecificguid"
            }
            else{
                Write-PSFMessage -Level Warning -Message "$NodeName does not have AXService accessible"
            }
            $httpsurl = $endpoints.Endpoints.$deployedinstancespecificguid

            if ($httpsurl.Length -gt 3) {
                $Status = "Operational"
            }
            else {
                $Status = "Down"
            }
            $Properties = @{'Name' = "AXSFGUIDEndpoint"
                'Details'          = "$deployedinstancespecificguid"
                'State'            = "$Status" 
                'ExtraInfo'        = "$httpsurl"
                'Source'           = $NodeName 
                'Group'            = 'ServiceFabric'
            }
            $Output = New-Object -TypeName psobject -Property $Properties
            $OutputList += $Output
        }
        
        $CurrentDate = Get-Date
        $ErrorDateCerts = $CurrentDate.AddDays(-$CertErrorValue)
        $WarningDateCerts = $CurrentDate.AddDays(-$CertWarningValue)

        if ($Config.SessionAuthenticationCertificateExpiresAfter) {
            if ($Config.SessionAuthenticationCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthentication"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.SessionAuthenticationCertificateExpiresAfter)"
                    'Source'           = $Config.SessionAuthenticationCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.SessionAuthenticationCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthentication"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SessionAuthenticationCertificateExpiresAfter)"
                    'Source'           = $Config.SessionAuthenticationCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: SessionAuthentication is expiring soon $($Config.SessionAuthenticationCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthentication"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SessionAuthenticationCertificateExpiresAfter)"
                    'Source'           = $Config.SessionAuthenticationCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for SessionAuthenticationCertificate"
        }

        
        if ($Config.SFClientCertificateExpiresAfter) {
            if ($Config.SFClientCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SFClientCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.SFClientCertificateExpiresAfter)"
                    'Source'           = $Config.SFClientCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.SFClientCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthentication"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SFClientCertificateExpiresAfter)"
                    'Source'           = $Config.SFClientCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: SFClientCertificate is expiring soon $($Config.SFClientCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthentication"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SFClientCertificateExpiresAfter)"
                    'Source'           = $Config.SFClientCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for SFClientCertificate"
        }

        #SFServerCertificate

        if ($Config.SFServerCertificateExpiresAfter) {
            if ($Config.SFServerCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SFServerCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.SFServerCertificateExpiresAfter)"
                    'Source'           = $Config.SFServerCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.SFServerCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SFServerCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SFServerCertificateExpiresAfter)"
                    'Source'           = $Config.SFServerCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: SFServerCertificate is expiring soon $($Config.SFServerCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SFServerCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SFServerCertificateExpiresAfter)"
                    'Source'           = $Config.SFServerCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for SFServerCertificate"
        }


        if ($Config.DataEncryptionCertificateExpiresAfter) {
            if ($Config.DataEncryptionCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataEncryptionCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.DataEncryptionCertificateExpiresAfter)"
                    'Source'           = $Config.DataEncryptionCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.DataEncryptionCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataEncryptionCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.DataEncryptionCertificateExpiresAfter)"
                    'Source'           = $Config.DataEncryptionCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: DataEncryptionCertificate is expiring soon $($Config.DataEncryptionCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataEncryptionCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.DataEncryptionCertificateExpiresAfter)"
                    'Source'           = $Config.DataEncryptionCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for DataEncryptionCertificate"
        }
        if ($Config.DataSigningCertificateExpiresAfter) {
            if ($Config.DataSigningCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataSigningCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.DataSigningCertificateExpiresAfter)"
                    'Source'           = $Config.DataSigningCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.DataSigningCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataSigningCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.DataSigningCertificateExpiresAfter)"
                    'Source'           = $Config.DataSigningCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: DataSigningCertificate is expiring soon $($Config.DataSigningCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataSigningCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.DataSigningCertificateExpiresAfter)"
                    'Source'           = $Config.DataSigningCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for DataSigningCertificate"
        }

        if ($Config.SessionAuthenticationCertificateExpiresAfter) {
            if ($Config.SessionAuthenticationCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthenticationCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.SessionAuthenticationCertificateExpiresAfter)"
                    'Source'           = $Config.SessionAuthenticationCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.SessionAuthenticationCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthenticationCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SessionAuthenticationCertificateExpiresAfter)"
                    'Source'           = $Config.SessionAuthenticationCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: SessionAuthenticationCertificate is expiring soon $($Config.SessionAuthenticationCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "SessionAuthenticationCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.SessionAuthenticationCertificateExpiresAfter)"
                    'Source'           = $Config.SessionAuthenticationCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for SessionAuthenticationCertificate"
        }

        if ($Config.FinancialReportingCertificateExpiresAfter) {
            if ($Config.FinancialReportingCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "FinancialReportingCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.FinancialReportingCertificateExpiresAfter)"
                    'Source'           = $Config.FinancialReportingCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.FinancialReportingCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "FinancialReportingCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.FinancialReportingCertificateExpiresAfter)"
                    'Source'           = $Config.FinancialReportingCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: FinancialReportingCertificate is expiring soon $($Config.FinancialReportingCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "FinancialReportingCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.FinancialReportingCertificateExpiresAfter)"
                    'Source'           = $Config.FinancialReportingCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for FinancialReportingCertificate"
        }
        if ($Config.ReportingSSRSCertificateExpiresAfter) {
            if ($Config.ReportingSSRSCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "ReportingSSRSCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.ReportingSSRSCertificateExpiresAfter)"
                    'Source'           = $Config.ReportingSSRSCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.ReportingSSRSCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "ReportingSSRSCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.ReportingSSRSCertificateExpiresAfter)"
                    'Source'           = $Config.ReportingSSRSCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: ReportingSSRSCertificate is expiring soon $($Config.ReportingSSRSCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "ReportingSSRSCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.ReportingSSRSCertificateExpiresAfter)"
                    'Source'           = $Config.ReportingSSRSCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for ReportingSSRSCertificate"
        }
        if ($Config.LocalAgentCertificateExpiresAfter) {
            if ($Config.LocalAgentCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "LocalAgentCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.LocalAgentCertificateExpiresAfter)"
                    'Source'           = $Config.LocalAgentCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.LocalAgentCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "LocalAgentCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.LocalAgentCertificateExpiresAfter)"
                    'Source'           = $Config.LocalAgentCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: LocalAgentCertificate is expiring soon $($Config.LocalAgentCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "LocalAgentCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.LocalAgentCertificateExpiresAfter)"
                    'Source'           = $Config.LocalAgentCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found for LocalAgentCertificate"
        }
        if ($Config.DataEnciphermentCertificateExpiresAfter) {
            if ($Config.DataEnciphermentCertificateExpiresAfter -lt $ErrorDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataEnciphermentCertificate"
                    'State'            = "Down" 
                    'ExtraInfo'        = "$($Config.DataEnciphermentCertificateExpiresAfter)"
                    'Source'           = $Config.DataEnciphermentCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            elseif ($Config.DataEnciphermentCertificateExpiresAfter -lt $WarningDateCerts) {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataEnciphermentCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.DataEnciphermentCertificateExpiresAfter)"
                    'Source'           = $Config.DataEnciphermentCertificate
                    'Group'            = 'D365Certificates'
                }
                Write-PSFMessage -Level Warning -Message "WARNING: DataEnciphermentCertificate is expiring soon $($Config.DataEnciphermentCertificateExpiresAfter)"
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
            else {
                $Properties = @{'Name' = "D365Certificates"
                    'Details'          = "DataEnciphermentCertificate"
                    'State'            = "Operational" 
                    'ExtraInfo'        = "$($Config.DataEnciphermentCertificateExpiresAfter)"
                    'Source'           = $Config.DataEnciphermentCertificate
                    'Group'            = 'D365Certificates'
                }
                $Output = New-Object -TypeName psobject -Property $Properties
                $OutputList += $Output
            }
        }
        else {
            Write-PSFMessage -Level VeryVerbose -Message "Expiration not found forDataEnciphermentCertificate"
        }

        [PSCustomObject]$OutputList

    }
    END {
        if ($SFModuleSession) {
            Remove-PSSession -Session $SFModuleSession  
        }
    }
}

function Get-D365LBDOrchestrationLogs {
    <#
    .SYNOPSIS
   
   .DESCRIPTION
    
   .EXAMPLE
    Get-D365LBDOrchestrationLogs
   
   .EXAMPLE
     Get-D365LBDOrchestrationLogs -ComputerName "LBDServerName" -verbose
    .EXAMPLE
    $config = Get-D365Config
     Get-D365OrchestrationLogs -config $config -numberofevents 5
    
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
 
   #>

    [alias("Get-D365OrchestrationLogs")]
    [CmdletBinding()]
    param ([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [string]$ComputerName,
        [int]$NumberofEvents = 5,
        [Parameter(ValueFromPipeline = $True)]
        [psobject]$Config
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        [int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $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  -KeepAliveIntervalInSec 400
                $count = $count + 1
                
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My  -KeepAliveIntervalInSec 400
                    if ($connection) {
                        Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                    }
                }
                if (!$connection) {
                    $connection = Connect-ServiceFabricCluster -KeepAliveIntervalInSec 400
                    if ($connection) {
                        Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster"
                    }
                }
            }  until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count) -eq 0)
            if (($count -eq $($Config.OrchestratorServerName).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
            if (!$connection) {
                Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
            }
        }
        $orchnodes = Get-D365LBDOrchestrationNodes -config $Config
        Write-PSFMessage -Level Verbose -Message "$orchnodes"
    
        $LatestEventInLog = $(Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents 1 -ComputerName $orchnodes.PrimaryNodeName).TimeCreated
        if ($NumberofEvents -eq 1) {
            $primary = Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents 2 -ComputerName $orchnodes.PrimaryNodeName | 
            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;
                }
            }
        }
        else {
            $primary = Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents $NumberofEvents -ComputerName $orchnodes.PrimaryNodeName | 
            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 $orchnodes.SecondaryNodeName).TimeCreated
        if ($NumberofEvents -eq 1) {
            $secondary = Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents 2 -ComputerName $orchnodes.SecondaryNodeName | 
            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;
                }
            }
        }
        else {
            $secondary = Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents $NumberofEvents -ComputerName $orchnodes.SecondaryNodeName | 
            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;
                }
            }
        }
        foreach ($primarylog in $primary) {
            if ($primarylog.EventMessage -like "status of job *, Success") {
                Write-PSFMessage -Message "Found RunBook Success Message" -Level Verbose
            }
            if ($primarylog.EventMessage -like "status of job *, Error") {
                Write-PSFMessage -Message "Found RunBook Error Message" -Level Verbose
            }
        }
        if (!$secondary) {
            $all = $Primary | Sort-Object { $_.TimeCreated } -Descending | Select-Object -First $NumberofEvents
        }
        else {
            $all = $Primary + $secondary | Sort-Object { $_.TimeCreated } -Descending | Select-Object -First $NumberofEvents
        }
        return $all
    }
    END {
    }
}

##Get Primary and Secondary
function Get-D365LBDOrchestrationNodes {
    <#
    .SYNOPSIS
  Quick command to find the primary and secondary orchestrator nodes (Note it can change during deployment if applications crash)
   .DESCRIPTION
    Quick command to find the primary and secondary orchestrator nodes (Note it can change during deployment if applications crash)
   .EXAMPLE
   Get-D365LBDOrchestrationNodes
  Gathers the primary and secondary orchestrators based on the local machines environment
   .EXAMPLE
    Get-D365LBDOrchestrationNodes -ComputerName "LBDServerName" -verbose
   Gathers the primary and secondary orchestrators based on the defined machines environment
   .EXAMPLE
   $config = Get-d365config
    Get-D365LBDOrchestrationNodes -config $config -verbose
   Gathers the primary and secondary orchestrators based on the defined machines environment
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   #>

    [alias("Get-D365OrchestrationNodes")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ValueFromPipeline = $True)]
        [psobject]$Config)
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        [int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $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  -KeepAliveIntervalInSec 400
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My -KeepAliveIntervalInSec 400
                    if ($connection) {
                        Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                    }
                }
                if (!$connection) {
                    $connection = Connect-ServiceFabricCluster -KeepAliveIntervalInSec 400
                    if ($connection) {
                        Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster"
                    }
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            }  until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count) -eq 0)
            if (($count -eq $($Config.OrchestratorServerName).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
        }
        $PartitionId = $(Get-ServiceFabricServiceHealth -ServiceName 'fabric:/LocalAgent/OrchestrationService').PartitionHealthStates | Select-Object PartitionId
        if (!$PartitionId) {
            Write-PSFMessage -Level Warning -Message "Warning: Guessing Primary and Secondary due to local agent not found inside of SF"
            foreach ($Orchestrator in $Config.OrchestratorServerNames) {
                $time = $(Get-WinEvent -LogName Microsoft-Dynamics-AX-LocalAgent/Operational -MaxEvents 1 -ComputerName $Orchestrator).TimeCreated
                if (!$NewestPrimary) {
                    $NewestPrimary = $Orchestrator
                    $NewestPrimaryTime = $time
                }
                else {
                    if ($time -gt $NewestPrimaryTime) {
                        Write-PSFMessage -Level VeryVerbose -Message "Updating the Primary to $Orchestrator"
                        $NewestSecondary = $NewestPrimary 
                        $NewestSecondaryTime = $NewestPrimaryTime
                        $NewestPrimary = $Orchestrator
                        $NewestPrimaryTime = $time

                    }
                    else {
                        if ($time -gt $NewestSecondaryTime) {
                            Write-PSFMessage -Level VeryVerbose -Message "Updating the Secondary to $Orchestrator"
                            $NewestSecondary = $Orchestrator
                            $NewestSecondaryTime = $time
                        }
                    }
                }
            }
            New-Object -TypeName PSObject -Property `
            @{'PrimaryNodeName'                = $NewestPrimary;
                'SecondaryNodeName'            = $NewestSecondary;
                'PrimaryReplicaStatus'         = $NewestPrimaryTime; 
                'SecondaryReplicaStatus'       = $NewestSecondaryTime;
                'PrimaryLastinBuildDuration'   = $primary.LastinBuildDuration;
                'SecondaryLastinBuildDuration' = $secondary.LastinBuildDuration;
                'PrimaryHealthState'           = $primary.HealthState;
                'SecondaryHealthState'         = $secondary.HealthState;
                'PartitionId'                  = $PartitionIDGUID;
            }

        }
        else {
            $PartitionIDGUID = $PartitionId.PartitionId
       
            Write-PSFMessage -Message "Looking up PartitionID $PartitionIDGUID." -Level Verbose
            $nodes = Get-ServiceFabricReplica -PartitionId "$PartitionIDGUID"
            $primary = $nodes | Where-Object { $_.ReplicaRole -eq "Primary" -or $_.ReplicaType -eq "Primary" }
            $secondary = $nodes | Where-Object { $_.ReplicaRole -eq "ActiveSecondary" -or $_.ReplicaType -eq "ActiveSecondary" } | Select -First 1
            Write-PSFMessage -Level VeryVerbose -Message "Primary Orchestrator Currently is : $($primary.NodeName) and Secondary Orchestrator: $($secondary.NodeName) "
            New-Object -TypeName PSObject -Property `
            @{'PrimaryNodeName'                = $primary.NodeName;
                'SecondaryNodeName'            = $secondary.NodeName;
                'PrimaryReplicaStatus'         = $primary.ReplicaStatus; 
                'SecondaryReplicaStatus'       = $secondary.ReplicaStatus;
                'PrimaryLastinBuildDuration'   = $primary.LastinBuildDuration;
                'SecondaryLastinBuildDuration' = $secondary.LastinBuildDuration;
                'PrimaryHealthState'           = $primary.HealthState;
                'SecondaryHealthState'         = $secondary.HealthState;
                'PartitionId'                  = $PartitionIDGUID;
            }
        }
    }
    END {
        if ($SFModuleSession) {
            Remove-PSSession -Session $SFModuleSession  
        }
    }
}

function Get-D365LBDSFErrorDetails {
    <#
    .SYNOPSIS
     
   .DESCRIPTION
  
   .EXAMPLE
    Get-D365LBDSFErrorDetails -ComputerName "LBDServerName" -verbose
    
    .EXAMPLE
    $config = get-d365Config
    Get-D365LBDSFErrorDetails -config $Config
    
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   #>

    [alias("Get-D365SFErrorDetails")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [int]$Timeout = 600
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        [int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                }
                Write-PSFMessage -Message "-ConnectionEndpoint $($config.SFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
                $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            } until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count) -eq 0)
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
        }
        $TotalApplications = (Get-ServiceFabricApplication).Count
        $HealthyApps = (Get-ServiceFabricApplication | Where-Object { $_.HealthState -eq "OK" }).Count
        if ($TotalApplications -eq $HealthyApps){
            Write-PSFMessage -Message "All deployed applications are healthy $TotalApplications / $HealthyApps " -Level Verbose
        }
        else{
            $NotHealthyApps = Get-ServiceFabricApplication | Where-Object { $_.HealthState -ne "OK" }
            foreach ($NotHealthyApp in $NotHealthyApps){
                Write-PSFMessage -Level VeryVerbose -Message "$NotHealthyApp"
                $ServiceswithIssues = Get-ServiceFabricService -ApplicationName $NotHealthyApp.ApplicationName
                foreach ($ServiceswithIssue in $ServiceswithIssues){
                    $ServicePartition = Get-ServiceFabricPartition -ServiceName $ServiceswithIssue.ServiceName
                    $ServiceReplicaList = Get-ServiceFabricReplicaHealth -PartitionId $ServicePartition.PartitionId
                    foreach ($ServiceReplica in $ServiceReplicaList){
                        $HealthEvents = Get-ServiceFabricReplicaHealth -partitionid $ServiceReplica.PartitionId -ReplicaOrInstanceId $ServiceReplica[0].id
                        $unhealthyevents = $HealthEvents.UnhealthyEvaluations
                        foreach ($unhealthyevent in $unhealthyevents){
                            $unhealthyevent
                        }
                    }
                }
            }
        }
        
    }
    END {}
}

function Get-D365LBDTestConfigData {
    <# TODO: Add fields
    .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', 'Server6')
            "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"                             = '6324123912084123-123d0-1232-11234123'
            "LCSEnvironmentName"                           = 'LCSEnvironmentName'
            "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'
            'CustomModuleVersioninAgentShare'              = '2020.1.29.1'
            'AXDatabaseRestoreDate'                        = '5/15/2021 8:24:06 PM'
            'AXDatabaseCreationDate'                       = '5/15/2020 8:24:06 PM'
            'AXDatabaseBackupStartDate'                    = '5/15/2022 8:24:06 PM'
            'CustomModuleVersionFullPreppedinAgentShare'   = '2020.1.29.1'
            'DBSyncStatus'                                 = "Failed"
            'DBSyncTimeStamp'                              = '5/15/2022 8:24:06 PM'
            'DBSyncServerWithLatestLog'                    = 'Server5'
            'DeploymentAssetIDinWPFolder'                  = 'asd87213-123a-312c-213f-891798asd8231h5'
            'OrchestratorJobRunBookState'                  = 'Successful'
            'OrchestratorJobState'                         = 'Successful'
            'D365FOLBDAdminEnvironmentType'                = 'LBDUnrestricted'
            'ManagementReporterServers'                    = 'Server6'
            'SSRSClusterServerNames'                       = ('Server5')
            'RunningAXCodeFolder'                          = 'C:\programData\SF\Server1\Fabric\work\Applications\AXSFType_App0001\AXSF.Code.1.0.20201020123040' 
            'AggregatedSFState'                            = 'Ok'
            'NumberOfAppsinServicefabric'                  = '7'
            'LastOrchJobId'                                = 'LCSEnvironmentName-123lj45-askldj-4asdf-412lk3j'
            'LastRunbookTaskId'                            = 'LCSEnvironmentName-asfd4-123as5-askldj-4asdf2w'
            'ComponentsinSetupModule'                      = ('common', 'reportingservices', 'aos')
            'LCSProjectID'                                 = '564185'
            'LCSEnvironmentURL'                            = 'https://lcs.dynamics.com/v2/EnvironmentDetailsV3/564185?EnvironmentId=6324123912084123-123d0-1232-11234123'
            'SFExplorerURL'                                = 'https://sf.offandonit.com:19080'
            'CustomModuleName'                             = "MOD"
            'ADFSIdentifier'                               = 'https://ADFS.website.com/adfs/services/trust'
        }
        ##Sends Custom Object to Pipeline
        [PSCustomObject]$Properties
    }
    END {
    }
}

function Get-D365LCSEnvironmentDetailsProjectPage {
    <#
    .SYNOPSIS
    Needs Selenium Powershell running on projects page
   .DESCRIPTION
   
   .EXAMPLE
    
     
   #>

    [alias("Get-LCSEnvironmentDetailsProjectPages")]
    [CmdletBinding()]
    param()
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        $CustomObjectAllEnvironments = @()
        $allenvironments = Get-SeElement -By XPath -Value "//div[contains(text(), 'Environment')]"
        $environmentcount = 0
        foreach ($environmentlcs in $allenvironments) {
            $environmentcount = $environmentcount + 1
            $text = $environmentlcs.text 
            $substring = $text.Substring(12)
            $environmentname = $substring.split('')[0]
            $finalsubstring = $substring -replace 'state:', ''
            $status = $($finalsubstring -replace $environmentname, '').trim('')

            $environmentcustom = New-Object -TypeName psobject -Property `
            @{'EnvironmentName'    = $environmentName
                'EnvironmentState' = $status
                'EnvironmentOrder' = $environmentCount
            }
            $CustomObjectAllEnvironments = $CustomObjectAllEnvironments + $environmentcustom
        }

        $allenvironmentsfulldetails = Get-SeElement -By XPath -Value "//div[contains(text(), 'Environment')]//parent::*//parent::*//parent::*//parent::*//parent::*//*[contains(text(), 'Full details')]"
        $countofsandboxes = Get-SeElement -By XPath -Value "//div[contains(text(), 'Environment')]//parent::*//parent::*//parent::*//parent::*//parent::*//parent::*//parent::*//parent::*//*[contains(text(), 'Sandbox')]"
        if ($allenvironmentsfulldetails.count -ne $countofsandboxes.Count) {
            Write-verbose "Production environment deployed"
            $ProdFound = "yes"
        }
        $CustomObjectAllEnvironmentsurl = @()
        $environmentcount = 0
        foreach ($details in $allenvironmentsfulldetails) {
            $environmentcount = $environmentcount + 1
            $url = Get-SeElementAttribute -Element $details -Name 'href'
            $environmenturlcustom = New-Object -TypeName psobject -Property `
            @{'Environmenturl'     = $url
                'EnvironmentOrder' = $environmentCount
            }
            $CustomObjectAllEnvironmentsurl = $CustomObjectAllEnvironmentsurl + $environmenturlcustom
        }

        $AllEnvironmentsLCS = @()
        foreach ($CustomObject in $CustomObjectAllEnvironments) {
            $Counter = $CustomObject.EnvironmentOrder
            if ($Counter -eq 1 -and $ProdFound -eq "yes") {
                $EnvironmentType = 'Production'
            }
            else {
                $EnvironmentType = 'Sandbox'
            }
            $URL = $CustomObjectAllEnvironmentsurl | Where-Object { $_.EnvironmentOrder -eq $Counter }
            $environmenturlcustom = New-Object -TypeName psobject -Property `
            @{'EnvironmentName'    = $CustomObject.environmentName
                'EnvironmentState' = $CustomObject.EnvironmentState
                'EnvironmentOrder' = $CustomObject.EnvironmentOrder
                'EnvironmentType'  = $EnvironmentType
                'EnvironmentURL'   = $URL.Environmenturl
            }
            $AllEnvironmentsLCS = $AllEnvironmentsLCS + $environmenturlcustom

        }
        $AllEnvironmentsLCS
    }
    END {}
}

function Get-AzureDevOpsLastSuccessfulRelease { 
    <#
        .SYNOPSIS
        Grabs the latest success of a specific release definition and specific stage.
        .DESCRIPTION
        Grabs the latest success of a specific release definition and specific stage.
        .EXAMPLE
        Get-AzureDevOpsLastSuccessfulRelease -Instance 'FakeVisualStudioInstance' -Project 'VisualStudioProjectName' -User 'fakeuser@fakeemail.com' -PAT 'fakepat912830985' -ReleaseDefinition 'ReleasePipeline' -ReleaseStage "LCSUpload"
        .PARAMETER ParameterName
        Parameter details
        #>
 
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            HelpMessage = 'Help Message?')]
        [Alias('Get-LastSuccessfulRelease')]
        [string]$Instance,
        [string]$Project,
        [string]$User,
        [string]$PAT,
        [string]$ReleaseDefinition, 
        [string]$ReleaseStage
    )

    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User, $PAT)))
    
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add('Authorization', ('Basic {0}' -f $base64AuthInfo))
    $headers.Add('Accept', 'application/json') 
    
    # Get array of project release types and get project (release def) id
    $releasedefinitionlistURL = "https://vsrm.dev.azure.com/$Instance/$Project/_apis/release/definitions?api-version=5.1"
    $results = Invoke-RestMethod -Headers $Headers -ContentType application/json -Uri $releasedefinitionlistURL -Method Get -UseBasicParsing

    $SpecificReleaseDefinition = $results.value | Where-Object { $_.name -eq $ReleaseDefinition }
    $ReleaseDefinitionId = $SpecificReleaseDefinition.id

    if (!$ReleaseDefinitionId) {
        Stop-PSFFunction -Message "Error: Cannot find release definition. Stopping" -EnableException $true -Cmdlet $PSCmdlet
    }
    
    $SpecificDefinitionIDSuccessAPI = "https://vsrm.dev.azure.com/$Instance/$Project/_apis/release/deployments?definitionid=$ReleaseDefinitionId&deploymentStatus=succeeded"
    $RPResults = Invoke-RestMethod -Method Get -Headers $Headers -ContentType application/json -Uri $SpecificDefinitionIDSuccessAPI -UseBasicParsing
    
    $ReleaseId = $RPResults.value.release.id | Sort-Object -Descending | Select-Object -First 1

    # Get release list
    $releaseapi = "https://vsrm.dev.azure.com/$Instance/$Project/_apis/release/releases/?api-version=5.1"
    $releaseapiResult = Invoke-RestMethod -Method Get -Headers $Headers -ContentType application/json -Uri $releaseapi -UseBasicParsing
    
    # Filter by release id and find build number
    $releaseapiFiltered = $releaseapiResult.value | Where-Object { $_.id -eq $ReleaseId }
    $TempArray = $releaseapiFiltered.description.Split(" ")
    $ReleaseName = $TempArray[$TempArray.Count - 1].TrimEnd(".")
    $url = "https://vsrm.dev.azure.com/$Instance/$Project/_apis/release/releases/$releaseID" + "?api-version=5.1"
    $Variables = (invoke-restmethod -method Get -uri $url -Headers $headers).variables
    $VariableNames = $Variables | Get-Member | Where-Object { $_.MemberType -eq "NoteProperty" -and $_.Name -ne "System.Debug" } | Select-Object Name

    $Properties = @{
        "ReleaseId"             = $ReleaseId
        "ReleaseName"           = $ReleaseName
        "ReleaseDefinitionName" = $ReleaseDefinition
    }
    $Output = New-Object PSObject -Property $Properties
    foreach ($VariableName in $VariableNames.Name) {
        
        $value = $Variables.$VariableName.value
        Write-PSFMessage -Level VeryVerbose -Message "Adding Variable $VariableName with a value of $value"
        Add-Member -Name $VariableName -Value $value -InputObject $Output -MemberType NoteProperty
    }


    return $Output
}

function Import-D365LBDCertificates {
    <# TODO: Need to rethink approach doesnt work smoothly
   .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
 
 
  #>

    [alias("Import-D365Certificates")]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $false)]
        [string]$CertThumbprint,
        [Parameter(Mandatory = $false)]
        [string]$CertFolder,
        [switch]$Exportable
    )
    BEGIN {
    }
    PROCESS {
        ##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"
            }
        }
        END {
        }
    }
}

function New-D365LBDAXSFNode {
    <# TODO: Needs better testing.
    .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."
    }
    END {
    }
}

function Remove-D365LBDSFImageStoreFiles {
    <# TODO: Needs more testing
    .SYNOPSIS
  Created to clean service fabric image store. needs more testing.
   .DESCRIPTION
   Created to clean service fabric image store. needs more testing.
   .EXAMPLE
   Remove-D365LBDSFImageStoreFiles
  Removes Image store files inside of the local environments Service fabric.
   .EXAMPLE
   $config = get-d365Config
    Remove-D365LBDSFImageStoreFiles -config $config
    Removes Image store files inside of the defined environments Service fabric.
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
 
   #>

    [alias("Remove-D365SFImageStoreFiles")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ValueFromPipeline = $True)]
        [psobject]$Config)
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        [int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $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
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            }  until ($connection -or ($count -eq $($OrchestratorServerNames).Count) -or ($($OrchestratorServerNames).Count) -eq 0)
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
        }
        
        $content = Get-servicefabricimagestorecontent -remoterelativepath "\" -ImageStoreConnectionString fabric:ImageStore
        foreach ($folder in $content) {
            if (($folder.StoreRelativePath -ne "Store") -and ($folder.StoreRelativePath -ne "WindowsFabricStore")) {
                Write-PSFMessage "Deleting $($folder.StoreRelativePath)" -Level VeryVerbose
                Remove-ServiceFabricApplicationPackage -ApplicationPackagePathInImageStore $folder.StoreRelativePath -ImageStoreConnectionString fabric:ImageStore
            }
        }
    }
    END {
    }
}


function Remove-D365LBDSFInstalledFinancialReporting {
    <#
 ##created for deployment bug when the local agent can't clean up properly this was fixed in later local agent versions but still has value when but use only in extreme situations
 #>

    [alias("Remove-D365SFInstalledFinancialReporting")]
    [CmdletBinding()]
    param (
        [string]$SFServerCertificate,
        [string]$SFConnectionEndpoint,
        [string]$AgentShareLocation,
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName 
        }

        if (-not $($config.TenantID)) {
            $cachedconfigfile = Join-path $($config.AgentShareLocation) -ChildPath "scripts\config.xml" 
            $config = Get-D365LBDConfig -ConfigImportFromFile $cachedconfigfile
        }
        if ($SFServerCertificate) {
            Connect-ServiceFabricCluster -ConnectionEndpoint $SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $SFServerCertificate -ServerCertThumbprint $SFServerCertificate
        }
        else {
            [int]$count = 0
            Write-PSFMessage -Message "Trying to connect to service fabric to find primary and secondary orchestration servers" -Level VeryVerbose
            while (!$connection) {
                do {
                    $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                    Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                    $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                    if (!$module) {
                        $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
                    if (!$connection) {
                        $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                    }
                    $count = $count + 1
                    if (!$connection) {
                        Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                    }
                } until ($connection -or ($count -eq $($Config.OrchestratorServerName).Count) -or ($($Config.OrchestratorServerName).Count) -eq 0)
                if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                    Write-PSFMessage -Level VeryVerbose -Message "Error: Can't connect to Service Fabric"
                }
            }
        }

        if ($AgentShareLocation) {
            $environmentwp = get-childitem $(Join-path $AgentShareLocation -ChildPath "\wp")
            $archivefolder = $(Join-path $AgentShareLocation -ChildPath "\archive")
        }
        else {
            $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
            if (!$environmentwp) {
                Write-PSFMessage -Level VeryVerbose -Message "WP Folder already cleaned up"
            }
        }
       
        Write-PSFMessage -Message "Deleting Financial Reporting applications inside of Service Fabric" -Level Verbose

        Get-ServiceFabricApplication |  Where-Object { $_.ApplicationName -eq "fabric:/FinancialReporting" } |  Remove-ServiceFabricApplication -Force
        Get-ServiceFabricApplicationType |  Where-Object { $_.ApplicationTypeName -eq "FinancialReportingType" } |      Unregister-ServiceFabricApplicationType -Force

     
       
    }
    END {
    }
}


function Remove-D365LBDSFLogs {
    <#
   .SYNOPSIS
  Removes older files in the service fabric fabric logs folder
   .DESCRIPTION
   Removes older files in the service fabric fabric logs folder
   .EXAMPLE
   Remove-D365SFLogs -verbose
    Will remove the log files on each server that are older than 1 day on the local machines environment. Recommended to run on verbose to see what server/step its at.
   .EXAMPLE
   $config = get-d365Config
    Remove-D365SFLogs config $config -CleanupOlderThanDays 2 -verbose
   Will remove the log files on each server that are older than 2 days on the defined configurations environment. Recommended to run on verbose to see what server/step its at.
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   .PARAMETER CleanupOlderThanDays
   integer
   Value in days that would be considered not needed. Example if set to 5 the cert expires in less than 5 days it delete all logs older than 5 days. Default of 1.
   .PARAMETER ControlFile
   switch
   Turns on making/appending a control file in the log folder saying how many files were deleted.
     #>

    [alias("Remove-D365SFLogs")]
    [CmdletBinding()]
    param
    (
        [Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [psobject]$Config,
        [int]$CleanupOlderThanDays = 1,
        [switch]$ControlFile
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly   
        }
        if ($CleanupOlderThanDays -lt 1){
            Stop-PSFFunction -Message "Error: CleanupOlderThanDays can't be less than 1 day". -EnableException $true -FunctionName $_ 
        }
        Foreach ($SFServerName in $($config.AllAppServerList | Select-Object ComputerName).ComputerName) {
            $LogFolder = Get-ChildItem -Path "\\$SFServerName\c$\ProgramData\SF\DiagnosticsStore\fabriclogs*\*\Fabric*" | Select-Object -First 1 -ExpandProperty FullName
            $StartTime = Get-Date
            Write-PSFMessage -Level Verbose -Message "Starting Clean on $LogFolder"
            $FilesThatAreBeingDeleted = Get-ChildItem -path $LogFolder | Sort-Object LastWriteTime | Where-Object { $_.Name -ne "ControlFile.txt" -and $_.LastWriteTime -lt (Get-Date).AddDays(-$CleanupOlderThanDays) }
            $FileCount = $FilesThatAreBeingDeleted.Count
            Write-PSFMessage -Level Verbose -Message "Deleting $FileCount files on $SFServerName"
            if ($FilesThatAreBeingDeleted -and $FileCount -gt 0 ) {
                $FilesThatAreBeingDeleted.FullName | Remove-Item -Force -Recurse
            }
            $EndTime = Get-Date
            $TimeDiff = New-TimeSpan -Start $StartTime -End $EndTime
            Write-PSFMessage -Level VeryVerbose -Message "$SFServerName - StartTime: $StartTime - EndTime: $EndTime - Execution Time: $($TimeDiff.Minutes) Minutes $($TimeDiff.Seconds) Seconds - Count of Files: $FileCount"
            if ($ControlFile -and $FileCount -gt 0) {
                "$SFServerName - StartTime: $StartTime - EndTime: $EndTime - Execution Time: $($TimeDiff.Minutes) $($TimeDiff.Seconds) Count of Files: $FileCount" | Out-File $LogFolder\ControlFile.txt -append
            }
        }
        Write-PSFMessage -Level VeryVerbose -Message "$($config.LCSEnvironmentName) Service Fabric Servers have been cleaned of older than $CleanupOlderThanDays days Service Fabric Logs."
    }
    END {
        
    }
}


function Remove-D365LBDSFOldAssets {
    <#
    .SYNOPSIS
  Removes deployment assets that are no longer needed based on age and how many that are left as backup.
   .DESCRIPTION
    Removes deployment assets that are no longer needed based on age and how many that are left as backup.
   .EXAMPLE
   Remove-D365LBDSFOldAssets -numberofassetstokeep 4
  Location of assets based on the local machine config. Keep the newest 4 builds while removing the older assets.
   .EXAMPLE
    Remove-D365LBDSFOldAssets -Config $config -NumberofAssetsToKeep 5 -ScanForInvalidZips
    Location of assets based on the config. Keep the newest 5 builds while removing the older assets and scan for all assets that are invalid.
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
    .PARAMETER NumberOfAssetsToKeep
    Integer
    Define how many assets to keep in the assets folder (must be greater than 2). If not defined will scan if defined in additional environment config.
 
   #>

    [alias("Remove-D365SFOldAssets")]
    [CmdletBinding()]
    param
    ([Parameter(ValueFromPipeline = $True,
        ValueFromPipelineByPropertyName = $True,
        Mandatory = $false,
        HelpMessage = 'D365FO Local Business Data Server Name',
        ParameterSetName = 'NoConfig')]
    [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
    [psobject]$Config,
    [int]$NumberofAssetsToKeep,
    [switch]$ControlFile,
    [switch]$ScanForInvalidZips
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly   
        }
        if (!$NumberofAssetsToKeep) {
            $AgentShareLocation = $Config.AgentShareLocation
            if (test-path $AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml) {
                Write-PSFMessage -Level Verbose -Message "Found AdditionalEnvironmentDetails config"
                $EnvironmentAdditionalConfig = get-childitem "$AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml"
                [xml]$EnvironmentAdditionalConfigXML = get-content  $EnvironmentAdditionalConfig
                if ($EnvironmentAdditionalConfigXML.D365LBDEnvironment.Automation.CleanupAssets.Enabled -eq "true") {
                    $NumberofAssetsToKeep = [int]$EnvironmentAdditionalConfigXML.D365LBDEnvironment.Automation.CleanupAssets.AssetsToKeep
                }
            }
        }
        if (!$NumberofAssetsToKeep) {
            Stop-PSFFunction -Message "Error: Number of Assets not defined and Additional Environment Details configured" -EnableException $True -FunctionName $_ 
        }

        if ($NumberofAssetsToKeep -lt 2) {
            Stop-PSFFunction -Message "Error: Number of Assets to keep must be 2 or more (currently set at: $NumberofAssetsToKeep) as you should always keep the main and backup. " -EnableException $True -FunctionName $_ 
        }
        $AssetsFolderinAgentShareLocation = join-path -Path $Config.AgentShareLocation -ChildPath "\assets"
        $Onedayold = $(get-date).AddDays(-1)
        $AlreadyDeployedAssetIDInWPFolder = $Config.DeploymentAssetIDinWPFolder
        $StartTime = Get-Date
        $AssetFolders = Get-ChildItem $AssetsFolderinAgentShareLocation | Where-Object { $_.Name -ne "chk" -and $_.Name -ne "topology.xml" -and $_.Name -ne "$AlreadyDeployedAssetIDInWPFolder" -and $_.CreateDate -lt $Onedayold -and $_.Name -ne "ControlFile.txt" } 
        if ($ScanForInvalidZips) {
            Write-PSFMessage -Level Verbose -Message "Checking for invalid assets in $AssetsFolderinAgentShareLocation"
        }
        foreach ($AssetFolder  in $AssetFolders ) {
            $StandaloneSetupZip = $null
            $StandaloneSetupZip = Get-ChildItem "$($AssetFolder.Fullname)\*\*\Packages\*\StandaloneSetup.zip"
            if ($ScanForInvalidZips) {
                $job = $null
                $job = start-job -ScriptBlock { Add-Type -AssemblyName System.IO.Compression.FileSystem; $zip = [System.IO.Compression.ZipFile]::OpenRead($using:StandaloneSetupZip) }
                if (Wait-Job $job -Timeout 300) { Receive-Job $job }else {
                    Write-PSFMessage -Level VeryVerbose -message "Invalid Zip file $StandaloneSetupZip."
                    Write-PSFMessage -Message "$AssetFolder is invalid - deleting" -Level VeryVerbose
                    Get-ChildItem $AssetFolder.Fullname | Remove-Item -Recurse -Force
                    Get-ChildItem $AssetsFolderinAgentShareLocation | Where-object { $_.Name -eq $AssetFolder } | Remove-Item -Recurse -Force
                }
                stop-job $job
                Remove-Job $job
            }
            if (!$StandaloneSetupZip) {
                Write-PSFMessage -Message "$AssetFolder is invalid no StandaloneSetup found - deleting" -Level VeryVerbose
                Get-ChildItem $AssetFolder.Fullname | Remove-Item -Recurse -Force
                Get-ChildItem $AssetsFolderinAgentShareLocation | Where-object { $_.Name -eq $AssetFolder } | Remove-Item -Recurse -Force
            }
            else {
                if ($StandaloneSetupZip.Length -eq 0) {
                    Write-PSFMessage -Message "Standalone zip in $AssetFolder is invalid - deleting" -Level VeryVerbose
                    Get-ChildItem $AssetFolder.Fullname | Remove-Item -Recurse -Force
                    Get-ChildItem $AssetsFolderinAgentShareLocation | Where-object { $_.Name -eq $AssetFolder } | Remove-Item -Recurse -Force
                }
                else {
                    Write-PSFMessage -Message "Standalone zip in $AssetFolder is VALID" -Level Verbose
                }
            }
        }
        Write-PSFMessage -Level Verbose -Message "Starting Clean on $AssetsFolderinAgentShareLocation"
        $FilesThatAreBeingDeleted = Get-ChildItem $AssetsFolderinAgentShareLocation | Where-Object { $_.Name -ne "chk" -and $_.Name -ne "topology.xml" -and $_.Name -ne "$AlreadyDeployedAssetIDInWPFolder" -and $_.CreateDate -lt $Onedayold -and $_.Name -ne "ControlFile.txt" } | Sort-Object CreationTime | Select-Object -SkipLast $NumberofAssetsToKeep
        $FileCount = $FilesThatAreBeingDeleted.Count
        if ($FileCount -or $FileCount -ne 0) {
            $FilesThatAreBeingDeleted.FullName | Remove-Item -Force -Recurse
        }
        $EndTime = Get-Date
        $TimeDiff = New-TimeSpan -Start $StartTime -End $EndTime
        Write-PSFMessage -Level VeryVerbose -Message "$AssetsFolderinAgentShareLocation - StartTime: $StartTime - EndTime: $EndTime - Execution Time: $($TimeDiff.Minutes) Minutes $($TimeDiff.Seconds) Seconds - Count of Files: $FileCount"
        if ($ControlFile -and $FileCount -gt 0) {
            "$AssetsFolderinAgentShareLocation - StartTime: $StartTime - EndTime: $EndTime - Execution Time: $($TimeDiff.Minutes) minutes $($TimeDiff.Seconds) seconds - Count of Files: $FileCount " | Out-File $AssetsFolderinAgentShareLocation\ControlFile.txt -append
        }
        Write-PSFMessage -Level VeryVerbose -Message "$($config.LCSEnvironmentName) AgentShare Assets have been cleaned"
    }
    END {
    }
}


function Remove-D365LBDStuckApps {
    <#
  ##created for deployment bug when the local agent can't clean up properly this was fixed in later local agent versions but still has value when but use only in extreme situations
  #>

    [alias("Remove-D365StuckApps")]
    [CmdletBinding()]
    param (
        [string]$SFServerCertificate,
        [string]$SFConnectionEndpoint,
        [string]$AgentShareLocation,
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName 
        }

        if (-not $($config.TenantID)) {
            $cachedconfigfile = Join-path $($config.AgentShareLocation) -ChildPath "scripts\config.xml" 
            $config = Get-D365LBDConfig -ConfigImportFromFile $cachedconfigfile
        }
        if ($SFServerCertificate) {
            Connect-ServiceFabricCluster -ConnectionEndpoint $SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $SFServerCertificate -ServerCertThumbprint $SFServerCertificate
        }
        else {
            [int]$count = 0
            Write-PSFMessage -Message "Trying to connect to service fabric to find primary and secondary orchestration servers" -Level VeryVerbose
            while (!$connection) {
                do {
                    $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                    Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                    $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                    if (!$module) {
                        $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
                    if (!$connection) {
                        $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                    }
                    $count = $count + 1
                    if (!$connection) {
                        Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                    }
                } until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count))
                if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                    Write-PSFMessage -Level VeryVerbose -Message "Error: Can't connect to Service Fabric"
                }
            }
        }

        if ($AgentShareLocation) {
            $environmentwp = get-childitem $(Join-path $AgentShareLocation -ChildPath "\wp")
            $archivefolder = $(Join-path $AgentShareLocation -ChildPath "\archive")
        }
        else {
            $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
            if (!$environmentwp) {
                Write-PSFMessage -Level VeryVerbose -Message "WP Folder already cleaned up"
            }
        }
        
        Write-PSFMessage -Message "Deleting applications inside of Service Fabric" -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

        if (!$environmentwp) {
        }
        else {
            Write-PSFMessage "Moving $($environmentwp.FullName) to $archivefolder " -Level VeryVerbose
            Move-Item -Path $environmentwp.FullName -Destination $archivefolder -Force -Verbose
        }
    
        Write-PSFMessage -Level Verbose -Message "Trigger deployment/retry in LCS"
    }
    END {
    }
}

function Remove-D365SFClusterExtraFiles {
    <#
   .SYNOPSIS
   When removing cluster the cleanup usually messes up and needs further cleanup.
   Run Clean fabric scripts on each server then run this to do final cleanup. If any files are locked restart computers
   Restart then remake cluster.
Use Get-D365LBDConfig -ConfigImportFromFile to get config
  #>

    [alias("Remove-D365ClusterExtraFiles")]
    [CmdletBinding()]
    param
    (
        [Parameter(ParameterSetName = 'AllAppServerList',
            ValueFromPipeline = $True)]
        [string[]]$AllAppServerList,
        [Parameter(Mandatory = $false)]
        [string]$ExportLocation,
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config
    )
    BEGIN {
    }
    PROCESS {
        if ($Config)
        {
            $AllAppServerList= $config.AllAppServerList
        }
        else{

        }
         
        foreach ($AppServer in $AllAppServerList) {
            Invoke-Command -ScriptBlock { $SFFolder = Get-ChildItem "C:\ProgramData" -Directory | Where-Object { $_.Name -eq "SF" };
                if ($SFFolder.Count -eq 1 ) {
                    $items.FullName | Remove-Item -Recurse -Force -Confirm -Verbose
                    Write-PSFMessage -Level VeryVerbose -Message "Cleaned SF Folder on $env:ComputerName "
                }
                else {
                    Write-PSFMessage -Level VeryVerbose -Message "SF Folder in Program Data doesnt exist on $env:ComputerName"
                }
            } -ComputerName $AppServer
        }

    }
    END {}
}


function Restart-D365LBDOrchestratorLastJob {
     <#
   .SYNOPSIS
  Restarts the state of the orchestratorjob and runbooktaskid tables last executed jobs
  .DESCRIPTION
  Restarts the state of the orchestratorjob and runbooktaskid tables last executed jobs by changing the values in the orchestrator database.
  .EXAMPLE
  $config = get-d365Config
   Restart-D365LBDOrchestratorLastJob -config $config
  .EXAMPLE
   Restart-D365LBDOrchestratorLastJob -OrchDatabaseServer 'DBSERVER01' -OrchDatabaseName 'OrchDatabaseServer'
  .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER OrchDatabaseServer
    string
    The name of the orchestrator database server can be defined with OrchDatabaseName to restart without a config
   .PARAMETER OrchDatabaseName
   string
   The name of the orchestrator database (usually OrchestratorData) can be defined with OrchDatabaseServer to restart without a config
  #>

    [CmdletBinding()]
    [alias("Restart-D365OrchestratorLastJob")]
    param ([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [Parameter(ParameterSetName = 'Directly')]
        [string]$OrchDatabaseServer,
        [string]$OrchDatabaseName
    )
    BEGIN {
    } 
    PROCESS {
        if ((!$Config -or $Config.OrchestratorServerNames.Count -eq 0) -and !$OrchDatabaseServer) {
     Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        else {
            if (!$config) {
                if ($OrchDatabaseName) {
                    Write-PSFMessage -Message "No DatabaseName specified trying OrchestratorData" -Level VeryVerbose
                    $OrchDatabaseName = 'OrchestratorData'
                }
            }
            else {
                ##Using Config
                Write-PSFMessage -Message "Using Config for execution" -Level Verbose
                $OrchDatabaseName = $Config.OrchDatabaseName
                $OrchDatabaseServer = $Config.OrchDatabaseServer
            }
        }

        if ($null -eq $OrchDatabaseServer) {
            Stop-PSFFunction -Message "Error: Can't Find OrchDatabaseServer. Stopping. Suggest running the command using the parameter set directly" -EnableException $true -Cmdlet $PSCmdlet
        }
  
        $OrchJobQuery = 'select top 1 JobId,State from OrchestratorJob order by ScheduledDateTime desc'
        $RunBookQuery = 'select top 1 RunbookTaskId, State from RunBookTask order by StartDateTime desc'
   
        function Invoke-SQL {
            param(
                [string] $dataSource = ".\SQLEXPRESS",
                [string] $database = "MasterData",
                [string] $sqlCommand = $(throw "Please specify a query.")
            )

            $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

            $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
            $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)
            $connection.Open()
    
            $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
            $dataset = New-Object System.Data.DataSet

            $adapter.Fill($dataSet) | Out-Null
            $connection.Close()
            $dataSet.Tables
        }
        $OrchJobQueryResults = Invoke-SQL -dataSource $OrchDatabaseServer -database $OrchDatabaseName -sqlCommand $OrchJobQuery
        $RunBookQueryResults = Invoke-SQL -dataSource $OrchDatabaseServer -database $OrchDatabaseName -sqlCommand $RunBookQuery 

        $LastOrchJobId = $($OrchJobQueryResults | select JobId).JobId
        $LastOrchState = $($OrchJobQueryResults | select state).State

        $LastRunbookTaskId = $($RunBookQueryResults | select RunbookTaskId).RunbookTaskId
        $LastRunbookState = $($RunBookQueryResults | select state).State

        if ($LastOrchState -eq 2 -or $LastOrchState -eq 1) {
            Write-PSFMessage -Level VeryVerbose -Message "Can't run OrchJob is already in running on completed successfully state"
        }
        else {
            $RestartQuery1 = "Update OrchestratorJob set State = 1 where JobId = '$LastOrchJobId'"
            $RestartQuery2 = "Update RunBookTask set State = 1, Retries = 1 where RunbookTaskId = '$LastRunbookTaskId'"
            Write-PSFMessage -Level VeryVerbose -Message "$RestartQuery1 Running on $OrchDatabaseServer against $OrchDatabaseName"
            Invoke-SQL -dataSource $OrchDatabaseServer -database $OrchDatabaseName -sqlCommand $RestartQuery1 
            Write-PSFMessage -Level VeryVerbose -Message "$RestartQuery2 Running on $OrchDatabaseServer against $OrchDatabaseName"
            Invoke-SQL -dataSource $OrchDatabaseServer -database $OrchDatabaseName -sqlCommand $RestartQuery2 
        }

        if (!$Config) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        [int]$count = 0
        Write-PSFMessage -Message "Trying to connect to service fabric to find primary and secondary orchestration servers" -Level VeryVerbose
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $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
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            } until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or (($($Config.OrchestratorServerNames).Count) -eq 0))
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Write-PSFMessage -Level VeryVerbose -Message "Error: Can't connect to Service Fabric"
            }
        }
        if ($connection) {
            Write-PSFMessage -Level VeryVerbose -Message "Connected to Service Fabric"
            $PartitionId = $(Get-ServiceFabricServiceHealth -ServiceName 'fabric:/LocalAgent/OrchestrationService').PartitionHealthStates | Select-Object PartitionId
       
        $PartitionIDGUID = $PartitionId.PartitionId
       
            $nodes = Get-ServiceFabricReplica -PartitionId $PartitionIDGUID
            $primary = $nodes | Where-Object { $_.ReplicaRole -eq "Primary" -or $_.ReplicaType -eq "Primary" }
            $secondary = $nodes | Where-Object { $_.ReplicaRole -eq "ActiveSecondary" -or $_.ReplicaType -eq "ActiveSecondary" } | Select -First 1
            New-Object -TypeName PSObject -Property `
            @{'PrimaryNodeName'                = $primary.NodeName;
                'SecondaryNodeName'            = $secondary.NodeName;
                'PrimaryReplicaStatus'         = $primary.ReplicaStatus; 
                'SecondaryReplicaStatus'       = $secondary.ReplicaStatus;
                'PrimaryLastinBuildDuration'   = $primary.LastinBuildDuration;
                'SecondaryLastinBuildDuration' = $secondary.LastinBuildDuration;
                'PrimaryHealthState'           = $primary.HealthState;
                'SecondaryHealthState'         = $secondary.HealthState;
                'PartitionId'                  = $PartitionIDGUID;
            }
        }
    }
    END {
    }
}

function Restart-D365LBDSFAppServers {
    <#
    .SYNOPSIS
    Restarts all application nodes in the service fabric layer. Also has the ability to reboot the whole Operating system (OS) and also to restart the orchestrator nodes (full OS restart only)
   .DESCRIPTION
   Restarts all application nodes in the service fabric layer. Also has the ability to reboot the whole Operating system (OS) and also to restart the orchestrator nodes (full OS restart only)
   .EXAMPLE
   Restart-D365LBDSFAppServers
   Based on the local server it will determine all the environment's servers and restart the service fabric nodes in the service fabric layer.
   .EXAMPLE
    Restart-D365LBDSFAppServers -ComputerName "LBDServerName" -verbose
    Based on the defined server it will determine all the environment's servers and restart the service fabric nodes in the service fabric layer.
   .EXAMPLE
    Restart-D365LBDSFAppServers -config $config -RebootWholeOS -verbose
    Based on the defined config it will determine all the environment's AX SF application servers and restart the whole Operating system of each.
    .EXAMPLE
    Restart-D365LBDSFAppServers -config $config -RebootWholeOSIncludingOrch -verbose -waittillhealthy
    Based on the config it will determine all the environment's servers including orchestrator nodes and restart the whole Operating system of each and will wait till the servers are "healthy" (can be accessed for more commands).
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
   #>

    [alias(" Restart-D365SFAppServers")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name',
            ParameterSetName = 'NoConfig')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [int]$Timeout = 600,
        [switch]$waittillhealthy,
        [switch]$RebootWholeOS,
        [switch]$RebootWholeOSIncludingOrch
    )
    ##Gather Information from the Dynamics 365 Orchestrator Server Config
    BEGIN {
    } 
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName
        }[int]$count = 0
        while (!$connection) {
            do {
                $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                }
                Write-PSFMessage -Message "-ConnectionEndpoint $($config.SFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
                $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                $count = $count + 1
                if ($connection) {
                    $ConnectedSFConnectionEndpoint = $config.SFConnectionEndpoint
                    $ConnectedOrchestratorServerName = $OrchestratorServerName
                    Write-PSFMessage -Message "Connected using: $ConnectedSFConnectionEndpoint and $ConnectedOrchestratorServerName" -Level VeryVerbose
                }
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                    if ($connection) {
                        $ConnectedSFConnectionEndpoint = $trialEndpoint 
                        $ConnectedOrchestratorServerName = $OrchestratorServerName
                        Write-PSFMessage -Message "Connected using: $ConnectedSFConnectionEndpoint and $ConnectedOrchestratorServerName" -Level VeryVerbose
                    }
                }
                
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            } until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count -eq 0))
            if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
            }
        }
        $AppNodes = Get-ServiceFabricNode | Where-Object { ($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType") -or ($_.NodeType -eq "ReportServerType") -or ($_.NodeType -eq "PrimaryNodeType") } 
      
        if ($RebootWholeOS -or $RebootWholeOSIncludingOrch) {
            if ($RebootWholeOSIncludingOrch) {
                if ($waittillhealthy) {
                    Write-PSFMessage -Message "Restarting $($config.AllAppServerList) and Waiting for Powershell to be available" -Level Verbose
                    Restart-computer -ComputerName  $config.AllAppServerList -Force -Wait -for PowerShell -Delay 2 -Verbose
                }
                else {
                    Write-PSFMessage -Message "Restarting $($config.AllAppServerList)" -Level Verbose
                    Restart-computer -ComputerName  $config.AllAppServerList -Force -Wait -for PowerShell -Delay 2 -Verbose
                }   
            }
            else {
                ## Only SF nodes
                if ($waittillhealthy) {
                    Write-PSFMessage -Message "Restarting $($config.AXSFServerNames) and Waiting for Powershell to be available" -Level Verbose
                    Restart-computer -ComputerName  $config.AXSFServerNames -Force -Wait -for PowerShell -Delay 2
                }
                else {
                    Write-PSFMessage -Message "Restarting $($config.AXSFServerNames)" -Level Verbose
                    Restart-computer -ComputerName  $config.AXSFServerNames -Force -Verbose
                }  
            }
        }
        else {
            foreach ($AppNode in $AppNodes) {
                Restart-ServiceFabricNode -NodeName $AppNode.NodeName -CommandCompletionMode Verify -Timeout 200
            }
        }
        [int] $timer = 0
        do {
            $OrchestratorServerName = $ConnectedOrchestratorServerName
            Write-PSFMessage -Message "Verbose: Disconnected Connection Reaching out to $OrchestratorServerName to try and connect to the service fabric." -Level Verbose
                
            $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
            if (!$module) {
                $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
            }
            Write-PSFMessage -Message "-ConnectionEndpoint $($ConnectedSFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
            $connectionnew = Connect-ServiceFabricCluster -ConnectionEndpoint $ConnectedSFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My 
            if (!$connectionnew) {
                Write-PSFMessage -Message "Verbose: Sleeping 10 seconds to try and reconnect to service fabric at $ConnectedSFConnectionEndpoint." -Level Verbose
                Start-Sleep -Seconds 10
                $timer = $timer + 10
            }
                
        } until ($connectionnew -or ($timer -gt $Timeout))
        
      
        Start-Sleep -Seconds 5
        [int]$timeoutondisablecounter = 0
        $nodestatus = Get-ServiceFabricNode | Where-Object { $_.NodeStatus -eq 'Disabled' -and (($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType")) }
        do {
            $nodestatus = Get-ServiceFabricNode | Where-Object { $_.NodeStatus -eq 'Disabled' -and (($_.NodeType -eq "AOSNodeType") -or ($_.NodeType -eq "MRType")) } 
            $timeoutondisablecounter = $timeoutondisablecounter + 5
            Start-Sleep -Seconds 5
        } until (!$nodestatus -or $nodestatus -eq 0 -or ($timeoutondisablecounter -gt $Timeout))
        Write-PSFMessage -Message "All App Nodes Enabled" -Level VeryVerbose

        do {
            try {
                $apps = Get-ServiceFabricApplication -ErrorAction Stop
                Start-Sleep -Seconds 5
            }
            catch {}
        } until ($apps.count -gt 0)
        $counterofhealthyapps = 0
        foreach ($app in $apps) {
            $health = Get-serviceFabricApplicationHealth -ApplicationName $app.ApplicationName

            if ($health.aggregatedhealthstate -eq "Ok") {
                $counterofhealthyapps = $counterofhealthyapps + 1
            }
            else {
                Write-PSFMessage -Level Warning -Message "Warning: $($health.ApplicationName) is Unhealthy"
                if ($waittillhealthy) {
                    $timer = 0
                    Write-PSFMessage -Message "Waiting for $($app.ApplicationName) to be healthy" -Level VeryVerbose`
                    do {
                        $health = Get-serviceFabricApplicationHealth -ApplicationName $app.ApplicationName
                        $timer = $timer + 10
                        Start-Sleep -Seconds 10
                        Write-PSFMessage -Message "Waiting for $($app.ApplicationName) to be healthy" -Level VeryVerbose
                    } until ($health.aggregatedhealthstate -eq "Ok" -or $timer -gt $Timeout)
                    Write-PSFMessage -Message "Health AggregatedHealthState is $($health.aggregatedhealthstate)" -Level VeryVerbose
                }
                if ($timer -gt $Timeout) {
                    Write-PSFMessage -Message "Warning: Timeout occured $Timeout seconds" -Level Warning
                }
                else {
                    if ($waittillhealthy) {
                        $RealHealth = Get-D365LBDEnvironmentHealth -ComputerName $ConnectedOrchestratorServerName | Where-Object { $_.Name -eq "ServiceFabricApplications" }
                        if ($RealHealth.State -eq "Operational") {
                            Write-PSFMessage -Level VeryVerbose -Message "All Service Fabric Apps are up"
                        }
                        else {
                            $timer = 0
                            while ($RealHealth.state -ne "Operational" -and $timer -le $Timeout) {
                                $timer = $timer + 10
                                Write-PSFMessage -Level VeryVerbose -Message "Sleeping before next check of health"
                                Start-Sleep -Seconds 10
                                $RealHealth = Get-D365LBDEnvironmentHealth -ComputerName $ConnectedOrchestratorServerName | Where-Object { $_.Name -eq "ServiceFabricApplications" }
                            }
                        }
                        Write-PSFMessage -Level VeryVerbose -Message "$RealHealth"
                    }
                }
            }

        }
    }
    END {}
}

function Send-D365LBDUpdateMSTeams {
    <#
   .SYNOPSIS
  Created to Send D365 updates to MSTeams
  .DESCRIPTION
Created to Send D365 updates to MSTeams
  .EXAMPLE
  Send-D365LBDUpdateMSTeams -messageType "StatusReport" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -config $config
 
  .EXAMPLE
Send-D365LBDUpdateMSTeams -messageType "BuildPrepStarted" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -config $config -build 'FakeBuildNumber'
 
  .EXAMPLE
Send-D365LBDUpdateMSTeams -messageType "BuildPrepped" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -config $config -CustomModuleName 'CUS'
 
  .EXAMPLE
Send-D365LBDUpdateMSTeams -messageType "BuildStart" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -MSTeamsBuildName '1.1.2021' -CustomModuleName 'CUS'
 
 .EXAMPLE
Send-D365LBDUpdateMSTeams -messageType "BuildComplete" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -MSTeamsBuildName '1.1.2021' -CustomModuleName 'CUS'
 
 .EXAMPLE
Send-D365LBDUpdateMSTeams -messageType "PlainText" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -PlainTextTitle 'TITLE' -PlainTextMessage 'Message'
 
 .EXAMPLE
  Send-D365LBDUpdateMSTeams -messageType "StatusReport" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -config $config -MSTeamsExtraDetailsTitle 'FactTitle' -MSTeamsExtraDetails 'Fact Text' -MSTeamsExtraDetailsURI 'http://google.com'
 
 .EXAMPLE
Send-D365LBDUpdateMSTeams -messageType "PlainText" -MSTeamsURI "htts://fakemicrosoft.office.com/webhookb2/98984684987156465-4654/incominginwebhook/ea5s6d4sa6" -PlainTextTitle 'TITLE' -PlainTextMessage 'Message'
 
 
  #>

    [alias("Send-D365UpdateMSTeams")]
    [CmdletBinding()]
    param
    (
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [string]$MSTeamsURI,
        [string]$MSTeamsExtraDetailsURI,
        [string]$MSTeamsExtraDetails,
        [string]$MSTeamsExtraDetailsTitle,
        [string]$MSTeamsBuildName,
        [string]$MSTeamsBuildURL,
        [string]$MSTeamsCustomStatus,
        [string]$MessageType,
        [string]$CustomModuleName,
        [string]$EnvironmentName,
        [string]$EnvironmentURL,
        [string]$PlainTextMessage,
        [string]$PlainTextTitle,
        [switch]$StatusReportIgnorePermissionErrors,
        [string]$PlaintTextStatus
    )
    BEGIN {
    }
    PROCESS {
        switch ( $MessageType) {
            "PreDeployment" { Stop-PSFFunction -Message "PreDeployment use Set-D365LBDOptions" }
            "PostDeployment" { Stop-PSFFunction -Message "PostDeployment use Set-D365LBDOptions" }
            "BuildStart" { $status = 'Build Started' }
            "BuildComplete" { $status = 'Build Completed' }
            "BuildPrepStarted" { $status = 'Build Prep Started' }
            "BuildPrepped" { $status = 'Build Prepped' }
            "StatusReport" { $Status = "Status Report" }
            "PlainText" {$Status = $PlaintTextStatus }
            default { Stop-PSFFunction -Message "Message type $MessageType is not supported" }
        }
        if ($MSTeamsCustomStatus) {
            $status = "$MSTeamsCustomStatus"
        }
        if (!$MSTeamsURI) {
            Write-PSFMessage -Level VeryVerbose -Message "MSTeamsURI not defined attemping to find in config"
            if (!$CustomModuleName) {
                if (!$Config) {
                    $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName -HighLevelOnly 
                } 
            }
            else {
                if (!$Config) {
                    $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly 
                }      
            }
            $AgentShareLocation = $config.AgentShareLocation 
            $EnvironmentAdditionalConfig = get-childitem "$AgentShareLocation\scripts\D365FOLBDAdmin\AdditionalEnvironmentDetails.xml"
            [xml]$EnvironmentAdditionalConfigXML = get-content $EnvironmentAdditionalConfig.FullName
        
            $MSTeamsURIS = $EnvironmentAdditionalConfigXML.D365LBDEnvironment.Communication.Webhooks.Webhook | Where-Object { $_.Type.'#text'.Trim() -eq "MSTeams" }
           
            if (!$MSTeamsURI -and !$MSTeamsURIS) {
                Stop-PSFFunction -Message "Error: MS Teams URI not specified and can't find one in configs" -EnableException $true -Cmdlet $PSCmdlet
            }
        }
        
        if (!$MSTeamsURIS) {
            $MSTeamsURIS = $MSTeamsURI
        }
        if (!$CustomModuleName -and $MessageType -eq "BuildPrepped") {
            if (!$Config) {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly 
            } 
            $CustomModuleName = $Config.CustomModuleName
            if (!$CustomModuleName -and !$MSTeamsBuildName) {
                Stop-PSFFunction -Message "ERROR: CustomModuleName NOT DEFINED and MSTeamsBuildName NOT DEFINED." -EnableException $true -Cmdlet $PSCmdlet
            }
            if (!$CustomModuleName -and $MSTeamsBuildName) {
                $CustomModuleName = "CustomModule"
            }
        }

        if (($CustomModuleName) -and $MessageType -eq "BuildPrepped" -and ($MSTeamsBuildName)) {
            ## BUILD PREPPED Beginning
            Write-PSFMessage -Level VeryVerbose -Message "MessageType is: BuildPrepped - BuildName has been defined ($MSTeamsBuildName)"
            if (!$EnvironmentName) {
                if (!$CustomModuleName -and $CustomModuleName -ne "CustomModule") {
                    if (!$Config) {
                        $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName -HighLevelOnly 
                    }
                }
                else {
                    if (!$Config) {
                        $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly 
                    }
                }
                $LCSEnvironmentName = $Config.LCSEnvironmentName
                $clienturl = $Config.clienturl
                $LCSEnvironmentURL = $Config.LCSEnvironmentURL
            }
            if (!$EnvironmentName) {
                $bodyjson = @"
{
     "@type": "MessageCard",
     "@context": "http://schema.org/extensions",
     "themeColor": "ff0000",
    "title": "$LCSEnvironmentName $status",
      "summary": "$LCSEnvironmentName $status",
      "sections": [{
      "facts": [{
       "name": "Environment",
       "value": "[$LCSEnvironmentName]($clienturl)"
         },{
        "name": "Build Version/Name",
        "value": "$MSTeamsBuildName"
         },{
         "name": "LCS",
         "value": "[LCS]($LCSEnvironmentURL)"
        }],
         "markdown": true
          }]
}
"@

            }
            else {
                $bodyjson = @"
{
     "@type": "MessageCard",
     "@context": "http://schema.org/extensions",
     "themeColor": "ff0000",
    "title": "$EnvironmentName $status ",
      "summary": "$EnvironmentName $status",
      "sections": [{
      "facts": [{
       "name": "Environment",
       "value": "[$EnvironmentName]($EnvironmentURL)"
         },{
        "name": "Build Version/Name",
        "value": "$MSTeamsBuildName"
         }],
         "markdown": true
          }]
}
"@


            }
            $bodyjsonformed = 1
        }
        ##
        if (($CustomModuleName) -and $MessageType -eq "BuildPrepped" -and $bodyjsonformed -ne 1) {
            Write-PSFMessage -Level VeryVerbose -Message "MessageType is: BuildPrepped - BuildName has NOT been defined"
            if (!$CustomModuleName -and !$Config) {
                $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName -HighLevelOnly 
            }
            else {
                if (!$Config) {
                    $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly 
                }
            }
            $Prepped = Export-D365LBDAssetModuleVersion -CustomModuleName $CustomModuleName -config $Config
            if ($Prepped) {
                if ($Prepped.Count -eq 1) {
                    Write-PSFMessage -Message "Found a prepped build: $Prepped" -Level VeryVerbose
                    $LCSEnvironmentName = $Config.LCSEnvironmentName
                    $clienturl = $Config.clienturl 
                    $LCSEnvironmentURL = $Config.LCSEnvironmentURL
                    $bodyjson = @"
{
                    "@type": "MessageCard",
                    "@context": "http://schema.org/extensions",
                    "themeColor": "ff0000",
                    "title": "$status $LCSEnvironmentName",
                    "summary": "$status $LCSEnvironmentName",
                    "sections": [{
                        "facts": [{
                            "name": "Environment",
                            "value": "[$LCSEnvironmentName]($clienturl)"
                        },{
                            "name": "Build Version/Name",
                            "value": "$Prepped"
                        },{
                            "name": "LCS",
                            "value": "[LCS]($LCSEnvironmentURL)"
                        }],
                        "markdown": true
                    }]
                }
"@

                    $bodyjsonformed = 1
                }
                else {
                    foreach ($build in $Prepped) {
                        Write-PSFMessage -Message "Found multiple prepped builds including: $build" -Level VeryVerbose
                    }
                }
            } ## if preppfound end starting else to find the latest built
                
            if ($bodyjsonformed -ne 1) {
                Write-PSFMessage -Level VeryVerbose -Message "No newly prepped build found" ##add logic to grab latest
                $MSTeamsBuildName = $Config.LastFullyPreppedCustomModuleAsset
                if ($EnvironmentName) {
                    $LCSEnvironmentName = $EnvironmentName
                }
                else {
                    $LCSEnvironmentName = $config.LCSEnvironmentName
                }  
                
                $clienturl = $Config.clienturl
                $LCSEnvironmentURL = $Config.LCSEnvironmentURL
                $Prepped = $config.LastFullyPreppedCustomModuleAsset
                if (!$MSTeamsBuildName) {
                    Write-PSFMessage -Message "Can't find Version removing from json"
 
                    $bodyjson = @"
{
                                        "@type": "MessageCard",
                                        "@context": "http://schema.org/extensions",
                                        "themeColor": "ff0000",
                                        "title": "$LCSEnvironmentName $status",
                                        "summary": "$LCSEnvironmentName $status",
                                        "sections": [{
                                            "facts": [{
                                                "name": "Environment",
                                                "value": "[$LCSEnvironmentName]($clienturl)"
                                            },{
                                                "name": "LCS",
                                                "value": "[LCS]($LCSEnvironmentURL)"
                                            }],
                                            "markdown": true
                                        }]
                                    }
"@


                }
                else {
                    $bodyjson = @"
{
                    "@type": "MessageCard",
                    "@context": "http://schema.org/extensions",
                    "themeColor": "ff0000",
                    "title": "$LCSEnvironmentName $status",
                    "summary": "$LCSEnvironmentName $status",
                    "sections": [{
                        "facts": [{
                            "name": "Environment",
                            "value": "[$LCSEnvironmentName]($clienturl)"
                        },{
                            "name": "Build Version/Name",
                            "value": "$MSTeamsBuildName"
                        },{
                            "name": "LCS",
                            "value": "[LCS]($LCSEnvironmentURL)"
                        }],
                        "markdown": true
                    }]
                }
"@

                }
                          
            }
        } ## end of build prep
        
        if ($MessageType -eq "PlainText") {
            Write-PSFMessage -Level VeryVerbose -Message "MessageType is: Plain Text Message" 
            if ($PlainTextTitle) {
                Write-PSFMessage -Level VeryVerbose -Message "Plain Text Message with Custom Title" 
                $bodyjson = @"
                {
                    "title":"$($("$PlainTextTitle $status").trim())",
                    "text":"$PlainTextMessage"
                }
"@

            }
            else {
                Write-PSFMessage -Level VeryVerbose -Message "Plain Text Message"              
                $bodyjson = @"
{
    "title":"$($("D365 Update $status").trim())",
    "text":"$PlainTextMessage"
}
"@


            }
            if ($MSTeamsExtraDetails) {
                $bodyjson = @"
                {
                                        "@type": "MessageCard",
                                        "@context": "http://schema.org/extensions",
                                        "themeColor": "ff0000",
                                        "title": "$PlainTextTitle $status",
                                        "summary": "$PlainTextTitle $PlainTextMessage",
                                        "sections": [{
                                            "facts": [{
                                                "name": "$PlainTextTitle",
                                                "value": "$PlainTextMessage"
                                            }],
                                            "markdown": true
                                        }]
                                    }
"@
                
            }
        } ## PLAIN TEXT END


        if ($MessageType -eq "BuildStart") {
            Write-PSFMessage -Message "MessageType is: BuildStart" -Level VeryVerbose
            if (!$MSTeamsBuildName) {
                Stop-PSFFunction -Message "Error: MSTEAMSBuildName needs to be defined" -EnableException $true -Cmdlet $PSCmdlet
            }
            else {
                if ($MSTeamsBuildURL) {
                    $bodyjson = @"
{
                        "@type": "MessageCard",
                        "@context": "http://schema.org/extensions",
                        "themeColor": "ff0000",
                        "title": "$status",
                        "summary": "$status",
                        "sections": [{
                            "facts": [{
                                "name": "Build Version",
                                "value": "[$MSTeamsBuildName]($MSTeamsBuildURL)"
                            }],
                            "markdown": true
                        }]
                    }
"@

                }
                else {
                    $bodyjson = @"
{
                        "@type": "MessageCard",
                        "@context": "http://schema.org/extensions",
                        "themeColor": "ff0000",
                        "title": "$status",
                        "summary": "$status",
                        "sections": [{
                            "facts": [{
                                "name": "Build Version",
                                "value": "$MSTeamsBuildName"
                            }],
                            "markdown": true
                        }]
                    }
"@

                }

            }
        }

        if ($MessageType -eq "BuildComplete") {
            Write-PSFMessage -Message "MessageType is: BuildComplete" -Level VeryVerbose
            if (!$MSTeamsBuildName) {
                Stop-PSFFunction -Message "Error: MSTEAMSBuildName needs to be defined" -EnableException $true -Cmdlet $PSCmdlet
            }
            else {
                if ($MSTeamsBuildURL) {
                    $bodyjson = @"
{
                        "@type": "MessageCard",
                        "@context": "http://schema.org/extensions",
                        "themeColor": "ff0000",
                        "title": "$status",
                        "summary": "$status",
                        "sections": [{
                            "facts": [{
                                "name": "Build Version",
                                "value": "[$MSTeamsBuildName]($MSTeamsBuildURL)"
                            }],
                            "markdown": true
                        }]
                    }
"@

                }
                else {
                    $bodyjson = @"
{
    "@type": "MessageCard",
    "@context": "http://schema.org/extensions",
    "themeColor": "ff0000",
    "title": "$status",
    "summary": "$status",
    "sections": [{
        "facts": [{
            "name": "Build Version",
            "value": "$MSTeamsBuildName"
        }],
        "markdown": true
    }]
}
"@

                }
            }
        }

        if ($MessageType -eq "BuildPrepStarted") {   
            Write-PSFMessage -Message "MessageType is: Build Prep Started" -Level VeryVerbose
            if (!$CustomModuleName) {
                if (!$Config) {    
                    $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName -HighLevelOnly 
                }
            }
            else {
                if (!$Config) {
                    $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly 
                }
            }
            $LCSEnvironmentName = $Config.LCSEnvironmentName
            $clienturl = $Config.clienturl
            $LCSEnvironmentURL = $Config.LCSEnvironmentURL
            
            if (!$MSTeamsBuildName) {
                Stop-PSFFunction -Message "Error: MSTEAMSBuildName needs to be defined" -EnableException $true -Cmdlet $PSCmdlet
            }
            $bodyjson = @"
{
     "@type": "MessageCard",
     "@context": "http://schema.org/extensions",
     "themeColor": "ff0000",
    "title": "$LCSEnvironmentName $status",
      "summary": "$LCSEnvironmentName $status",
      "sections": [{
      "facts": [{
       "name": "Environment",
       "value": "[$LCSEnvironmentName]($clienturl)"
         },{
        "name": "Build Version/Name",
        "value": "$MSTeamsBuildName"
         },{
         "name": "LCS",
         "value": "[LCS]($LCSEnvironmentURL)"
        }],
         "markdown": true
          }]
}
"@

        }

        if ($MessageType -eq "StatusReport") {   
            Write-PSFMessage -Message "MessageType is: StatusReport" -Level VeryVerbose
            if (!$CustomModuleName) {
                if (!$Config) { 
                    $Config = Get-D365LBDConfig -ComputerName $ComputerName 
                }
            }
            else {
                if (!$Config) {
                    $Config = Get-D365LBDConfig -ComputerName $ComputerName -CustomModuleName $CustomModuleName
                }
            }
            [int]$count = 0
            while (!$connection) {
                do {
                    $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                    Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                    $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                    if (!$module) {
                        $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                    }
                    Write-PSFMessage -Message "-ConnectionEndpoint $($config.SFConnectionEndpoint) -X509Credential -FindType FindByThumbprint -FindValue $($config.SFServerCertificate) -ServerCertThumbprint $($config.SFServerCertificate) -StoreLocation LocalMachine -StoreName My" -Level Verbose
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                    if (!$connection) {
                        $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                    }
                    $count = $count + 1
                    if (!$connection) {
                        Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                    }
                } until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count))
                if (($count -eq $($Config.OrchestratorServerNames).Count) -and (!$connection)) {
                    Stop-PSFFunction -Message "Error: Can't connect to Service Fabric"
                }
            }
            $TotalApplications = (Get-ServiceFabricApplication).Count
            $HealthyApps = (Get-ServiceFabricApplication | Where-Object { $_.HealthState -eq "OK" }).Count
            if (!$EnvironmentName) {
                $LCSEnvironmentName = $Config.LCSEnvironmentName
            }
            else {
                $LCSEnvironmentName = $EnvironmentName
            }
            if (!$EnvironmentURL) {
                $EnvironmentURL = $Config.ClientURL
            }
            
            if (!$MSTeamsBuildName) {
                $MSTeamsBuildName = $Config.CustomModuleVersion

            }

            $Health = Get-D365LBDEnvironmentHealth -Config $config 
            if ($StatusReportIgnorePermissionErrors) {
                $Health = $Health | Where-Object { $_.Details -notlike "*Check Permissions" }
            }
            if ($Health.State -contains "Down") {
                foreach ($issue in $($health | Where-Object { $_.State -eq 'Down' })) {
                    $HealthCheck = "$HealthCheck" + "Down" + "$($issue.ExtraInfo)"
                }
            }
            else {
                $HealthCheck = "Operational"
            }

            $Dependency = Get-D365LBDDependencyHealth -config $Config
            if ($Dependency.State -contains "Down") {
                foreach ($issue in $($Dependency | Where-Object { $_.State -eq 'Down' })) {
                    $DependencyCheck = "$DependencyCheck" + "Down" + " $($issue.ExtraInfo)"
                }
            }
            else {
                $DependencyCheck = "Operational"
            }

            $bodyjson = @"
{
    "@type": "MessageCard",
    "@context": "http://schema.org/extensions",
    "themeColor": "ff0000",
    "title": "$LCSEnvironmentName $status",
    "summary": "$LCSEnvironmentName $status",
    "sections": [{
        "facts": [{
            "name": "Environment",
            "value": "[$LCSEnvironmentName]($EnvironmentURL)"
        },{
            "name": "Build Version",
            "value": "$MSTeamsBuildName"
        },{
            "name": "Healthy Apps/Total Apps",
            "value": "$HealthyApps / $TotalApplications"
        },{
            "name": "D365 Health Check",
            "value": "$HealthCheck"
        },{
            "name": "D365 Dependency Check",
            "value": "$DependencyCheck"
        }],
        "markdown": true
    }]
}
"@

        }

        if ($MSTeamsExtraDetails) {
            Write-PSFMessage -Level VeryVerbose -Message "Adding extra Details to JSON"
            if ($MSTeamsExtraDetailsURI) {    
                $Additionaljson = @"
    ,{
            "name": "$MSTeamsExtraDetailsTitle",
            "value": "[$MSTeamsExtraDetails]($MSTeamsExtraDetailsURI)"
        }],
"@

                $bodyjson = $bodyjson.Replace('],', "$Additionaljson")
            }
            else {
                $Additionaljson = @"
        ,{
                "name": "$MSTeamsExtraDetailsTitle",
                "value": "$MSTeamsExtraDetails"
            }],
"@

                $bodyjson = $bodyjson.Replace('],', "$Additionaljson")
            }
        }
        if (!$bodyjson) {
            Write-PSFMessage -Message "ERROR: JSON is empty!" -Level VeryVerbose
        }
        if ($MSTeamsURIS) {
            foreach ($MSTeamsURI in $MSTeamsURIS) {
                Write-PSFMessage -Message "Calling $MSTeamsURI with Post of $bodyjson" -Level VeryVerbose
                $WebRequestResults = Invoke-WebRequest -uri $MSTeamsURI -ContentType 'application/json' -Body $bodyjson -UseBasicParsing -Method Post -Verbose
                Write-PSFMessage -Message "$WebRequestResults" -Level VeryVerbose
            }
        }
    }
    END {
    }
}

function Set-D365LBDOptions {
    <#
   .SYNOPSIS
  Uses switches to set different deployment options created for expanding the pre and post deployment scripts.
  .DESCRIPTION
  Uses switches to set different deployment options created for expanding the pre and post deployment scripts.
  Recommend: Run multiple times for each task then the last run run with the teams communication.
  .EXAMPLE
  $config = Get-D365Config
  Set-D365LBDOptions -RemoveMR -predeployment -config $config
  Prevents the installation of Management reporter in the predeployment stage
  .EXAMPLE
   $config = Get-D365Config
    Set-D365LBDOptions -predeployment -enableuserid 'stefan' -config $config
    Enables user stefan in the predeployment stage
 .EXAMPLE
   $config = Get-D365Config
     Set-D365LBDOptions -predeployment -OtherTaskName 'TalkedToMyself' -OtherTaskStatus 'Success' -config $config
    Adds a custom task and status to the predeployment list for communication
  .EXAMPLE
   $config = Get-D365Config
    Set-D365LBDOptions -postdeployment -MSTEAMSCustomStatus 'Deployment Finished' -MSTeamsURI 'https://fake.outlook.com/webhook/fakeurl/123123' -MSTeamsBuildName '2021.03.04.01' -MSTeamsExtraDetails 'Web Search' -MSTeamsExtraDetailsURI 'https://google.com' -config $config
    Custom status of deployment finished and added an extra field called Web Search with a link to google. Also says the Build name as '2021.03.04.01' (recommend making a build name related to the config)
  #>

    [alias("Set-D365Options")]
    [CmdletBinding()]
    param
    (
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [switch]$PreDeployment,
        [switch]$PostDeployment,
        [switch]$RemoveMR,
        [switch]$MaintenanceModeOn,
        [switch]$MaintenanceModeOff,
        [string]$MSTeamsURI,
        [string]$MSTeamsExtraDetailsURI,
        [string]$MSTeamsExtraDetails,
        [string]$MSTeamsBuildName,
        [string]$MSTeamsCustomStatus,
        [string]$SQLQueryToRun,
        [string]$EnableUserid,
        [string]$DisableUserid,
        [string]$OtherTaskName,
        [string]$OtherTaskStatus
    )
    BEGIN {
    }
    PROCESS {
        if (!$Config -or $Config.OrchestratorServerNames.Count -eq 0) {
            Write-PSFMessage -Level VeryVerbose -Message "Config not defined or Config is invalid. Trying to Get new config using $ComputerName"
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly   
        }
        if ($PreDeployment) {
            Write-PSFMessage -Level Verbose -Message "PreDeployment Selected"
            $filenameprename = "PREDeployment"
        }
        if ($PostDeployment) {
            Write-PSFMessage -Level Verbose -Message "PostDeployment Selected"
            $filenameprename = "PostDeployment"
        }
        if ($Config) {
            $agentsharelocation = $Config.AgentShareLocation
            $AXDatabaseServer = $Config.AXDatabaseServer
            $AXDatabaseName = $Config.AXDatabaseName
            $LCSEnvironmentName = $Config.LCSEnvironmentName
            $clienturl = $Config.clienturl
            $LastRunbookTaskId = $Config.LastRunbookTaskId
            if (!$AXDatabaseServer) {
                $AXDatabaseServer = $config.databaseclusterservernames | select -First 1
                if (!$AXDatabaseServer) {
                    $AXDatabaseServer = $config.OrchDatabaseServer
                }
            }
        }
        if ((Test-Path $agentsharelocation\scripts\D365FOLBDAdmin) -eq $false) {
            
            new-item -path "$agentsharelocation\scripts\" -Name "D365FOLBDAdmin"  -ItemType "directory"
        }
        if ($null -eq $LastRunbookTaskId) {
            $norunbooktaskid = get-date -Format MMddyy
            if ((Test-Path $agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$norunbooktaskid.xml) -eq $false) {
                #$newfile = New-Item $agentsharelocation -path $agentsharelocation\scripts\D365FOLBDAdmin -Name "$filenameprename$norunbooktaskid.xml"
                @{} | Export-Clixml "$agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$norunbooktaskid.xml"

            }
            else {
                Write-PSFMessage -Level VeryVerbose -Message "$filenameprename$LastRunbookTaskId.xml already exists"
            }
        }
        else {
            if ((Test-Path $agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$LastRunbookTaskId.xml) -eq $false) {
                $newfile = New-Item -path $agentsharelocation\scripts\D365FOLBDAdmin -Name "$filenameprename$LastRunbookTaskId.xml"
                @{} | Export-Clixml "$agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$LastRunbookTaskId.xml"
                $CLIXML = Import-Clixml "$agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$LastRunbookTaskId.xml"
            }
            else {
                Write-PSFMessage -Level VeryVerbose -Message "$agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$LastRunbookTaskId.xml already exists"
                $newfile = Get-ChildItem $agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$LastRunbookTaskId.xml
                $CLIXML = Import-Clixml "$agentsharelocation\scripts\D365FOLBDAdmin\$filenameprename$LastRunbookTaskId.xml"
            } 
        }
        if ($OtherTaskName) {
            if (!$OtherTaskStatus) {
                $OtherTaskStatus = "Success"
            }
            $CLIXML += @{"$OtherTaskName" = "$OtherTaskStatus" }  
        }
        
        if ($RemoveMR) {
            Write-PSFMessage -Level Verbose -Message "Attempting to Remove MR"
            if ($PreDeployment -eq $True) {
                $JsonLocation = Get-ChildItem $AgentShareLocation\wp\*\StandaloneSetup-*\SetupModules.json | Sort-Object { $_.CreationTime } -Descending | Select-Object -First 1 
                $JsonLocationRoot = Get-ChildItem $AgentShareLocation\wp\*\StandaloneSetup-*\  | Sort-Object { $_.CreationTime } -Descending | Select-Object -First 1
                copy-item $JsonLocation.fullName -Destination $AgentShareLocation\OriginalSetupModules.json
                $json = Get-Content $JsonLocation.FullName -Raw | ConvertFrom-Json
                $json.components = $json.components | Where-Object { $_.name -ne 'financialreporting' }
                $json | ConvertTo-Json -Depth 100 | Out-File $JsonLocationRoot\Setupmodules.json -Force -Verbose
                $CLIXML += @{'Removed MR' = 'Success' }  
            }
            else {
                Write-PSFMessage -Message "Error: Can't remove MR during anything other than PreDeployment" -Level VeryVerbose
                $CLIXML += @{'Removed MR' = 'Failed - Cant run outside of predeployment' }
            }
        }
        function Invoke-SQL {
            param(
                [string] $dataSource = ".\SQLEXPRESS",
                [string] $database = "MasterData",
                [string] $sqlCommand = $(throw "Please specify a query.")
            )

            $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

            $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
            $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)
            $connection.Open()

            $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
            $dataset = New-Object System.Data.DataSet
            $adapter.Fill($dataSet) | Out-Null

            $connection.Close()
            $dataSet.Tables
        }

        if ($MaintenanceModeOn) {
            if (!$AXDatabaseServer) {
                Write-PSFMessage -Level Error -Message "Config does not have AX Database Server cant turn on maintenance mode"
            }
            Write-PSFMessage -Message "Turning On Maintenance Mode" -Level Verbose
            $SQLQuery = "update SQLSYSTEMVARIABLES SET VALUE = 1 Where PARM = 'CONFIGURATIONMODE'"
            $Sqlresults = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQuery
            if (!$PostDeployment -or !$PreDeployment) {
                foreach ($AXSFServer in $config.AXSFServerNames) {
                    Restart-Computer -ComputerName $AXSFServer -Force
                }
            }
            Write-PSFMessage -Message "$SQLresults" -Level VeryVerbose
            if ($Sqlresults) {
                $CLIXML += @{'Turned On Maintenance Mode' = "Success - $SQLQuery" }  
                Write-PSFMessage -Message "Turned On Maintenance Mode. Note AXSF needs to be restarted (or done as predeployment step) for maintenance mode to be fully on." -Level VeryVerbose
            }
            else {
                $CLIXML += @{'Turned Off Maintenance Mode' = "Success - $SQLQuery" }  
            }
        }

        if ($MaintenanceModeOff) {
            if (!$AXDatabaseServer) {
                Write-PSFMessage -Level Error -Message "Config does not have AX Database Server cant turn off maintenance mode"
            }
            Write-PSFMessage -Message "Turning Off Maintenance Mode" -Level Verbose
            $SQLQuery = "update SQLSYSTEMVARIABLES SET VALUE = 0 Where PARM = 'CONFIGURATIONMODE'"
            $Sqlresults = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQuery
            if ($PostDeployment -eq $false -or $PreDeployment -eq $false) {
                foreach ($AXSFServer in $config.AXSFServerNames) {
                    Restart-Computer -ComputerName $AXSFServer -Force
                }
            }
            Write-PSFMessage -Message "$SQLresults" -Level VeryVerbose
            if ($Sqlresults) {
                $CLIXML += @{'Turned Off Maintenance Mode' = "Success - $SQLQuery" }  
                Write-PSFMessage -Message "Turned Off Maintenance Mode. Note AXSF needs to be restarted (or done as predeployment step) for maintenance mode to be fully off." -Level VeryVerbose
            }
            else {
                $CLIXML += @{'Turned Off Maintenance Mode' = "Failed - $SQLQuery" }  
            }
        }

        if ($EnableUserid) {
            ##Trim 8 characters
            if (!$AXDatabaseServer) {
                Write-PSFMessage -Level Error -Message "Config does not have AX Database Server cant enable user"
            }
            Write-PSFMessage -Message "Enabling $EnableUserid. Note: User must already exist in system" -Level Verbose
            $SQLQuery = "update userinfo SET Enable = 1, RECVERSION = RECVERSION +1 Where id = '$EnableUserid'"
            $SQLQuery2 = "select * from userinfo where enable = 1 and id = '$EnableUserid'"
            $SqlresultsUpdate = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQuery
            $Sqlresults = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQuery2 
            if ($Sqlresults) {
                if ($PreDeployment -or $PostDeployment) {
                    $CLIXML += @{"Enable User $EnableUserid" = "Success - $SQLQuery" }  
                }
                Write-PSFMessage -Message "$EnableUserid enabled." -Level VeryVerbose
            }
            else {
                if ($PreDeployment -or $PostDeployment) {
                    $CLIXML += @{"Enable User $EnableUserid" = "Failed - $SQLQuery" } 
                } 
                Write-PSFMessage -Message "$EnableUserid enable failed." -Level VeryVerbose
            }
            Write-PSFMessage -Message "ID: $($SQLresults.ID) EnableFlag: $($SQLresults.Enable) " -Level VeryVerbose
        }
            
        if ($DisableUserid) {
            if (!$AXDatabaseServer) {
                Write-PSFMessage -Level Error -Message "Config does not have AX Database Server cant disable user"
            }
            else {
                Write-PSFMessage -Message "Disabling $DisableUserid. Note: User must already exist in system" -Level Verbose
                $SQLQuery = "update userinfo SET Enable = 0, RECVERSION = RECVERSION +1 Where id = '$DisableUserid'"
                $SQLQuery2 = "select * from userinfo where enable = 0 and id = '$DisableUserid'"
                $SQLQuery3 = "SELECT [USER_] ,[SECURITYROLE],  t2.NAME, t2.AOTNAME  FROM [dbo].[SECURITYUSERROLE]  t1  inner join  [SECURITYROLE] t2 on t1.SECURITYROLE=t2.RECID  where USER_ = '$DisableUserid'"
                $SqlresultsUpdate = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQuery 
                $Sqlresults2 = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQuery2
                $Sqlresults3 = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQuery3 
                Write-PSFMessage -Message "ID: $($SQLresults2.ID) EnableFlag: $($SQLresults2.Enable) " -Level VeryVerbose
                Write-PSFMessage -Message "User in the following groups" -Level VeryVerbose
                Write-PSFMessage -Message "$($($Sqlresults3.Name) -join ', ')"
            }
            if ($Sqlresults2) {
                if ($PreDeployment -or $PostDeployment) {
                    $CLIXML += @{'Disable User' = "Success - $SQLQuery" }  
                }
                write-PSFMessage -Message "$DisableUserid disabled." -Level VeryVerbose
            }
            else {
                if ($PreDeployment -or $PostDeployment) {
                    $CLIXML += @{'Disable User' = "Failed - $SQLQuery" }  
                }
                Write-PSFMessage -Message "$DisableUserid disable failed." -Level VeryVerbose
            }
        }

        if ($SQLQueryToRun) {
            if (!$AXDatabaseServer) {
                Write-PSFMessage -Level Error -Message "Config does not have AX Database Server cant run SQL command"
            }
            $Sqlresults = invoke-sql -datasource $AXDatabaseServer -database $AXDatabaseName -sqlcommand $SQLQueryToRun
            Write-PSFMessage -Message "$SQLresults" -Level VeryVerbose
            $CountofSQLScripts = $($CLIXML.GetEnumerator() | Where-Object { $_.Name -like "SQL*" }).Count
            $CountOfSQLScripts = $CountofSQLScripts + 1
            if ($Sqlresults) {
                $CLIXML += @{"SQL$CountOfSQLScripts" = "Success - $SQLQueryToRun" }  
            }
            else {
                $CLIXML += @{"SQL$CountOfSQLScripts" = "Failed - $SQLQueryToRun" }  
            }
        }
        ##EXPORT FILE AFTER CHANGES
        $CLIXML | Export-Clixml $newfile.FullName

        if ($MSTeamsURI) {
            Write-PSFMessage -Level VeryVerbose -Message "MSTeamsURI defined sending message"
            $MSTeamsFormmatedJSONofCLIItems = ""
            foreach ($XMLItem in $CLIXML.GetEnumerator()) {
                $WorkingJSON = @"
,{
"name": "$($XMLItem.Name)",
"value": "$($XMLItem.Value)"
}
"@

                $MSTeamsFormmatedJSONofCLIItems += $WorkingJSON
            }

            if ($PreDeployment) {
                $status = 'PreDeployment Started'
            }
            if ($PostDeployment) {
                $status = 'Deployment Finished. PostDeployment Started'
            }
            if ($MSTeamsCustomStatus) {
                $status = "$MSTeamsCustomStatus"
            }
            if (!$MSTeamsBuildName) {
                $MSTeamsBuildName = $config.LastFullyPreppedCustomModuleAsset
            }
            if ($MSTeamsFormmatedJSONofCLIItems) {
                $bodyjson = @"
                {
                    "@type": "MessageCard",
                    "@context": "http://schema.org/extensions",
                    "themeColor": "ff0000",
                    "title": "D365 $LCSEnvironmentName $status",
                    "summary": "D365 $LCSEnvironmentName $status",
                    "sections": [{
                        "facts": [{
                            "name": "Environment",
                            "value": "[$LCSEnvironmentName]($clienturl)"
                        },{
                            "name": "Build Version/Name",
                            "value": "$MSTeamsBuildName"
                        },{
                            "name": "Status",
                            "value": "$status"
                        }$MSTeamsFormmatedJSONofCLIItems],
                        "markdown": true
                    }]
                }
"@

            }
            else {
                $bodyjson = @"
                {
                    "@type": "MessageCard",
                    "@context": "http://schema.org/extensions",
                    "themeColor": "ff0000",
                    "title": "D365 $LCSEnvironmentName $status",
                    "summary": "D365 $LCSEnvironmentName $status",
                    "sections": [{
                        "facts": [{
                            "name": "Environment",
                            "value": "[$LCSEnvironmentName]($clienturl)"
                        },{
                            "name": "Build Version/Name",
                            "value": "$MSTeamsBuildName"
                        },{
                            "name": "Status",
                            "value": "$status"
                        }],
                        "markdown": true
                    }]
                }
"@

            }
            if ($MSTeamsExtraDetails) {
                if ($MSTeamsFormmatedJSONofCLIItems) {
                    $bodyjson = @"
                    {
                        "@type": "MessageCard",
                        "@context": "http://schema.org/extensions",
                        "themeColor": "ff0000",
                        "title": "D365 $LCSEnvironmentName $status",
                        "summary": "D365 $LCSEnvironmentName $status",
                        "sections": [{
                            "facts": [{
                                "name": "Environment",
                                "value": "[$LCSEnvironmentName]($clienturl)"
                            },{
                                "name": "Build Version",
                                "value": "$MSTeamsBuildName"
                            },{
                                "name": "Details",
                                "value": "[$MSTeamsExtraDetails]($MSTeamsExtraDetailsURI)"
                            },{
                                "name": "Status",
                                "value": "$status"
                            }$MSTeamsFormmatedJSONofCLIItems],
                            "markdown": true
                        }]
                    }
"@

                }
                else {
                    $bodyjson = @"
{
    "@type": "MessageCard",
    "@context": "http://schema.org/extensions",
    "themeColor": "ff0000",
    "title": "D365 $LCSEnvironmentName $status",
    "summary": "D365 $LCSEnvironmentName $status",
    "sections": [{
        "facts": [{
            "name": "Environment",
            "value": "[$LCSEnvironmentName]($clienturl)"
        },{
            "name": "Build Version",
            "value": "$MSTeamsBuildName"
        },{
            "name": "Details",
            "value": "[$MSTeamsExtraDetails]($MSTeamsExtraDetailsURI)"
        },{
            "name": "Status",
            "value": "$status"
        }],
        "markdown": true
    }]
}
"@

                }
            }
            Write-PSFMessage -Message "Calling $MSTeamsURI with Post of $bodyjson" -Level VeryVerbose
            $WebRequestResults = Invoke-WebRequest -uri $MSTeamsURI -ContentType 'application/json' -Body $bodyjson -UseBasicParsing -Method Post -Verbose
            Write-PSFMessage -Message "$WebRequestResults" -Level VeryVerbose
        }
    }
    END {
    }
}


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 -config $config -SQLuser 'axdbadmin' -sqluserpassword 'fakepassword123' -verbose
    .EXAMPLE
    Start-D365FOLBDDBSync -AXSFSERVER 'axsfserver01' -axdatabaseserver 'db01' -axdatabasename 'axdb' -SQLuser 'axdbadmin' -sqluserpassword 'fakepassword123' -verbose
   .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 should be FQDN
   .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,
            ParameterSetName = 'NoConfig')]
        [string]$AXSFServer, ## Remote execution needs to be tested and worked on use localhost until then
        [Parameter(Mandatory = $true,
            ParameterSetName = 'NoConfig')]
        [string]$AXDatabaseServer, ##FQDN
        [Parameter(Mandatory = $true,
            ParameterSetName = 'NoConfig')]
        [string]$AXDatabaseName,
        [Parameter(Mandatory = $true)]
        [string]$SQLUser,
        [Parameter(Mandatory = $true)]
        [string]$SQLUserPassword,
        [int]$Timeout = 60,
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [switch]$Wait
    )
    
    begin {
    }
    process {
        $starttime = Get-date
        if (!$Config -and !$AXSFServer) {
            $Config = Get-D365LBDConfig -ComputerName $ComputerName -HighLevelOnly
        }
        if ($Config) {
            $AXDatabaseServer = $Config.AXDatabaseServer
            $AXDatabaseName = $Config.AXDatabaseName
            $AXSFServer = $Config.SourceAXSFServer
            Write-PSFMessage -Level VeryVerbose -Message "Sync will be using AXSF Server: $AXSFServer and Database Server: $AXDatabaseServer DB: $AXDatabaseName"
        }
        $LatestEventinLog = $(Get-WinEvent -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -maxevents 1 -computername $AXSFServer -ErrorAction Stop).TimeCreated
        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
            
            Write-PSFMessage -Level Verbose -Message "$($D365DeploymentExe.FullName)"
            Write-PSFMessage -Level Verbose -Message '-metadatadir {0} --bindir {1} --sqlserver {2} --sqldatabase {3} --sqluser {4} --sqlpwd removed --setupmode sync --syncmode fullall --isazuresql false --verbose true' -f $AXSFCodePackagesFolder, $AXSFCodePackagesFolder, $AXDatabaseServer, $AXDatabaseName, $SQLUser
               
            $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 {
            ##REMOTE START
            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           
            $AXSFCodePackagesFolder = Invoke-Command -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"
                $AXSFCodePackagesFolder
            }
            $D365DeploymentExe = Invoke-Command -ComputerName $AXSFServer -ScriptBlock { 
                $AXSFCodeFolder = Split-Path $(Get-Process | Where-Object { $_.name -eq "AXService" }).Path -Parent
                $AXSFCodeBinFolder = Join-Path $AXSFCodeFolder "\bin"
                $D365DeploymentExe = Get-ChildItem $AXSFCodeBinFolder | Where-Object { $_.Name -eq "Microsoft.Dynamics.AX.Deployment.Setup.exe" }
                $D365DeploymentExe
            }
            $CommandLineArgs2 = "$('-metadatadir {0} --bindir {1} --sqlserver {2} --sqldatabase {3} --sqluser {4} --sqlpwd removed --setupmode sync --syncmode fullall --isazuresql false --verbose true' -f $AXSFCodePackagesFolder, $AXSFCodePackagesFolder, $AXDatabaseServer, $AXDatabaseName, $SQLUser)"
            Write-PSFMessage -Level Verbose -Message "$CommandLineArgs2"
             $session = New-PSSession -ComputerName $AXSFServer
            invoke-command -Session $session -ScriptBlock {
            $CommandLineArgs = '--metadatadir {0} --bindir {1} --sqlserver {2} --sqldatabase {3} --sqluser {4} --sqlpwd {5} --setupmode sync --syncmode fullall --isazuresql false --verbose true' -f $using:AXSFCodePackagesFolder, $using:AXSFCodePackagesFolder, $using:AXDatabaseServer, $using:AXDatabaseName, $using:SQLUser, $using:SQLUserPassword
            if ($using:Wait) {
                $DBSyncProcess = Start-Process -file $using:D365DeploymentExe.fullname -ArgumentList "$CommandLineArgs" -Wait
            }
            else {
                Start-Process -file $using:D365DeploymentExe.fullname -ArgumentList "$CommandLineArgs" -Wait
                Start-Sleep -Seconds 5
            }
        } -ArgumentList $D365DeploymentExe, $AXSFCodePackagesFolder, $AXSFCodePackagesFolder, $AXDatabaseServer, $AXDatabaseName, $SQLUser, $SQLUserPassword, $Wait
           Remove-PSSession $session
 
        }
        $currtime = Get-date
        $timediff = New-TimeSpan -Start $starttime -End $currtime
        $LatestEventinLogNew = $(Get-WinEvent -LogName Microsoft-Dynamics-AX-DatabaseSynchronize/Operational -maxevents 1 -computername $AXSFServer -ErrorAction Stop).TimeCreated
        if ($LatestEventinLogNew -eq $LatestEventinLog ) {
            Write-PSFMessage -Level Verbose -Message "No deployment happened, check username/password or SQL cert expiration"
        }
        else {
            Write-PSFMessage -Level Verbose -Message "Database Sync took $timediff"
        }
    }
    end {
    }
}

function Start-D365LBDDeploymentSleep {
        <#
    .SYNOPSIS
Watches the deployment of a D365 LBD package
   .DESCRIPTION
Watches the deployment of a D365 LBD package. Recommend to use with exported config
   .EXAMPLE
   $config = Get-D365Config -ConfigImportFromFile "C:\environment\environment.xml"
Start-D365LBDDeploymentSleep -config $config
   .EXAMPLE
 
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
     
   #>

    [alias("Start-D365DeploymentSleep")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(Mandatory = $true,
            ValueFromPipeline = $True)][psobject]$Config,
        [int]$TimeOutMinutes = 400
    )
    BEGIN {
    }
    PROCESS {
        $Runtime = 0
        $count = 0
        Write-PSFMessage -Level VeryVerbose -Message "Recommend always use an exported valid config not a live config"

        if (!$connection) {
            do {
                $OrchestratorServerName = $config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                if (!$module) {
                    $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
                if ($connection) {
                    Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $config.ConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                }
                if (!$connection) {
                    $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My
                    if ($connection) {
                        Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                    }
                }
                if (!$connection) {
                    $connection = Connect-ServiceFabricCluster
                    if ($connection) {
                        Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster"
                    }
                }
                $count = $count + 1
                if (!$connection) {
                    Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                }
            } until ($connection -or ($count -eq $($config.OrchestratorServerNames).Count) -or ($($config.OrchestratorServerNames).Count) -eq 0)
        }

        do { 
            $logscurrent = Get-D365LBDOrchestrationLogs -Config $config -NumberofEvents 4
            Start-Sleep -Seconds 60
            Write-PSFMessage -Level VeryVerbose -Message "Waiting for StandaloneSetup to start Runtime: $Runtime" 
            $logs = Get-D365LBDOrchestrationLogs -Config $config -NumberofEvents 4
            if (Compare-Object $logs -DifferenceObject $logscurrent -Property Eventdetails) {
                foreach ($log in $logs) {
                    if ($logscurrent.Eventdetails -contains $log.Eventdetails) {}else {
                        Write-PSFMessage -Level VeryVerbose -Message "$log"
                    }
                    if ($log.EventMessage -like "Execution of custom powershell script*"){
                        Write-PSFMessage -Level VeryVerbose -Message "$log"
                        $time = $(get-date).AddMinutes(-15)
                        $customscriptlogs = get-childitem  "$($config.AgentShareLocation)\scripts\logs" | Where-Object {$_.CreationTime -gt $time}
                        foreach ($customscriptlog in $customscriptlogs){
                            Write-PSFMessage -Level VeryVerbose -Message "BEGIN Log: $($CustomscriptLog.Name)"
                            $customlogcontent = Get-Content $customscriptlog.FullName
                            Write-PSFMessage -Level VeryVerbose -Message "$customlogcontent"
                            Write-PSFMessage -Level VeryVerbose -Message "END Log: $($CustomscriptLog.Name)"

                        }
                    }
                    #Write-PSFMessage -Level VeryVerbose -Message "$log"
                }
                
            } 
            $Runtime = $Runtime + 1
            $logscurrent = $logs
            $count = 0
            if (!$logs) {
                do {
                    $OrchestratorServerName = $config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                    Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                    $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                    if (!$module) {
                        $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 -KeepAliveIntervalInSec 400
                    if ($connection) {
                        Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $config.ConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                    }
                    if (!$connection) {
                        $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My -KeepAliveIntervalInSec 400
                        if ($connection) {
                            Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                        }
                    }
                    if (!$connection) {
                        $connection = Connect-ServiceFabricCluster -KeepAliveIntervalInSec 400
                        if ($connection) {
                            Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster"
                        }
                    }
                    $count = $count + 1
                    if (!$connection) {
                        Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                    }
                } until ($connection -or ($count -eq $($config.OrchestratorServerNames).Count) -or ($($config.OrchestratorServerNames).Count) -eq 0)
            }

            $atStandaloneSetupexecution = $logs | Where-Object { $_.eventmessage -like "*StandaloneSetup*" }

        }
        until($atStandaloneSetupexecution -or $Runtime -gt $TimeOutMinutes) 

        if ($Runtime -gt $TimeOutMinutes) {
            return "Failed"
            Stop-PSFFunction -Message "Error: Failed did not complete within $TimeOutMinutes minutes"  -EnableException $true -Cmdlet $PSCmdlet
        }
        $logscurrent = Get-D365LBDOrchestrationLogs -Config $config -NumberofEvents 4
        do {
            Start-Sleep -Seconds 60
            $Runtime = $Runtime + 1
            Write-PSFMessage -Message "Waiting for AXSF to be created. Runtime: $Runtime"  -Level VeryVerbose
            $apps = $(get-servicefabricclusterhealth | Select-Object ApplicationHealthStates).ApplicationHealthStates
            Write-PSFMessage -Level VeryVerbose -Message "Apps Current status $apps" 
            if (!$apps){
                Write-PSFMessage -Level VeryVerbose -Message "Lost connection reconnecting to SF"
                do {
                    $OrchestratorServerName = $Config.OrchestratorServerNames | Select-Object -First 1 -Skip $count
                    Write-PSFMessage -Message "Verbose: Reaching out to $OrchestratorServerName to try and connect to the service fabric" -Level Verbose
                    $SFModuleSession = New-PSSession -ComputerName $OrchestratorServerName
                    if (!$module) {
                        $module = Import-Module -Name ServiceFabric -PSSession $SFModuleSession 
                       ## Import-PSSession -Session $SFModuleSession
                    }
                    $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $config.SFConnectionEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My  -KeepAliveIntervalInSec 400
                    if (!$connection) {
                        $trialEndpoint = "https://$OrchestratorServerName" + ":198000"
                        $connection = Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $config.SFServerCertificate -ServerCertThumbprint $config.SFServerCertificate -StoreLocation LocalMachine -StoreName My -KeepAliveIntervalInSec 400
                        if ($connection) {
                            Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster -ConnectionEndpoint $trialEndpoint -X509Credential -FindType FindByThumbprint -FindValue $ServerCertificate -ServerCertThumbprint $ServerCertificate -StoreLocation LocalMachine -StoreName My"
                        }
                    }
                    if (!$connection) {
                        $connection = Connect-ServiceFabricCluster -KeepAliveIntervalInSec 400
                        if ($connection) {
                            Write-PSFMessage -Message "Connected to Service Fabric Via: Connect-ServiceFabricCluster"
                        }
                    }
                    $count = $count + 1
                    if (!$connection) {
                        Write-PSFMessage -Message "Count of servers tried $count" -Level Verbose
                    }
                }  until ($connection -or ($count -eq $($Config.OrchestratorServerNames).Count) -or ($($Config.OrchestratorServerNames).Count) -eq 0)
            }
          
            $AXSF = $apps | Where-Object { $_.ApplicationName -eq 'fabric:/AXSF' }
            if ($AXSF) {
                Write-PSFMessage -message "Found AXSF Running" -Level veryVerbose
            }

            $logs = Get-D365LBDOrchestrationLogs -Config $config -NumberofEvents 4
            if (Compare-Object $logs -DifferenceObject $logscurrent -Property Eventdetails) {
                foreach ($log in $logs) {
                    if ($logscurrent.Eventdetails -contains $log.Eventdetails) {}else {
                        if ($log.EventMessage -like "Execution of custom powershell script*"){
                            Write-PSFMessage -Level VeryVerbose -Message "$log"
                            $time = $(get-date).AddMinutes(-15)
                            $customscriptlogs = get-childitem  "$($config.AgentShareLocation)\scripts\logs" | Where-Object {$_.CreationTime -gt $time}
                            foreach ($customscriptlog in $customscriptlogs){
                                Write-PSFMessage -Level VeryVerbose -Message "BEGIN Log: $($CustomscriptLog.Name)"
                                $customlogcontent = Get-Content $customscriptlog.FullName
                                Write-PSFMessage -Level VeryVerbose -Message "$customlogcontent"
                                Write-PSFMessage -Level VeryVerbose -Message "END Log: $($CustomscriptLog.Name)"

                            }
                        }
                        Write-PSFMessage -Level VeryVerbose -Message "$log"
                    }
                }
            }
            $logscurrent = $logs
            $FoundError = $logs | Where-Object { $_.EventMessage -like "status of job*Error" }
            if ($FoundError) {
                $Deployment = "Failure"
            }

        }until ($AXSF -or $Deployment -eq 'Failure' -or $Runtime -gt $TimeOutMinutes)
        if ($Runtime -gt $TimeOutMinutes -or $Deployment -eq 'Failure') {
            return "Failed"
            Stop-PSFFunction -Message "Error: The Deployment failed. Stopping" -EnableException $true -Cmdlet $PSCmdlet
        }

        do {
            $DBeventscurrent = Get-D365DBEvents -Config $config -NumberofEvents 5
            Start-Sleep -Seconds 120
            $Runtime = $Runtime + 2
            $logs = Get-D365LBDOrchestrationLogs -Config $config -NumberofEvents 4
            $FoundSuccess = $logs | Where-Object { $_.EventMessage -like "status of job*Success" }
            $FoundError = $logs | Where-Object { $_.EventMessage -like "status of job*Error" }
            $logs = Get-D365LBDOrchestrationLogs -Config $config -NumberofEvents 4
            if (Compare-Object $logs -DifferenceObject $logscurrent -Property Eventdetails) {
                foreach ($log in $logs) {
                    if ($logscurrent.Eventdetails -contains $log.Eventdetails) {}else {
                        Write-PSFMessage -Level VeryVerbose -Message "$log"
                    }
                }
            }
            $logscurrent = $logs
            if ($FoundSuccess) {
                $Deployment = "Success"
            }
            if ($FoundError) {
                $Deployment = "Failure"
            }
            if ($FoundRecentDBSync -eq "Yes"){
                $DBevents = Get-D365DBEvents -OnlyThisDBServer $newconfig.DBSyncServerWithLatestLog -NumberofEvents 5
            }else{
            $DBevents = Get-D365DBEvents -Config $config -NumberofEvents 5
        }
            if (Compare-Object $DBevents -DifferenceObject $DBeventscurrent -Property EventMessage ) {
                $RightNow = Get-Date
                $15MinsAgo = $RightNow.AddMinutes(-15)
                foreach ($event in $DBevents) {
                    if ((($event.message -contains "Table synchronization failed.") -or ($event.message -contains "Database Synchronize Succeeded.") -or ($event.message -contains "Database Synchronize Failed.")) -and $SyncStatusFound -eq $false) {
                        if (($event.message -contains "Table synchronization failed.") -or ($event.message -contains "Database Synchronize Failed.")) {
                            Write-PSFMessage -Message "Found a DB Sync failure $event" -Level Verbose
                            $DBSyncStatus = "Failed"
                            $DBSyncTimeStamp = $event.TimeCreated
                        }
                        if ($event.message -contains "Database Synchronize Succeeded.") {
                            Write-PSFMessage -Message "Found a DB Sync Success $event" -Level Verbose
                            $DBSyncStatus = "Succeeded"
                            $DBSyncTimeStamp = $event.TimeCreated
                        }
                        $SyncStatusFound = $true
                    }
                    if ($DBeventscurrent -contains $event) {}else {
                        Write-PSFMessage -Level VeryVerbose -Message "DBSyncLog $Event"
                    }
                    if ($event.TimeCreated -gt $15MinsAgo){
                        $FoundRecentDBSync = "Yes"
                        if (!$newconfig){
                            Write-PSFMessage -Level VeryVerbose -Message "Found a recent Database event getting a fresh config"
                            $newconfig = get-d365config -ComputerName $config.SourceAXSFServer -highlevelonly
                        }
                    }
                    else{
                        $FoundRecentDBSync = "nos"
                    }
                }
            }
            if ($DBSyncStatus) {
                Write-PSFMessage -Level VeryVerbose -Message "Found Database Sync Status: $DBSyncStatus" 
                foreach ($event in $DBevents) {
                    Write-PSFMessage -Level VeryVerbose -Message "$event"  
                }
            }
            $DBeventscurrent = $DBevents
        }
        until($Deployment -eq "Success" -or $Deployment -eq "Failure")

        Write-Verbose "$Deployment" -Verbose
        if ($Deployment -eq "Failure") {
            return "Failed"
            Stop-PSFFunction -Message "Error: The Deployment failed. Stopping" -EnableException $true -Cmdlet $PSCmdlet
        }
        else{
            Write-PSFMessage -Level VeryVerbose -Message "Deployment status = Success"
            return "Success"
        }

    }
    END {
    }
}

function Start-D365LBDSleepForNewAssetPrep {
    [alias("Start-D365SleepForNewAssetPrep")]
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(Mandatory = $true)][string]$CustomModuleName,
        [int]$TimeOutMinutes = 400,
        [psobject]$Config

    )
    $Runtime = 0
    if (!$config) {
        $config = Get-D365Config -ComputerName "$Computername" -CustomModuleName "$CustomModuleName" -HighLevelOnly
    }
    $config = Get-D365Config -ComputerName $config.SourceAXSFServer -CustomModuleName "$CustomModuleName" -HighLevelOnly
    $LatestFullyPreppedVersion = $config.LastFullyPreppedCustomModuleAsset
    $CustommoduleVersion = $config.CustomModuleVersion
    $CheckforOldPrepped = Export-D365AssetModuleVersion -CustomModuleName $CustomModuleName -Config $config

    Write-PSFMessage -Level VeryVerbose -message "Currently running $CustommoduleVersion with a prepped version of $LatestFullyPreppedVersion"
    Write-verbose "Timeout set to $TimeOutMinutes minutes" -verbose
    do {
        Write-PSFMessage -Level VeryVerbose "Looking for new build new prep every minute. Runtime: $runtime" -Verbose
        Start-Sleep -Seconds 60
        $Runtime = $Runtime + 1
        $newversion = Export-D365AssetModuleVersion -CustomModuleName $CustomModuleName -Config $config
    }
    until($newversion -or $Runtime -gt $TimeOutMinutes)
  
    if ($Runtime -gt $TimeOutMinutes) {
        Stop-PSFFunction -Message "Error: Timeout hit. Stopping" -EnableException $true -Cmdlet $PSCmdlet
    }
    else {
        $Updatedconfig = Get-D365Config -ComputerName $config.SourceAXSFServer -CustomModuleName "$CustomModuleName" -HighLevelOnly
        Write-PSFMessage -Level VeryVerbose -Message "$($Updatedconfig.LastFullyPreppedCustomModuleAsset) newversion has been prepped. Took $Runtime"
        Write-PSFMessage -Level VeryVerbose -Message "RunBook Task $($Updatedconfig.LastRunbookName) has a state is $($Updatedconfig.OrchestratorJobRunBookState) of been prepped"
        $Updatedconfig 
    }

}




function Update-ServiceFabricD365ClusterConfig {
    <# TODO: More testing to be done
    .SYNOPSIS
   
   .DESCRIPTION
    
   .EXAMPLE
   Update-ServiceFabricD365ClusterConfig
   
   .EXAMPLE
    Update-ServiceFabricD365ClusterConfig -ComputerName "LBDServerName" -verbose
    
   .PARAMETER ComputerName
   String
   The name of the D365 LBD Server to grab the environment details; needed if a config is not specified and will default to local machine.
   .PARAMETER Config
    Custom PSObject
    Config Object created by either the Get-D365LBDConfig or Get-D365TestConfigData function inside this module
 
   #>

    [CmdletBinding()]
    param([Parameter(ValueFromPipeline = $True,
            ValueFromPipelineByPropertyName = $True,
            Mandatory = $false,
            HelpMessage = 'D365FO Local Business Data Server Name')]
        [PSFComputer]$ComputerName = "$env:COMPUTERNAME",
        [Parameter(ParameterSetName = 'Config',
            ValueFromPipeline = $True)]
        [psobject]$Config,
        [string]$Workingfolder = "C:\temp"
    )
       
    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