SecurityComplianceCenter.psm1

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

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName SecurityComplianceCenter.Import.DoDotSource -Fallback $false
if ($SecurityComplianceCenter_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 SecurityComplianceCenter.Import.IndividualFiles -Fallback $false
if ($SecurityComplianceCenter_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 'SecurityComplianceCenter' -Language 'en-US'

function Assert-SccConnection
{
<#
    .SYNOPSIS
        Asserts, that a proper connection to SCC has been established.
     
    .DESCRIPTION
        Asserts, that a proper connection to SCC has been established.
        Will terminate the calling function in fire and blood.
     
        Use this during the begin block of all functions interacting with SCC.
     
    .PARAMETER Cmdlet
        The $PSCmdlet variable of the calling function.
     
    .EXAMPLE
        PS C:\> Assert-SccConnection -Cmdlet $PSCmdlet
     
        Terminates the calling function, if no connection to SCC has been established.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Cmdlet
    )
    
    process
    {
        if (Test-Path function:\Get-Label) { return }
        
        $exception = [System.InvalidOperationException]::new('No connection to the Security and Compliance Center detected! Please run "Connect-SCC" to establish a connection!')
        $errorRecord = [System.Management.Automation.ErrorRecord]::new($exception, "SccNotConnected", 'ConnectionError', $null)
        $Cmdlet.ThrowTerminatingError($errorRecord)
    }
}

function Get-EnrichedLabel
{
<#
    .SYNOPSIS
        Returns all labels with extended Metadata.
     
    .DESCRIPTION
        Returns all labels with extended Metadata:
     
        - LS: Locale Settings reprocessed to be easily accessible.
        - FriendlyName: <Parent>\<Child> notation with DisplayName
        - FQLN: <Parent>\<Child> notation with Name
     
    .EXAMPLE
        PS C:\> Get-EnrichedLabel
     
        Returns all labels with extended Metadata.
#>

    [CmdletBinding()]
    Param (
    
    )
    
    begin
    {
        Assert-SccConnection -Cmdlet $PSCmdlet
    }
    process
    {
        $allLabels = Get-Label
        foreach ($label in $allLabels)
        {
            $displayNameHash = @{ }
            $tooltipHash = @{ }
            foreach ($setting in (@($label.LocaleSettings | ConvertFrom-Json) | Where-Object LocaleKey -EQ "displayName").Settings) { $displayNameHash[$setting.Key] = $setting.Value }
            foreach ($setting in (@($label.LocaleSettings | ConvertFrom-Json) | Where-Object LocaleKey -EQ "tooltip").Settings) { $tooltipHash[$setting.Key] = $setting.Value }
            
            $locale = @{
                DisplayName = $displayNameHash
                Tooltip        = $tooltipHash
            }
            Add-Member -InputObject $label -MemberType NoteProperty -Name LS -Value $locale
            
            if (-not $label.ParentID)
            {
                Add-Member -InputObject $label -MemberType NoteProperty -Name FriendlyName -Value $label.DisplayName
                Add-Member -InputObject $label -MemberType NoteProperty -Name FQLN -Value $label.Name
                $label
                continue
            }
            
            $parentLabel = $allLabels | Where-Object Guid -EQ $label.ParentID
            Add-Member -InputObject $label -MemberType NoteProperty -Name FriendlyName -Value ('{0}\{1}' -f $parentLabel.DisplayName, $label.DisplayName)
            Add-Member -InputObject $label -MemberType NoteProperty -Name FQLN -Value ('{0}\{1}' -f $parentLabel.Name, $label.Name)
            $label
        }
    }
}

function Connect-SCC
{
<#
    .SYNOPSIS
        Establishes a Modern Auth connection with the Security & Compliance Center.
     
    .DESCRIPTION
        Establishes a Modern Auth connection with the Security & Compliance Center.
     
        Behind the scenes, it uses the ExchangeOnlineManagement module's Connect-ExchangeOnline command.
     
    .PARAMETER AzureADAuthorizationEndpointUri
        The AzureADAuthorizationEndpointUri parameter specifies the Azure AD Authorization endpoint Uri that can issue OAuth2 access tokens.
     
    .PARAMETER ExchangeEnvironmentName
        The ExchangeEnvironmentName specifies the Exchange Online environment. Valid values are:
 
        - O365China
        - O365Default (this is the default value)
        - O365GermanyCloud
        - O365USGovDoD
        - O365USGovGCCHigh
     
    .PARAMETER PSSessionOption
        The PSSessionOption parameter specifies the PowerShell session options to use in your connection to SCC.
        Use the "New-PSSessionOption" cmdlet to generate them.
        Useful for example to configure a proxy.
     
    .PARAMETER BypassMailboxAnchoring
        The BypassMailboxAnchoring switch bypasses the use of the mailbox anchoring hint.
     
    .PARAMETER DelegatedOrganization
        The DelegatedOrganization parameter specifies the customer organization that you want to manage (for example, contosoelectronics.onmicrosoft.com).
        This parameter only works if the customer organization has agreed to your delegated management via the CSP program.
 
        After you successfully authenticate, the cmdlets in this session are mapped to the customer organization, and all operations in this session are done on the customer organization.
     
    .PARAMETER Prefix
        Add a module prefix to the imported commands.
     
    .PARAMETER UserPrincipalName
        The UserPrincipalName parameter specifies the account that you want to use to connect (for example, fred@contoso.onmicrosoft.com).
        Using this parameter allows you to skip the first screen in authentication prompt.
     
    .PARAMETER Credential
        The credentials to use when connecting to SCC.
        Needed for unattended automation.
        If this parameter is omitted, you will be prompted interactively.
     
    .EXAMPLE
        PS C:\> Connect-SCC
     
        Connects to the Securit & Compliance Center
#>

    [Alias('cscc')]
    [CmdletBinding()]
    param (
        [string]
        $AzureADAuthorizationEndpointUri,
        
        [Microsoft.Exchange.Management.RestApiClient.ExchangeEnvironment]
        $ExchangeEnvironmentName,
        
        [System.Management.Automation.Remoting.PSSessionOption]
        $PSSessionOption,
        
        [switch]
        $BypassMailboxAnchoring,
        
        [string]
        $DelegatedOrganization,
        
        [string]
        $Prefix,
        
        [string]
        $UserPrincipalName,
        
        [PSCredential]
        $Credential
    )
    
    begin
    {
        $settings = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WinRM\Client\' -ErrorAction Ignore
        if ($settings -and 0 -eq $settings.AllowBasic)
        {
            Write-PSFMessage -Level Warning -String 'Connect-SCC.Basic.Disabled'
            throw 'Logon impossible, client policies prevent connection.'
        }

        if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$null))
        {
            $PSBoundParameters['OutBuffer'] = 1
        }
        $parameters = @{
            ShowBanner    = $false
            ConnectionUri = Get-PSFConfigValue -FullName 'SecurityComplianceCenter.Connection.Uri'
        }
        $parameters += $PSBoundParameters | ConvertTo-PSFHashtable
        
        try
        {
            $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Connect-ExchangeOnline', [System.Management.Automation.CommandTypes]::Function)
            $scriptCmd = { & $wrappedCmd @parameters }
            $steppablePipeline = $scriptCmd.GetSteppablePipeline()
            $steppablePipeline.Begin($PSCmdlet)
        }
        catch
        {
            throw
        }
    }
    
    process
    {
        try
        {
            $steppablePipeline.Process($_)
        }
        catch
        {
            throw
        }
    }
    
    end
    {
        try
        {
            $steppablePipeline.End()
        }
        catch
        {
            throw
        }
    }
}

function Enable-SccAuthentication
{
    <#
    .SYNOPSIS
        Enables using modern authentication to connect to Security & Compliance Center.
     
    .DESCRIPTION
        Enables using modern authentication to connect to Security & Compliance Center.
        In some environments, policies exist that prevent the use of basic authentication for PowerShell CLIENTS.
 
        Connect-SCC does NOT use basic authentication, but WinRM cannot tell the difference between basic authentication and modern authentication.
        This command overrides the policy, but requires elevation ("Run as Administrator") to perform the override.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Enable-SccAuthentication
 
        Enables using modern authentication to connect to Security & Compliance Center.
    #>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [switch]
        $EnableException
    )

    process {
        $settings = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WinRM\Client\' -ErrorAction Ignore
        if (-not $settings) { return }
        if ($settings.PSObject.Properties.Name -notcontains 'AllowBasic') { return }
        if ($settings.AllowBasic -ne 0) { return }

        if (-not (Test-PSFPowerShell -Elevated))
        {
            Stop-PSFFunction -String 'Enable-SccAuthentication.NotElevated' -EnableException $EnableException -Category SecurityError
            return
        }

        Invoke-PSFProtectedCommand -ActionString 'Enable-SccAuthentication.Enabling' -Target $env:COMPUTERNAME -ScriptBlock {
            Set-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WinRM\Client\' -Name AllowBasic -Value 1 -ErrorAction Stop
        } -EnableException $EnableException -PSCmdlet $PSCmdlet
    }
}

function Get-SccLabelLocalization
{
<#
    .SYNOPSIS
        Reads localization data from existing labels.
     
    .DESCRIPTION
        Reads localization data from existing labels.
     
    .PARAMETER Name
        Filter by name or by ID.
     
    .PARAMETER DisplayName
        Filter by the displayname of the label
     
    .PARAMETER Language
        Constrain results by the language you are interested about.
     
    .EXAMPLE
        PS C:\> Get-SCCLabelLocalization
     
        Return all localization data for all labels
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]
        $Name = '*',
        
        [string]
        $DisplayName = '*',
        
        [string[]]
        $Language
    )
    
    begin
    {
        Assert-SccConnection -Cmdlet $PSCmdlet
        
        $allLabels = Get-EnrichedLabel
    }
    process
    {
        foreach ($label in $allLabels)
        {
            $found = $false
            foreach ($labelName in $Name) {
                if ($label.Name -like $labelName) { $found = $true }
            }
            if (-not $found) { continue }

            if ($label.DisplayName -notlike $DisplayName) { continue }

            foreach ($languageKey in $label.LS.DisplayName.Keys) {
                if ($Language -and $languageKey -notin $Language) { continue }

                [pscustomobject]@{
                    PSTypeName   = 'SecurityComplianceCenter.Label.Locale'
                    FriendlyName = $label.friendlyName
                    LabelID         = $label.Guid
                    FQLN          = $label.FQLN
                    LabelName    = $label.Name
                    Type         = 'DisplayName'
                    Language     = $languageKey
                    Text         = $label.LS.DisplayName[$languageKey]
                    Label         = $label
                }
            }
            
            foreach ($languageKey in $label.LS.Tooltip.Keys) {
                if ($Language -and $languageKey -notin $Language) { continue }

                [pscustomobject]@{
                    PSTypeName   = 'SecurityComplianceCenter.Label.Locale'
                    FriendlyName = $label.friendlyName
                    LabelID         = $label.Guid
                    FQLN          = $label.FQLN
                    LabelName    = $label.Name
                    Type         = 'Tooltip'
                    Language     = $languageKey
                    Text         = $label.LS.Tooltip[$languageKey]
                    Label         = $label
                }
            }
        }
    }
}

function Import-SccLabelLocalizationXml
{
<#
    .SYNOPSIS
        Imports label data from an export-xml of classic AIP label localization.
     
    .DESCRIPTION
        Imports label data from an export-xml of classic AIP label localization.
     
        This only parses the XML files and generates PowerShell objects containing the relevant data.
        To apply the localization data thus generated, use Set-SccLabelLocalization.
     
    .PARAMETER Path
        Path(s) to the XML file(s) to import / parse.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> Import-SccLabelLocalizationXml -Path .\de-DE.xml
     
        Imports the localization data stored in de-DE.xml
     
    .EXAMPLE
        PS C:\> Import-SccLabelLocalizationXml -Path .\*.xml | Set-SccLabelLocalization
     
        Imports all localization XML in the current folder and applies the localization data to the online labels in SCC.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('FullName')]
        [string[]]
        $Path,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $defaultProcessed = @{ }
    }
    process
    {
        foreach ($pathItem in $Path)
        {
            try { $resolvedPaths = Resolve-PSFPath -Path $pathItem -Provider FileSystem }
            catch { Stop-PSFFunction -String 'Import-SccLabelLocalizationXml.InvalidPath.Error' -StringValues $pathItem -Target $pathItem -EnableException $EnableException -Continue -ErrorRecord $_ }
            
            foreach ($fileItem in $resolvedPaths)
            {
                try { [xml]$xmlData = Get-Content -Path $fileItem -ErrorAction Stop -Encoding utf8 }
                catch { Stop-PSFFunction -String 'Import-SccLabelLocalizationXml.Content.Error' -StringValues $fileItem -Target $fileItem -EnableException $EnableException -Continue -ErrorRecord $_ }
                $language = $xmlData.Language.Id
                if (-not $language) { Stop-PSFFunction -String 'Import-SccLabelLocalizationXml.Content.BadDocument' -StringValues $fileItem -Target $fileItem -EnableException $EnableException -Continue -Category InvalidData }
                
                Write-PSFMessage -String 'Import-SccLabelLocalizationXml.Processing' -StringValues $fileItem -Target $fileItem
                
                #region Process Entries
                foreach ($entry in $xmlData.Language.LocItem)
                {
                    if ($entry.ID -notmatch '^labelGroups/Sensitivity/labels/.+/(DisplayName|Description)$') { continue }
                    
                    $type = 'Tooltip'
                    if ($entry.ID -Match 'DisplayName$') { $type = 'DisplayName' }
                    
                    if ($type -eq 'DisplayName' -and $entry.LocalizedText.Length -gt 64)
                    {
                        Write-PSFMessage -Level Warning -String 'Import-SccLabelLocalizationXml.DisplayName.TooLong' -StringValues ($entry.ID -split "/")[-2], $language, $entry.defaultText, $entry.LocalizedText
                    }
                    if ($type -eq 'DisplayName' -and $entry.LocalizedText -match $script:PatternDisplayNameValidation)
                    {
                        $characters = $entry.LocalizedText | Select-String "($script:PatternDisplayNameValidation)" -AllMatches | ForEach-Object {
                            @($_.Matches).ForEach{ $_.Groups[1].Value }
                        } | Select-Object -Unique | ForEach-Object { '"{0} (C: {1})"' -f $_, ([int][char]$_) }
                        Write-PSFMessage -Level Warning -String 'Import-SccLabelLocalizationXml.DisplayName.BadCharacters' -StringValues ($entry.ID -split "/")[-2], $language, ($characters -join ","), $entry.defaultText, $entry.LocalizedText
                    }
                    if ($type -eq 'Tooltip' -and $entry.LocalizedText.Length -gt 1000)
                    {
                        Write-PSFMessage -Level Warning -String 'Import-SccLabelLocalizationXml.Tooltip.TooLong' -StringValues ($entry.ID -split "/")[-2], $language, $entry.defaultText, $entry.LocalizedText
                    }
                    if ($type -eq 'Tooltip' -and $entry.LocalizedText -match $script:PatternTooltipValidation)
                    {
                        $characters = $entry.LocalizedText | Select-String "($script:PatternTooltipValidation)" -AllMatches | ForEach-Object {
                            @($_.Matches).ForEach{ $_.Groups[1].Value }
                        } | Select-Object -Unique | ForEach-Object { '"{0} (C: {1})"' -f $_, ([int][char]$_) }
                        Write-PSFMessage -Level Warning -String 'Import-SccLabelLocalizationXml.Tooltip.BadCharacters' -StringValues ($entry.ID -split "/")[-2], $language, ($characters -join ","), $entry.defaultText, $entry.LocalizedText
                    }
                    
                    [PSCustomObject]@{
                        Name = ($entry.ID -split "/")[-2]
                        Identity = $entry.ID.Replace("labelGroups/Sensitivity/labels/", "").Replace("subLabels/", "").Replace("/", "\") -replace '\\(DisplayName|Description)$'
                        Type = $type
                        Language = $language
                        Text = $entry.LocalizedText
                    }
                    
                    if ($defaultProcessed[$entry.ID]) { continue }
                    
                    [PSCustomObject]@{
                        Name = ($entry.ID -split "/")[-2]
                        Identity = $entry.ID.Replace("labelGroups/Sensitivity/labels/", "").Replace("subLabels/", "").Replace("/", "\") -replace '\\(DisplayName|Description)$'
                        Type = $type
                        Language = 'default'
                        Text = $entry.defaultText
                    }
                    
                    $defaultProcessed[$entry.ID] = $true
                }
                #endregion Process Entries
            }
        }
    }
}

function Set-SccLabelLocalization
{
<#
    .SYNOPSIS
        Updates localization of Labels.
     
    .DESCRIPTION
        Updates localization of Labels.
     
    .PARAMETER Name
        The (system) name of the label.
     
    .PARAMETER FriendlyName
        The friendly name of the label.
        This is the DisplayName in case of a top level Label.
        In case of a child label, it is <ParentDisplayName>\<DisplayName>
     
    .PARAMETER Identity
        The Identity - or FQLN - of a Label is similar to the FriendlyName, only using the Name properties instead.
        Thus it is the Name in case of a top level Label.
        In case of a child label, it is <ParentName>\<Name>
     
    .PARAMETER Language
        The language for which to update text.
     
    .PARAMETER Type
        The type of text to write:
        DisplayName or Tooltip.
     
    .PARAMETER Text
        The text to write.
     
    .PARAMETER Default
        By default, existing localization entries will be overwritten.
        With this parameter, already existing localization entries will be honored and only new strings added.
     
    .PARAMETER DelayWrite
        Defers updating labels until the end, collecting all changes and applies them in bulk.
        By default, each label text is written as it comes in.
        Caching all writes and executing them in bulk is a performance update, but risks changes to be lost in case of terminating errors.
     
    .PARAMETER NameMapping
        A hashtable mapping input Names to new names.
        Useful when importing into a tenant other than the source tenant where not all names match perfectly.
     
    .PARAMETER FriendlyNameMapping
        A hashtable mapping input FriendlyNames to new FriendlyNames.
        Useful when importing into a tenant other than the source tenant where not all names match perfectly.
     
    .PARAMETER IdentityMapping
        A hashtable mapping input Identities to new Identities.
        Useful when importing into a tenant other than the source tenant where not all names match perfectly.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Set-SccLabelLocalization -Name Confidential -Language 'de-DE' -Type DisplayName -Text 'Vertraulich'
     
        Adds a German localization to the "Confidential" label
     
    .EXAMPLE
        PS C:\> Import-Csv .\localizations.csv | Set-SccLabelLocalization
     
        Imports all localization data from the localizations.csv document.
        The document must contain some columns:
        - Language
        - Type
        - Text
        - At least one of: Name, FriendlyName, Identity, FQLN
     
    .EXAMPLE
        PS C:\> Import-SccLabelLocalizationXml -Path .\*.xml | Set-SccLabelLocalization
     
        Imports all localization XML in the current folder and applies the localization data to the online labels in SCC.
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Name,
        
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $FriendlyName,
        
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias('FQLN')]
        [string]
        $Identity,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Language,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateSet('DisplayName', 'Tooltip')]
        [string]
        $Type,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Text,
        
        [switch]
        $Default,
        
        [switch]
        $DelayWrite,
        
        [Hashtable]
        $NameMapping,
        
        [hashtable]
        $FriendlyNameMapping,
        
        [hashtable]
        $IdentityMapping,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        Assert-SccConnection -Cmdlet $PSCmdlet
        
        #region Utility Functions
        function Write-Label
        {
            [CmdletBinding()]
            param (
                $LabelObject
            )

            # Due to a change in service processing, we must only upload if all languages in both sets are filled out
            if ($LabelObject.LS.DisplayName.Keys.Count -and $LabelObject.LS.Tooltip.Keys.Count)
            {
                foreach ($key in $LabelObject.LS.DisplayName.Keys) {
                    if ($key -in $LabelObject.LS.Tooltip.Keys) { continue }
                    $LabelObject.LS.Tooltip[$key] = $LabelObject.LS.Tooltip['default']
                }
                foreach ($key in $LabelObject.LS.Tooltip.Keys) {
                    if ($key -in $LabelObject.LS.DisplayName.Keys) { continue }
                    $LabelObject.LS.DisplayName[$key] = $LabelObject.LS.DisplayName['default']
                }
            }
            
            $dnHash = @{
                localeKey = "displayName"
                Settings  = @()
            }
            foreach ($key in $LabelObject.LS.DisplayName.Keys)
            {
                $dnHash.Settings += [pscustomobject]@{
                    Key   = $key
                    Value = $LabelObject.LS.DisplayName[$key]
                }
            }
            
            $ttHash = @{
                localeKey = "tooltip"
                Settings  = @()
            }
            foreach ($key in $LabelObject.LS.Tooltip.Keys)
            {
                $ttHash.Settings += [pscustomobject]@{
                    Key   = $key
                    Value = $LabelObject.LS.Tooltip[$key]
                }
            }
            
            try
            {
                if ($dnHash.Settings.Count -and $ttHash.Settings.Count) {
                    Set-Label -Identity $LabelObject.Guid -LocaleSettings ($dnHash | ConvertTo-Json), ($ttHash | ConvertTo-Json) -ErrorAction Stop -WarningAction SilentlyContinue
                }
                elseif ($dnHash.Settings.Count -gt 0) { Set-Label -Identity $LabelObject.Guid -LocaleSettings ($dnHash | ConvertTo-Json) -ErrorAction Stop -WarningAction SilentlyContinue }
                elseif ($ttHash.Settings.Count -gt 0) { Set-Label -Identity $LabelObject.Guid -LocaleSettings ($ttHash | ConvertTo-Json) -ErrorAction Stop -WarningAction SilentlyContinue }
            }
            catch { throw }
        }
        #endregion Utility Functions
        
        $allLabels = Get-EnrichedLabel
        $modifiedLabels = @{ }
    }
    process
    {
        :main foreach ($dummyVar in 1)
        {
            $targetItem = [PSCustomObject]($PSBoundParameters | ConvertTo-PSFHashtable)
            
            #region Find Target Label
            if (Test-PSFParameterBinding -ParameterName Name, FriendlyName, Identity -Not)
            {
                Stop-PSFFunction -String 'Set-SccLabelLocalization.Label.NoIdentity.Error' -EnableException $EnableException -Category InvalidArgument -Continue -Cmdlet $PSCmdlet -Target $targetItem
            }
            
            $targetLabel = $null
            if ($Name)
            {
                $resolvedName = $Name
                if ($NameMapping -and $NameMapping[$Name]) { $resolvedName = $NameMapping[$Name] }
                $targetLabel = $allLabels | Where-Object Name -EQ $resolvedName
            }
            if ($FriendlyName -and -not $targetLabel)
            {
                $resolvedFriendlyName = $FriendlyName
                if ($FriendlyNameMapping -and $FriendlyNameMapping[$FriendlyName]) { $resolvedFriendlyName = $FriendlyNameMapping[$FriendlyName] }
                $targetLabel = $allLabels | Where-Object FriendlyName -EQ $resolvedFriendlyName
            }
            if ($Identity -and -not $targetLabel)
            {
                $resolvedIdentity = $Identity
                if ($IdentityMapping -and $IdentityMapping[$Identity]) { $resolvedIdentity = $IdentityMapping[$Identity] }
                $targetLabel = $allLabels | Where-Object FQLN -EQ $resolvedIdentity
            }
            
            if (-not $targetLabel)
            {
                Stop-PSFFunction -String 'Set-SccLabelLocalization.Label.NotFound.Error' -StringValues $Name, $FriendlyName, $Identity -EnableException $EnableException -Category ObjectNotFound -Continue -Cmdlet $PSCmdlet -Target $targetItem
            }
            #endregion Find Target Label
            
            #region Validate Text
            switch ($Type)
            {
                'DisplayName' {
                    if ($Text.Length -gt 64)
                    {
                        Stop-PSFFunction -String 'Set-SccLabelLocalization.Text.DisplayName.TooLong' -StringValues $targetLabel.FriendlyName, $Language, $Text -EnableException $EnableException -Category InvalidArgument -Continue -ContinueLabel main -Cmdlet $PSCmdlet -Target $targetItem
                    }
                    if ($Text -match $script:PatternDisplayNameValidation)
                    {
                        $characters = $Text | Select-String "($script:PatternDisplayNameValidation)" -AllMatches | ForEach-Object {
                            @($_.Matches).ForEach{ $_.Groups[1].Value }
                        } | Select-Object -Unique | ForEach-Object { '"{0} (C: {1})"' -f $_, ([int][char]$_) }
                        Stop-PSFFunction -String 'Set-SccLabelLocalization.Text.DisplayName.BadCharacters' -StringValues $targetLabel.FriendlyName, $Language, ($characters -join ","), $Text -EnableException $EnableException -Category InvalidArgument -Continue -ContinueLabel main -Cmdlet $PSCmdlet -Target $targetItem
                    }
                }
                'Tooltip' {
                    if ($Text.Length -gt 1000)
                    {
                        Stop-PSFFunction -String 'Set-SccLabelLocalization.Text.Tooltip.TooLong' -StringValues $targetLabel.FriendlyName, $Language, $Text -EnableException $EnableException -Category InvalidArgument -Continue -ContinueLabel main -Cmdlet $PSCmdlet -Target $targetItem
                    }
                    if ($Text -match $script:PatternTooltipValidation)
                    {
                        $characters = $Text | Select-String "($script:PatternTooltipValidation)" -AllMatches | ForEach-Object {
                            @($_.Matches).ForEach{ $_.Groups[1].Value }
                        } | Select-Object -Unique | ForEach-Object { '"{0} (C: {1})"' -f $_, ([int][char]$_) }
                        Stop-PSFFunction -String 'Set-SccLabelLocalization.Text.Tooltip.BadCharacters' -StringValues $targetLabel.FriendlyName, $Language, ($characters -join ","), $Text -EnableException $EnableException -Category InvalidArgument -Continue -ContinueLabel main -Cmdlet $PSCmdlet -Target $targetItem
                    }
                }
            }
            
            Write-PSFMessage -String 'Set-SccLabelLocalization.Processing' -StringValues $targetLabel.FriendlyName -Target $targetItem
            #endregion Validate Text
            
            #region Process Updates
            if ($Default -and $targetLabel.LS."$Type".$Language)
            {
                Write-PSFMessage -String 'Set-SccLabelLocalization.Skipping.AlreadySet' -StringValues $targetLabel.FriendlyName, $Type, $Language -Target $targetItem
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Set-SccLabelLocalization.Updating' -ActionStringValues $targetLabel.FriendlyName, $Type, $Language -ScriptBlock {
                $backupHash = $targetLabel.LS["$Type"].Clone()
                $targetLabel.LS["$Type"][$Language] = $Text
                if ($DelayWrite) { $modifiedLabels[$targetLabel.Name] = $targetLabel }
                else
                {
                    try { Write-Label -LabelObject $targetLabel -ErrorAction Stop }
                    catch
                    {
                        # Rollback the change that failed
                        $targetLabel.LS["$Type"] = $backupHash
                        throw
                    }
                }
            } -EnableException $EnableException -PSCmdlet $PSCmdlet -Continue -Target $targetItem
            #endregion Process Updates
        }
    }
    end
    {
        #region Execute delayed write
        if ($DelayWrite)
        {
            foreach ($labelObject in $modifiedLabels.Values)
            {
                try
                {
                    Write-PSFMessage -String 'Set-SccLabelLocalization.Updating.Bulk' -StringValues $labelObject.FriendlyName -Target $labelObject
                    Write-Label -LabelObject $labelObject -ErrorAction Stop
                }
                catch { Stop-PSFFunction -String 'Set-SccLabelLocalization.Updating.Bulk.Failed' -StringValues $labelObject.FriendlyName -Target $labelObject -ErrorRecord $_ -EnableException $EnableException -Continue }
            }
        }
        #endregion Execute delayed write
    }
}

$script:PatternDisplayNameValidation = '[\\<>%&:;?/+|]'
$script:PatternTooltipValidation = '[\x00\x08\x0B\x0C\x0E-\x1F]'

<#
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 'SecurityComplianceCenter' -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 'SecurityComplianceCenter' -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 'SecurityComplianceCenter' -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."
Set-PSFConfig -Module 'SecurityComplianceCenter' -Name 'Connection.Uri' -Value 'https://ps.compliance.protection.outlook.com/powershell-liveid/' -Initialize -Validation string -Description 'The Url used to connect to the EDiscovery service in the 0365 Compliance Center'

<#
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 'SecurityComplianceCenter.ScriptBlockName' -Scriptblock {
     
}
#>


Register-PSFTeppScriptblock -Name 'SecurityComplianceCenter.Int.CultureKeys' -ScriptBlock {
    [System.Globalization.CultureInfo]::GetCultures([System.Globalization.CultureTypes]::AllCultures).Name
}
Register-PSFTeppArgumentCompleter -Command Set-SccLabelLocalization -Parameter Language -Name 'SecurityComplianceCenter.Int.CultureKeys'

Register-PSFTeppScriptblock -Name 'SecurityComplianceCenter.LabelName' -ScriptBlock {
    (Get-Label).Name
}
Register-PSFTeppArgumentCompleter -Command Get-Label -Parameter Identity -Name 'SecurityComplianceCenter.LabelName'
Register-PSFTeppArgumentCompleter -Command Set-Label -Parameter Identity -Name 'SecurityComplianceCenter.LabelName'
Register-PSFTeppArgumentCompleter -Command Remove-Label -Parameter Identity -Name 'SecurityComplianceCenter.LabelName'
Register-PSFTeppArgumentCompleter -Command Get-SccLabelLocalization -Parameter Name -Name 'SecurityComplianceCenter.LabelName'
Register-PSFTeppArgumentCompleter -Command Set-SccLabelLocalization -Parameter Name -Name 'SecurityComplianceCenter.LabelName'



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


New-PSFLicense -Product 'SecurityComplianceCenter' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2020-04-14") -Text @"
Copyright (c) 2020 Friedrich Weinmann
 
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