Public/SC_Helpers.ps1

<#
.SYNOPSIS
    Test Exchange Online connectivity
.DESCRIPTION
    Checks ExchangeOnlineManagement connection information and token expiry.
    Imports ExchangeOnlineManagement if it is not loaded. Returns a Boolean status;
    connection checks can also query accepted domains and update the cached tenant information.
.PARAMETER showDefaultDomain
    Emit the default accepted domain before the Boolean status when a valid session
    is found. With this switch, the success output is not just a single Boolean.
.PARAMETER Connect
    Attempt browser-based authentication for a missing or expired session only when
    the module's InteractiveSession flag is set. This is not an unconditional reconnect.
    After connecting, call the command again to verify the new session status.
.EXAMPLE
    Test-SC365ConnectionStatus
     
    Tests the connection to Exchange Online without any parameters.
    Returns $true if connected and token is valid, $false otherwise.
    Performs a quick check of the current session state.
.EXAMPLE
    Test-SC365ConnectionStatus -Verbose
     
    Tests the connection with verbose output for troubleshooting.
    Displays detailed information about token expiry time, module name, and connection status.
    Useful for diagnosing connectivity issues and session validation.
.EXAMPLE
    Test-SC365ConnectionStatus -showDefaultDomain
     
    Tests the connection and displays the current default email domain.
    Returns both connection status and the tenant's default accepted domain.
    Helpful for confirming which tenant you're connected to.
.EXAMPLE
    Test-SC365ConnectionStatus -Connect
     
    Attempts to connect if the module considers the session interactive.
    Call Test-SC365ConnectionStatus again afterwards to verify the connection.
.EXAMPLE
    if (Test-SC365ConnectionStatus) { Write-Host "Connected!" }
     
    Uses the cmdlet in a conditional statement to verify connectivity.
    Execute commands only when properly connected to Exchange Online.
    Common pattern in automation scripts.
.INPUTS
    Inputs (if any)
.OUTPUTS
    true/false
 
#>

function Test-SC365ExoConnStatus
{
    [CmdLetBinding(
        #HelpURI = ''
    )]
    Param
    (
        [Parameter(
            Mandatory=$false,
            HelpMessage = 'If turned on, the CmdLet will emit the current default domain'
        )]
        [switch]$showDefaultDomain,

        [Parameter(
            Mandatory=$false,
            HelpMessage = 'If turned on, the CmdLet will try to connect to Exchange Online is disconnected'
        )]
        [switch]$Connect

    )

    [bool]$isConnected = $false

    Write-Verbose "Check if module ExchangeOnlineManagement is imported"
    if(!(Get-Module ExchangeOnlineManagement -ErrorAction SilentlyContinue))
    {
        Write-Warning "ExchangeOnlineManagement module not yet imported, importing ..."

        if(!(Import-Module ExchangeOnlineManagement -PassThru -ErrorAction SilentlyContinue))
        {throw [System.Exception] "ExchangeOnlineManagement module does not seem to be installed! Use 'Install-Module ExchangeOnlineManagement' to install.'"}
    }
    else
    {
        $ExoConnInfo = if (Get-Connectioninformation) {(Get-ConnectionInformation)[-1]}

        if ($ExoConnInfo) {
            Write-Verbose "Connected to Exchange Online Tenant $($ExoConnInfo.TenantID)"
            if ((!($global:tenantAcceptedDomains)) -or ((Get-AcceptedDomain) -ne $tenantAcceptedDomains) ) {
                try {
                    $global:tenantAcceptedDomains = Get-AcceptedDomain -Erroraction silentlycontinue
                }
                catch {
                    Write-Error "Cannot detect accepted domains, maybe disconnected. Connect to Exchange Online and load the module again!"
                    break
                }       
            }
            [datetime]$TokenExpiryTimeLocal = $ExoConnInfo.TokenExpiryTimeUTC.Datetime.ToLocalTime()
            $delta = New-TimeSpan -Start (Get-Date) -End $TokenExpiryTimeLocal
            $ticks = $delta.Ticks
            if ($ticks -like '-*') # Token expired
            {
                $isconnected = $false
                Write-Warning "You're not actively connected to your Exchange Online organization. TOKEN is EXPIRED"
                if(($InteractiveSession) -and ($Connect))# defined in public/Functions.ps1
                {
                    try
                    {
                        # throws an exception if authentication fails
                        Write-Verbose "Reconnecting to Exchange Online"
                        Connect-ExchangeOnline -SkipLoadingFormatData
                        $isConnected = $true
                    }
                    catch
                    {
                        throw [System.Exception] "Could not connect to Exchange Online, please retry."}
                }
                else {
                    $isConnected = $false
                }
                
            }
            else # Valid connection
            {
                $tokenLifeTime = [math]::Round($delta.TotalHours)
                Write-verbose "Active session token exipry time is $TokenExpiryTimeLocal (roughly $tokenLifeTime hours)"
                $tmpModuleName = Split-Path -Path $ExoConnInfo.ModuleName -Leaf
                Write-verbose "Active session Module name is $tmpModuleName"
                
                $isConnected = $true
                    
                [string] $Script:ExODefaultDomain = Get-AcceptedDomain | Where-Object{$_.Default} | Select-Object -ExpandProperty DomainName -First 1
                if ($showDefaultDomain) {"$Script:ExoDefaultdomain"}
            }
            } 
            else # No Connection
            {
                if(($InteractiveSession) -and ($connect)) # defined in public/Functions.ps1
                {
                    try
                    {
                        # throws an exception if authentication fails
                        Write-Verbose "Connecting to Exchange Online"
                        Connect-ExchangeOnline -SkipLoadingFormatData
                    }
                    catch
                    {
                        throw [System.Exception] "Could not connect to Exchange Online, please retry."}
                }
                else {
                    $isConnected = $false
                }
            }
    }
    return $isConnected
}

<#
.SYNOPSIS
    Test Microsoft Entra ID connectivity.
.DESCRIPTION
    Checks the Microsoft Graph context and verifies connectivity using Get-MgOrganization.
    Returns a single Boolean. Imports the required Graph modules when needed.
    Organization.Read.All or another sufficient organization read permission is required.
    Failed checks return $false with a warning. Verbose output includes organization name,
    tenant ID, default verified domain, tenant type, account, authentication type and scopes.
.PARAMETER showDefaultDomain
    Retained for compatibility. The default domain is now included in verbose output
    only; this switch never adds a domain string to the Boolean success output.
.PARAMETER Connect
    Sign in with Organization.Read.All if no Graph context exists, then verify the
    connection in the same call. Without this switch, no login is started.
    An existing context is checked without reconnecting or changing its permissions.
.EXAMPLE
    Test-SC365EntraConnStatus
     
    Returns $true if the organization can be read, otherwise $false.
.EXAMPLE
    Test-SC365EntraConnStatus -Verbose
     
    Also displays readable organization and authentication details.
.EXAMPLE
    Test-SC365EntraConnStatus -showDefaultDomain -Verbose
     
    Displays the default domain on the verbose stream, retaining Boolean success output.
.EXAMPLE
    Test-SC365EntraConnStatus -Connect
     
    Signs in if needed and returns the verified connection status.
.EXAMPLE
    if (Test-SC365EntraConnStatus) { Write-Host "Connected!" }
     
    Executes commands only if the organization can be read.
.INPUTS
    None.
.OUTPUTS
    System.Boolean
.NOTES
    See https://github.com/seppmail/SEPPMAIL365cloud/blob/main/README.md for more
#>

function Test-SC365EntraConnStatus
{
    [CmdLetBinding(
        # HelpURI = 'https://docs.seppmail.com/<TBD>'
    )]
    Param
    (
        [Parameter(
            Mandatory=$false,
            HelpMessage = 'Compatibility switch; use -Verbose to display the default domain'
        )]
        [switch]$showDefaultDomain,

        [Parameter(
            Mandatory=$false,
            HelpMessage = 'If turned on, the CmdLet will try to connect to EntraID Online if disconnected'
        )]
        [switch]$Connect
    )
    try
    {
        $requiredmodules = @(
            'Microsoft.Graph.Authentication'
            'Microsoft.Graph.Identity.DirectoryManagement'
            'Microsoft.Graph.Applications'
            'Microsoft.Graph.Groups'
        )
        foreach ($moduleName in $requiredmodules)
        {
            if (!(Get-Module $moduleName))
            {
                Write-Verbose "Importing $moduleName"
                Import-Module $moduleName -ErrorAction Stop
            }
        }

        $scopes = @(
            'Application.ReadWrite.All'
            'AppRoleAssignment.ReadWrite.All'
            'Group.Read.All'
            'Organization.Read.All'
        )        
        $context = Get-MgContext -ErrorAction Stop
        if (!$context -and $Connect)
        {
            Write-Verbose "Connecting to Microsoft Entra ID"
            Connect-MgGraph -Scopes $scopes -NoWelcome -ErrorAction Stop | Out-Null
            $context = Get-MgContext -ErrorAction Stop
        }
        if (!$context)
        {
            Write-Verbose "Not connected to Microsoft Entra ID. Use Connect-MGGraph to sign in."
            return $false
        }

        $organization = Get-MgOrganization -Property Id, DisplayName, VerifiedDomains, TenantType -ErrorAction Stop |
            Select-Object -First 1
        if (!$organization)
        {
            Write-Warning "Microsoft Entra ID connection check failed: no organization was returned."
            return $false
        }

        $defaultDomain = $organization.VerifiedDomains |
            Where-Object { $_.IsDefault } | Select-Object -ExpandProperty Name -First 1
        if (!$defaultDomain) { $defaultDomain = 'Not available' }

        Write-Verbose "Organization: $($organization.DisplayName)"
        Write-Verbose "Tenant ID: $($organization.Id)"
        Write-Verbose "Default domain: $defaultDomain"
        Write-Verbose "Tenant type: $($organization.TenantType)"
        Write-Verbose "Account: $($context.Account)"
        Write-Verbose "Authentication type: $($context.AuthType)"
        Write-Verbose "Scopes: $($context.Scopes -join ', ')"
        return $true
    }
    catch
    {
        Write-Warning "Microsoft Entra ID connection check failed. Verify your Graph login and organization read permissions: $($_.Exception.Message)"
        return $false
    }
}

<#
.SYNOPSIS
    Validates if a given strig (domainname) is the tenant default maildomain
.DESCRIPTION
    It takes the string and prooves if the domain is a member of the tenant. If this fails, the function returns an error and stops.
    If the domain is a tenant-member it returns true/false if its the domain default.
.PARAMETER ValidationDomain
    Required domain to compare with the accepted domains cached by the module.
    Returns $true for the default domain and $false for another accepted domain.
    A domain outside the tenant produces an error. Establish a connection and populate
    the accepted-domain cache before calling this function.
.NOTES
    - none -
.LINK
    - none -
.EXAMPLE
    Confirm-SC365TenantDefaultDomain -ValidationDomain 'contoso.eu'
     
    Validates if contoso.eu is the tenant's default domain.
    Returns $true if it's the default domain, $false if it's a member but not default.
    Writes an error if the domain is not part of the tenant at all.
.EXAMPLE
    Confirm-SC365TenantDefaultDomain -ValidationDomain 'contoso.com'
     
    Checks whether contoso.com is the default accepted domain.
    Useful for validating domain configurations before setup.
    Ensures operations target the correct domain in multi-domain tenants.
#>

function Confirm-SC365TenantDefaultDomain {
    param (
        [CmdLetBinding()]

        [Parameter(Mandatory = $true)]
        [String]$ValidationDomain
    )

    begin {
        $TenantDefaultDomain = $TenantAcceptedDomains.Where({$_.Default -eq $true}).DomainName     
    }
    process {
        If (!($TenantAcceptedDomains.DomainName -contains $ValidationDomain)) {
            Write-Error "$ValidationDomain is not member of the connected tenant. Retry using only tenant-domains (Use CmdLet: Get-AcceptedDomain)"
            break
        } else {
            if ($Validationdomain -eq $TenantDefaultDomain) {
                return $true
            } else {
                return $false
            }    
        }
    }
    end {
    }
}
<#
.SYNOPSIS
    Display Office/Microsoft365 Tenant Information
.DESCRIPTION
    Shows detailed information about the connected Exchange Online tenant.
    Displays tenant name, regions, Exchange version, and feature settings.
.EXAMPLE
    Show-SC365Tenant
     
    Displays comprehensive tenant information including:
    - Tenant Name and DisplayName
    - Default and Allowed Mailbox Regions
    - Exchange Version
    - SendFromAliasEnabled status
    - Grace period status
.EXAMPLE
    Show-SC365Tenant | Format-List
     
    Shows tenant information in detailed list format.
    Useful for comprehensive review of tenant configuration.
    Displays all properties with full values.
.EXAMPLE
    $tenantInfo = Show-SC365Tenant
    $tenantInfo.DefaultMailboxRegion
     
    Stores tenant information in a variable for further processing.
    Access specific properties like DefaultMailboxRegion.
    Useful in automation scripts for conditional logic.
.INPUTS
    None. This command has no function-specific parameters.
.OUTPUTS
    A custom object containing tenant name, regions, Exchange version and feature settings.
.NOTES
    See https://github.com/seppmail/SEPPMAIL365cloud/blob/main/README.md for more
#>

Function Show-SC365Tenant {
    [CmdLetBinding(
        # HelpURI = 'https://github.com/seppmail/SEPPMAIL365cloud/blob/main/README.md#setup-the-integration'
    )]
    param (
    )

    if(!(Test-SC365ConnectionStatus)) {
        throw [System.Exception] "You're not connected to Exchange Online - please connect prior to using this CmdLet"
    } else {
        Write-Verbose "Connected to Exchange Organization `"$Script:ExODefaultDomain`"" -InformationAction Continue
        try {
            $where = Get-OrganizationConfig
            $youare = [PSCustomobject]@{
                                 'Name' = $where.Name 
                          'DisplayName' = $where.DisplayName 
                 'DefaultMailboxRegion' = $where.DefaultMailboxRegion 
                'AllowedMailboxRegions' = $where.AllowedMailboxRegions 
                      'ExchangeVersion' = $where.ExchangeVersion
                 'SendFromAliasEnabled' = $where.SendFromAliasEnabled
                'IsTenantInGracePeriod' = $Where.IsTenantInGracePeriod        
                }
            return $youare
         } catch {
            Write-Error $Error[0].Message   
        }    
    }


}

<#
.SYNOPSIS
    Read DateTime of SEPPMAIL.cloud Setup
.DESCRIPTION
    Reads WhenCreated from the first matching SEPPMAIL.cloud inbound connector and
    emits a formatted string with the creation time and age in days. The installation
    date extracted from connector comments is written to the verbose stream.
.INPUTS
    None. This command has no function-specific parameters.
.OUTPUTS
    A formatted string, not a DateTime object. A missing connector produces a warning.
.NOTES
    none
.LINK
    none
.EXAMPLE
    Get-SC365SetupTime
     
    Displays when the SEPPMAIL.cloud setup was created.
    Shows the creation timestamp of the Inbound Connector.
    Example output: "Create time was 03/20/2023 10:56:04 (13 days ago)"
.EXAMPLE
    Get-SC365SetupTime -Verbose
     
    Shows setup time with additional verbose information.
    Displays how many days ago the setup was created.
    Shows the installation date from connector comments.
     
    Example output:
    Create time was 03/20/2023 10:56:04 (13 days ago)
    VERBOSE: Inbound Connector SEPPMAIL Setup Comments writes install date is: 03/20/2023 10:56:04
.EXAMPLE
    $setupSummary = Get-SC365SetupTime
    Write-Host $setupSummary
     
    Stores and displays the formatted summary. It is not a DateTime value.
    For date calculations, read WhenCreated directly with Get-InboundConnector.
#>

Function Get-SC365SetupTime {
    [CmdLetBinding()]

    param ()

    begin {
        if(!(Test-SC365ConnectionStatus)) {
            throw [System.Exception] "You're not connected to Exchange Online - please connect prior to using this CmdLet"
            break
        }
    }
    process {
        $ibc = Get-InboundConnector -Identity '[SEPPMAIL.Cloud]*' -ErrorAction SilentlyContinue| select-object -first 1 -ErrorAction SilentlyContinue
        if ($ibc) {
            $createDateTime = $ibc|Select-Object -ExpandProperty WhenCreated

            $days = (New-Timespan -Start (Get-Date $ibc.WhenCreated) -End (Get-Date)).Days
            Write-Output "Create time was $createDateTime ($days days ago)"
            $commentstime = ((($ibc.comment|select-String 'Created with') -split 'version').trim()[-1] -split 'on').trim()[-1]
            Write-Verbose "Inbound Connector SEPPMAIL Setup Comments writes install date is: $commentsTime"
        } else {
            Write-Warning "No inbond connector found, no or incomplete Setup"
        }
    }
    end{}
}

<#
.SYNOPSIS
    Read DateTime of SEPPMAIL Appliance Integration Setup
.DESCRIPTION
    Reads the Creation Time of the SEPPMAIL Appliance Integration Inbound Connector and emits dateTime of the moment the setup occured.
.NOTES
    none
.LINK
    none
.EXAMPLE
    Get-SM365SetupTime
     
    Displays when the SEPPMAIL.cloud setup was created.
    Shows the creation timestamp of the Inbound Connector.
    Example output: "Monday, March 20, 2023 10:56:04"
.EXAMPLE
    Get-SM365SetupTime -Verbose
     
    Shows setup time with additional verbose information.
    Displays how many days ago the setup was created.
    Shows the installation date from connector comments.
     
    Example output:
    Create time was 03/20/2023 10:56:04 (13 days ago)
    VERBOSE: Inbound Connector SEPPMAIL Setup Comments writes install date is: 03/20/2023 10:56:04
.EXAMPLE
    $setupDate = Get-SM365SetupTime
    if ((New-TimeSpan -Start $setupDate -End (Get-Date)).Days -gt 30) { Write-Host "Setup is older than 30 days" }
     
    Stores the setup time and performs date calculations.
    Useful for checking configuration age in automation scripts.
    Can trigger maintenance or update workflows.
#>

Function Get-SM365SetupTime {
    [CmdLetBinding()]

    param ()

    begin {
        if(!(Test-SM365ConnectionStatus)) {
            throw [System.Exception] "You're not connected to Exchange Online - please connect prior to using this CmdLet"
            break
        }
    }
    process {
        $ibc = Get-InboundConnector -Identity '[SEPPMAIL]*' -ErrorAction SilentlyContinue| select-object -first 1 -ErrorAction SilentlyContinue
        if ($ibc) {
            $createDateTime = $ibc|Select-Object -ExpandProperty WhenCreated

            $days = (New-Timespan -Start (Get-Date $ibc.WhenCreated) -End (Get-Date)).Days
            Write-Output "Create time was $createDateTime ($days days ago)"
            $commentstime = ((($ibc.comment|select-String 'Created with') -split 'version').trim()[-1] -split 'on').trim()[-1]
            Write-Verbose "Inbound Connector SEPPMAIL Setup Comments writes install date is: $commentsTime"
        } else {
            Write-Warning "No inbond connector found, no or incomplete Setup"
        }
    }
    end{}
}


<#
.SYNOPSIS
    Read Office/Microsoft365 Azure TenantID
.DESCRIPTION
    Every Exchange Online is part of some sort of Microsoft Subscription and each subscription has an Azure Active Directory included. We need the TenantId to identify managed domains in seppmail.cloud
.PARAMETER maildomain
    Required domain belonging to the Microsoft 365 tenant. Alias: SEPPMAILCloudDomain.
    Queries the public OpenID configuration endpoint to resolve the tenant ID.
    Requires network access, but does not require an Exchange Online connection.
.EXAMPLE
    Get-SC365TenantID -MailDomain 'contoso.de'
     
    Retrieves the Azure Tenant ID for the domain contoso.de.
    Returns the GUID identifier for the Microsoft 365 tenant.
    Example output: "12345678-1234-1234-1234-123456789abc"
.EXAMPLE
    Get-SC365TenantID -SEPPMAILCloudDomain 'contoso.com'
     
    Uses the alias parameter name to get the Tenant ID.
    Both -MailDomain and -SEPPMAILCloudDomain work identically.
    Useful for maintaining script compatibility.
.EXAMPLE
    $tenantId = Get-SC365TenantID -MailDomain 'contoso.eu'
    Write-Host "Your Tenant ID is: $tenantId"
     
    Stores the Tenant ID in a variable for further use.
    Useful in scripts that require the Tenant ID for other operations.
    Common in certificate-based connector configurations.
.INPUTS
    Maildomain as string (mandatory)
.OUTPUTS
    TenantID (GUID) as string
.NOTES
    See https://github.com/seppmail/SEPPMAIL365cloud/blob/main/README.md for more
#>

Function Get-SC365TenantID {
    [CmdLetBinding(
        # HelpURI = 'https://github.com/seppmail/SEPPMAIL365cloud/blob/main/README.md#setup-the-integration'
    )]
    param (
        [Parameter(Mandatory=$true)]
        [Alias('SEPPMAILCloudDomain')]
        [string]$maildomain
    )

    $uri = 'https://login.windows.net/' + $maildomain + '/.well-known/openid-configuration'
    $TenantId = (Invoke-WebRequest $uri| ConvertFrom-Json).token_endpoint.Split('/')[3]
    Return $tenantid
}

<#
.SYNOPSIS
    Convert a DNS domain to IDNA Format
.DESCRIPTION
    The CmdLet uses the System.Globalization.IdnMapping .NET Method to convert a DNS Domain with special characters like ä, ü, or ß to the IDNA format.
.PARAMETER String
    Required Unicode domain name to convert to ASCII-compatible IDNA encoding.
    Accepts a string from the pipeline. No Exchange Online connection is required.
.NOTES
    none
.LINK
    none
.EXAMPLE
    ConvertTo-SC365IDNA -String 'öbb.at'
     
    Converts the domain with special characters to IDNA format.
    Returns: "xn--bb-eka.at"
    Required for DNS operations with internationalized domain names.
.EXAMPLE
    'münchen.de' | ConvertTo-SC365IDNA
     
    Uses pipeline input to convert a domain with umlauts.
    Returns the ASCII-compatible encoding (ACE) format.
    Useful for batch processing multiple domains.
.EXAMPLE
    $domains = @('öbb.at', 'münchen.de', 'zürich.ch')
    $domains | ConvertTo-SC365IDNA
     
    Converts multiple internationalized domains to IDNA format.
    Illustrates pipeline syntax for several domains. The current implementation has
    no process block, so it does not reliably convert every pipeline item.
    Use ForEach-Object for batch conversion, as shown below.
.EXAMPLE
    @('öbb.at', 'münchen.de', 'zürich.ch') | ForEach-Object { ConvertTo-SC365IDNA -String $_ }
 
    Calls the function separately for each domain and returns all ASCII domain names.
#>

function ConvertTo-SC365IDNA {
    [CmdLetBinding()]
    param (
        [Parameter(
                    Mandatory = $true,
            ValueFromPipeline = $true
            )]
        [string]$String
    )
    $idn = [System.Globalization.IdnMapping]::new()
    return $idn.GetAscii($String)
}
<#
.SYNOPSIS
    Convert a IDNA Formatted Domain to DNS
.DESCRIPTION
    The CmdLet uses the System.Globalization.IdnMapping .NET Method to convert a IDNA Domain with special characters like ä, ü, or ß to the original DNS format.
.PARAMETER String
    Required ASCII-compatible IDNA domain name to convert to Unicode.
    Accepts a string from the pipeline. No Exchange Online connection is required.
.NOTES
    none
.LINK
    none
.EXAMPLE
    ConvertFrom-SC365IDNA -String 'xn--bb-eka.at'
     
    Converts an IDNA formatted domain back to Unicode.
    Returns: "öbb.at"
    Makes internationalized domains human-readable.
.EXAMPLE
    'xn--mnchen-3ya.de' | ConvertFrom-SC365IDNA
     
    Uses pipeline input to convert IDNA back to readable format.
    Returns: "münchen.de"
    Useful for displaying domains in reports.
.EXAMPLE
    Get-AcceptedDomain | Where-Object {$_.DomainName -like 'xn--*'} | ForEach-Object {ConvertFrom-SC365IDNA $_.DomainName}
     
    Finds all IDNA domains in the tenant and converts them to Unicode.
    Useful for auditing internationalized domains.
    Displays domains in their original, readable format.
#>

function ConvertFrom-SC365IDNA {
    [CmdLetBinding()]
    param (
        [Parameter(
                    Mandatory = $true,
            ValueFromPipeline = $true
            )]
        [string]$String
    )
    $idn = [System.Globalization.IdnMapping]::new()
    return $idn.GetUnicode($String)
}

<#
.SYNOPSIS
    Check ARC, inbound connector and content filter settings for parallel routing.
.DESCRIPTION
    Reads Exchange Online configuration and compares it with the supplied expectations.
    Returns a hashtable of retrieved values, writes warnings for mismatches and also
    emits a status string when no mismatches were collected. Does not change settings.
    Requires an Exchange Online connection with permission to read these objects.
.PARAMETER ExpectedArcTrustedSealers
    Expected ARC trusted sealer text. Default: SEPPMAIL.cloud. The current comparison
    uses this string inside a regular expression, rather than a literal equality test.
.PARAMETER InboundConnectorIdentity
    Identity passed to Get-InboundConnector.
    Default: [SEPPMAIL.cloud] Inbound-Parallel.
.PARAMETER ExpectedEFSkipIPs
    Boolean expected value compared with the connector's EFSkipIPs property.
    Default: $false. This parameter is not an IP address list.
.PARAMETER ExpectedEFSkipLastIP
    Expected Boolean EFSkipLastIP value. Default: $true.
    Supply an explicit Boolean value, for example -ExpectedEFSkipLastIP $false.
.PARAMETER ExpectedContentFilterPolicyIdentity
    Identity of the hosted content filter policy to inspect. Default: Default.
.PARAMETER ExpectedMarkAsSpamSpfRecordHardFail
    Expected policy setting for MarkAsSpamSpfRecordHardFail. Default: Off.
    This parameter only controls the comparison; it does not update the policy.
.EXAMPLE
    Get-SC365ParallelModeConfig
 
    Checks the standard parallel connector, ARC sealer and default content filter policy.
.EXAMPLE
    Get-SC365ParallelModeConfig -ExpectedArcTrustedSealers 'SEPPMAIL.cloud' -InboundConnectorIdentity '[SEPPMAIL.cloud] Inbound-Parallel' -ExpectedEFSkipIPs $false -ExpectedEFSkipLastIP $true -ExpectedContentFilterPolicyIdentity 'Default' -ExpectedMarkAsSpamSpfRecordHardFail 'Off'
 
    Supplies every expectation explicitly. Boolean parameters require values, not switches.
.EXAMPLE
    Get-SC365ParallelModeConfig -InboundConnectorIdentity 'Custom inbound connector' -ExpectedContentFilterPolicyIdentity 'Custom policy' -ExpectedEFSkipLastIP $false -Verbose
 
    Inspects custom objects with a different skip-last-IP expectation and diagnostic output.
.INPUTS
    None.
.OUTPUTS
    A hashtable and, when no mismatches were collected, a status string.
.NOTES
    A missing inbound connector writes a warning and leaves its properties absent.
    A status string is not proof that every object was found; review warnings as well.
#>

function Get-SC365ParallelModeConfig {
    [CmdletBinding()]
    param (
        [Parameter(
            Mandatory = $false
        )]
        [string]$ExpectedArcTrustedSealers = "SEPPMAIL.cloud",  # Expected ArcTrustedSealers value

        [Parameter(
            Mandatory = $false
        )]
        [string]$InboundConnectorIdentity = "[SEPPMAIL.cloud] Inbound-Parallel",  # Expected InboundConnector identity pattern

        [Parameter(
            Mandatory = $false
        )]
        [bool]$ExpectedEFSkipIPs = $false,  # Expected EFSkipIPs value

        [Parameter(
            Mandatory = $false
        )]
        [bool]$ExpectedEFSkipLastIP = $true,  # Expected EFSkipLastIP value

        [Parameter(
            Mandatory = $false
        )]
        [string]$ExpectedContentFilterPolicyIdentity = "Default",  # Expected Hosted Content Filter Policy Identity

        [Parameter(
            Mandatory = $false
        )]
        [string]$ExpectedMarkAsSpamSpfRecordHardFail = "Off"  # Expected value for MarkAsSpamSpfRecordHardFail
    )

    Begin {
        Write-Verbose "Initializing Exchange Online configuration check..."
        $results = @{}  # Hashtable to store retrieved values
        $warnings = @() # Array to store warnings
    }

    Process {
        try {
            # Get current ARC configuration
            $arcConfig = Get-ArcConfig
            $results["ArcTrustedSealers"] = $arcConfig.ArcTrustedSealers
            if ($results["ArcTrustedSealers"] -notmatch "\b$ExpectedArcTrustedSealers\b") {
                $warnings += "ArcTrustedSealers does not contain '$ExpectedArcTrustedSealers', Found: '$($arcConfig.ArcTrustedSealers)'. This will be Updated with the Setup of the SEPPMAIL.cloud connectors automatic cally"
            }

            # Get current InboundConnector configuration (use Get-InboundConnector to retrieve details)
            if ($inboundConnector = Get-InboundConnector -Identity $InboundConnectorIdentity -ErrorAction SilentlyContinue) {
                $results["EFSkipIPs"] = $inboundConnector.EFSkipIPs
                $results["EFSkipLastIP"] = $inboundConnector.EFSkipLastIP    
                if ($inboundConnector.EFSkipIPs -ne $ExpectedEFSkipIPs) {
                    $warnings += "EFSkipIPs is not as expected! Expected: '$ExpectedEFSkipIPs', Found: '$($inboundConnector.EFSkipIPs)'"
                }
                if ($inboundConnector.EFSkipLastIP -ne $ExpectedEFSkipLastIP) {
                    $warnings += "EFSkipLastIP is not as expected! Expected: '$ExpectedEFSkipLastIP', Found: '$($inboundConnector.EFSkipLastIP)'"
                }    
            } else {
                Write-Warning "No Parallel Inbound Connector with Identity `'$InboundConnectorIdentity`' found"
            }

            # Get current Hosted Content Filter Policy configuration
            $contentFilterPolicy = Get-HostedContentFilterPolicy -Identity $ExpectedContentFilterPolicyIdentity
            $results["MarkAsSpamSpfRecordHardFail"] = $contentFilterPolicy.MarkAsSpamSpfRecordHardFail
            if ($contentFilterPolicy.MarkAsSpamSpfRecordHardFail -ne $ExpectedMarkAsSpamSpfRecordHardFail) {
                $warnings += "MarkAsSpamSpfRecordHardFail is not as expected! Expected: '$ExpectedMarkAsSpamSpfRecordHardFail', Found: '$($contentFilterPolicy.MarkAsSpamSpfRecordHardFail)'"
            }
        }
        catch {
            Write-Error "An error occurred while retrieving Exchange Online configuration. Error: $_"
        }
    }

    End {
        # Output the retrieved values
        Write-Output $results

        # Display warnings if any configuration does not match
        if ($warnings.Count -gt 0) {
            Write-Warning "The setup is not as required! See details below and use Set-SC365ParallelModeConfig to prepare your tenant"
            foreach ($warning in $warnings) {
                Write-Warning $warning
            }
        } else {
            Write-Output "`nThe setup MATCHES the expected configuration."
        }
    }
}

<#
.SYNOPSIS
    Disable SPF hard-fail spam marking in a hosted content filter policy.
.DESCRIPTION
    Sets MarkAsSpamSpfRecordHardFail to Off for the selected Exchange Online policy.
    Does not change ARC or inbound connector settings. Requires an Exchange Online
    connection with permission to update the policy.
.PARAMETER ContentFilterPolicyIdentity
    Identity of the hosted content filter policy to update. Default: Default.
.PARAMETER WhatIf
    Show the policy update without executing it.
.PARAMETER Confirm
    Request confirmation before the policy update.
    -Confirm:$false suppresses the ShouldProcess confirmation.
.EXAMPLE
    Set-SC365ParallelModeConfig
 
    Sets MarkAsSpamSpfRecordHardFail to Off on the Default policy.
.EXAMPLE
    Set-SC365ParallelModeConfig -ContentFilterPolicyIdentity 'Custom policy' -WhatIf
 
    Previews the change to a named policy without modifying it.
.EXAMPLE
    Set-SC365ParallelModeConfig -ContentFilterPolicyIdentity 'Default' -Confirm -Verbose
 
    Requests confirmation and writes diagnostic output when updating the default policy.
.INPUTS
    None.
.OUTPUTS
    No dedicated result object. Review errors and re-read the policy to verify the update.
#>

function Set-SC365ParallelModeConfig {
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(
            Mandatory = $false
        )]
        [string]$ContentFilterPolicyIdentity = "Default" # Default value for Content Filter Policy Identity
    )

    Begin {
        Write-Verbose "Initializing Exchange Online configuration process..."
        $progressCounter = 0
        $progressSteps = 1
    }

    Process {
        try {
            # Task 1: Configure Hosted Content Filter Policy
            $progressCounter++
            Write-Progress -Activity "Configuring Content Filter Policy" -Status "Step $progressCounter of $progressSteps" -PercentComplete (($progressCounter / $progressSteps) * 100)
            
            if ($PSCmdlet.ShouldProcess("Hosted Content Filter Policy", "Setting MarkAsSpamSpfRecordHardFail to Off for Identity $ContentFilterPolicyIdentity")) {
                Set-HostedContentFilterPolicy -Identity $ContentFilterPolicyIdentity -MarkAsSpamSpfRecordHardFail Off
                Write-Verbose "Content Filter Policy updated successfully."
            }
        }
        catch {
            Write-Error "An error occurred while configuring Exchange Online. Error: $_"
        }
    }

    End {
        Write-Progress -Activity "Configuring Exchange Online" -Status "Completed" -Completed
    }
}
Register-ArgumentCompleter -CommandName Get-SC365TenantId -ParameterName MailDomain -ScriptBlock $paramDomSB

if (!(Get-Alias 'Confirm-SM365TenantDefaultDomain' -ErrorAction SilentlyContinue)) {
    New-Alias -Name Confirm-SM365TenantDefaultDomain -Value Confirm-SC365TenantDefaultDomain -Description "Alias for Confirm-SC365TenantDefaultDomain"
}

if (!(Get-Alias 'Show-SM365Tenant' -ErrorAction SilentlyContinue)) {
    New-Alias -Name Show-SM365Tenant -Value Show-SC365Tenant -Description "Alias for Show-SC365Tenant"
}

if (!(Get-Alias 'Get-SM365TenantID' -ErrorAction SilentlyContinue)) {
    New-Alias -Name Get-SM365TenantID -Value Get-SC365TenantID -Description "Alias for Get-SC365TenantID"
}


# Aliases for old Connectionstatus compatibility
if (!(Get-Alias 'Test-SM365ConnectionStatus' -ErrorAction SilentlyContinue)) {
    New-Alias -Name Test-SM365ConnectionStatus -Value Test-SC365ExoConnStatus -Description "Alias for Test-SC365ExoConnStatus"
}

if (!(Get-Alias 'Test-SC365ConnectionStatus' -ErrorAction SilentlyContinue)) {
    New-Alias -Name Test-SC365ConnectionStatus -Value Test-SC365ExoConnStatus -Description "Alias for Test-SC365ExoConnStatus"
}

# SIG # Begin signature block
# MIIQVQYJKoZIhvcNAQcCoIIQRjCCEEICAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCCVVINwlyP5denV
# AcsSSEKWUDpdwCS62w8xi/EWSlnojaCCDJEwggYaMIIEAqADAgECAhBiHW0MUgGe
# O5B5FSCJIRwKMA0GCSqGSIb3DQEBDAUAMFYxCzAJBgNVBAYTAkdCMRgwFgYDVQQK
# Ew9TZWN0aWdvIExpbWl0ZWQxLTArBgNVBAMTJFNlY3RpZ28gUHVibGljIENvZGUg
# U2lnbmluZyBSb290IFI0NjAeFw0yMTAzMjIwMDAwMDBaFw0zNjAzMjEyMzU5NTla
# MFQxCzAJBgNVBAYTAkdCMRgwFgYDVQQKEw9TZWN0aWdvIExpbWl0ZWQxKzApBgNV
# BAMTIlNlY3RpZ28gUHVibGljIENvZGUgU2lnbmluZyBDQSBSMzYwggGiMA0GCSqG
# SIb3DQEBAQUAA4IBjwAwggGKAoIBgQCbK51T+jU/jmAGQ2rAz/V/9shTUxjIztNs
# fvxYB5UXeWUzCxEeAEZGbEN4QMgCsJLZUKhWThj/yPqy0iSZhXkZ6Pg2A2NVDgFi
# gOMYzB2OKhdqfWGVoYW3haT29PSTahYkwmMv0b/83nbeECbiMXhSOtbam+/36F09
# fy1tsB8je/RV0m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