AzStackHciExternalActiveDirectory/AzStackHci.ExternalActiveDirectory.Tests.psm1

Import-LocalizedData -BindingVariable lcAdTxt -FileName AzStackHci.ExternalActiveDirectory.Strings.psd1

class ExternalADTest
{
    [string]$TestName
    [scriptblock]$ExecutionBlock
}

$ExternalAdTestInitializors = @(
)

$ExternalAdTests = @(
    (New-Object -Type ExternalADTest -Property @{
        TestName = "RequiredOrgUnitsExist"
        ExecutionBlock = {
            Param ([hashtable]$testContext)

            $serverParams = @{}
            if ($testContext["AdServer"])
            {
                $serverParams += @{Server = $testContext["AdServer"]}
            }
            if ($testContext["AdCredentials"])
            {
                $serverParams += @{Credential = $testContext["AdCredentials"]}
            }

            $requiredOU = $testContext["ADOUPath"]

            Log-Info -Message (" Checking for the existance of OU: {0}" -f $requiredOU) -Type Info -Function "RequiredOrgUnitsExist"

            try {
                $resultingOU = Get-ADOrganizationalUnit -Identity $requiredOU -ErrorAction SilentlyContinue @serverParams
            }
            catch {
            }

            return @{
                Resource    = $_
                Status      = if ($resultingOU) { 'SUCCESS' } else { 'FAILURE' }
                TimeStamp   = [datetime]::UtcNow
                Source      = $ENV:COMPUTERNAME
                Detail = ($testContext["LcAdTxt"].MissingOURemediation -f $_)
           }
        }
    }),
    (New-Object -Type ExternalADTest -Property @{
        TestName = "LogPhysicalMachineObjectsIfExist"
        ExecutionBlock = {
            Param ([hashtable]$testContext)

            $serverParams = @{}
            if ($testContext["AdServer"])
            {
                $serverParams += @{Server = $testContext["AdServer"]}
            }
            if ($testContext["AdCredentials"])
            {
                $serverParams += @{Credential = $testContext["AdCredentials"]}
            }

            $adOUPath = $testContext["ADOUPath"]
            $domainFQDN = $testContext["DomainFQDN"]
            $seedNode = $ENV:COMPUTERNAME

            $detailedErrors = @()
            Log-Info -Message (" Validating seednode : {0} is part of a domain or not " -f $seedNode) -Type Info -Function "PhysicalMachineObjectsExist"
            $domainStatus = (gwmi win32_computersystem).partofdomain
            if ($domainStatus)
            {

                Log-Info -Message (" Seed node {0} joined to the domain. Disconnect the seed node from the domain and proceed with the deployment" -f $seedNode) -Type Error -Function "PhysicalMachineObjectsExist"
                $results += @{
                    Resource    = "SeedNodePartofDomain"
                    Status      = "FAILURE"
                    TimeStamp   = [datetime]::UtcNow
                    Source      = $ENV:COMPUTERNAME
                    Detail = ("Seed joined to the domain. Disconnect the seed node from the domain and proceed with the deployment")
                }
            }
            else
            {
                $physicalHostsSetting = @($testContext["PhysicalMachineNames"] | Where-Object { -not [string]::IsNullOrEmpty($_) })
                Log-Info -Message (" Validating settings for physical hosts: {0}" -f ($physicalHostsSetting -join ", ")) -Type Info -Function "PhysicalMachineObjectsExist"

                try {
                    $allComputerObjects = Get-ADComputer -SearchBase $adOUPath -Filter "*" @serverParams
                }
                catch {
                    Log-Info -Message (" Failed to find any computer objects in ActiveDirectory. Inner exception: {0}" -f $_) -Type Error -Function "PhysicalMachineObjectsExist"
                    $allComputerObjects = @()
                }

                $foundPhysicalHosts = @($allComputerObjects | Where-Object {$_.Name -in $physicalHostsSetting})
                $missingPhysicalHostEntries = @($physicalHostsSetting | Where-Object {$_ -notin $allComputerObjects.Name})

                Log-Info -Message (" Found {0} entries in AD : {1}" -f $foundPhysicalHosts.Count,($foundPhysicalHosts.Name -join ", ")) -Type Info -Function "PhysicalMachineObjectsExist"
                $timeoutSeconds = 60

                if ($missingPhysicalHostEntries.Count -gt 0)
                {
                    $jobs = foreach ($physicalHost in $missingPhysicalHostEntries)
                            {
                                start-job -ScriptBlock {
                                    param($computerName, $serverparams)
                                    Import-Module ActiveDirectory
                                    Get-ADComputer -Filter "Name -eq '$computerName' " @serverparams
                                } -ArgumentList $physicalHost, $serverParams
                            }
                    # Wait for all jobs to complete or timeout
                    Wait-Job -Job $jobs -Timeout $timeoutSeconds | Out-Null

                    # Check the status of each job and display the results
                    foreach ($job in $jobs) {
                        $status = $job.State
                        if ($status -eq 'Completed') {
                            $result = Receive-Job -Job $job -ErrorAction SilentlyContinue
                            if ($result) {
                                Log-Info -Message (" Found physical host {0} in AD and it's DistinguishedName :: {1}. Please remove the computer object." -f $($result.Name), $($result.DistinguishedName)) -Type Error -Function "PhysicalMachineObjectsExist"
                                $detailedErrors += " Found physical host {0} in AD and it's DistinguishedName :: {1}. Please remove the computer object." -f $($result.Name), $($result.DistinguishedName)
                            } 
                        } elseif ($status -eq 'Running') {
                            Stop-Job -Job $job -ErrorAction Ignore | Out-Null
                        }
                        # Clean up the job
                        Remove-Job -Job $job -ErrorAction Ignore | Out-Null
                    } 
                }

                if ($detailedErrors.Count -gt 0) {
                    $detail = $detailedErrors -join "; "
                    $statusValue = 'FAILURE'
                }
                else
                {
                    $statusValue = 'SUCCESS'
                    $detail = ""
                }

                $results += @{
                    Resource    = "PhysicalHostAdComputerEntries"
                    Status      = $statusValue
                    TimeStamp   = [datetime]::UtcNow
                    Source      = $ENV:COMPUTERNAME
                    Detail = $detail
                }
            }
            return $results
        }
    }),
    (New-Object -Type ExternalADTest -Property @{
        TestName = "LogClusterObjectIfExist"
        ExecutionBlock = {
            Param ([hashtable]$testContext)

            $serverParams = @{}
            if ($testContext["AdServer"])
            {
                $serverParams += @{Server = $testContext["AdServer"]}
            }
            if ($testContext["AdCredentials"])
            {
                $serverParams += @{Credential = $testContext["AdCredentials"]}
            }

            $adOUPath = $testContext["ADOUPath"]
            $domainFQDN = $testContext["DomainFQDN"]
            $seedNode = $ENV:COMPUTERNAME
            $clusterName = $testContext["ClusterName"]

                $detail = ""
                Log-Info -Message (" Validating cluster object {0} is available in {1} " -f $clusterName, $adOUPath) -Type Info -Function "LogClusterObjectIfExist"
                $statusValue = 'SUCCESS'
                try {
                    $clusterObject = Get-ADComputer -SearchBase $adOUPath -Filter "Name -eq '$clusterName' " @serverParams
                }
                catch {
                    Log-Info -Message (" Failed to find cluster objects in ActiveDirectory. Inner exception: {0}" -f $_) -Type Error -Function "LogClusterObjectIfExist"
                    $detail = " Failed to find cluster objects in ActiveDirectory. Inner exception: {0}" -f $_
                    $statusValue = 'FAILURE'
                }

                if ($clusterObject)
                {
                    $detail = ("Cluster object {0} available in {1}" -f $clusterName, $adOUPath)
                }
                else
                {
                    $timeoutSeconds = 60
                    Log-Info -Message (" Cluster object {0} not found in {1} " -f $clusterName, $adOUPath) -Type Info -Function "LogClusterObjectIfExist"

                    $job = start-job -ScriptBlock {
                                    param($clusterName, $serverparams)
                                    Import-Module ActiveDirectory
                                    Get-ADComputer -Filter "Name -eq '$clusterName' " @serverparams
                                } -ArgumentList $clusterName, $serverParams

                    Wait-Job -Job $job -Timeout $timeoutSeconds | Out-Null

                    $status = $job.State
                    if ($status -eq 'Completed') {
                        $result = Receive-Job -Job $job -ErrorAction SilentlyContinue
                        if ($result) {
                            Log-Info -Message (" Found cluster {0} in AD and it's DistinguishedName :: {1}. Please remove the computer object." -f $($result.Name), $($result.DistinguishedName)) -Type Error -Function "LogClusterObjectIfExist"
                            $detail = " Found cluster {0} in AD and it's DistinguishedName :: {1}. Please remove the computer object." -f $($result.Name), $($result.DistinguishedName)
                            $statusValue = 'FAILURE'
                        }
                        else
                        {
                            $detail = (" cluster object {0} not found in active directory." -f $clusterName)
                        }
                    } 
                    elseif ($status -eq 'Running') {
                        $detail = " Unable to get the cluster object within the timeout and assuming that cluster object is not available on AD"
                        Stop-Job -Job $job -ErrorAction Ignore | Out-Null
                    }
                    else
                    {
                        $detail = " Unable to get the cluster object and assuming that cluster object is not available on AD"
                    }
                    Remove-Job -Job $job -ErrorAction Ignore | Out-Null
                }

                $results += @{
                    Resource    = "ClusterObject"
                    Status      = $statusValue
                    TimeStamp   = [datetime]::UtcNow
                    Source      = $ENV:COMPUTERNAME
                    Detail = $detail
                }
            return $results
        }
    }),
    (New-Object -Type ExternalADTest -Property @{
        TestName = "GpoInheritanceIsBlocked"
        ExecutionBlock = {
            Param ([hashtable]$testContext)

            $serverParams = @{}
            if ($testContext["AdServer"])
            {
                $serverParams += @{Server = $testContext["AdServer"]}
            }
            if ($testContext["AdCredentials"])
            {
                $serverParams += @{Credential = $testContext["AdCredentials"]}
            }

            $ouPath = $testContext["ADOUPath"]

            Log-Info -Message (" Checking whether gpInheritance is blocked for the OU : {0} " -f $ouPath) -Type Info -Function "GpoInheritanceIsBlocked"
            $statusValue = 'FAILURE'

            try {
                $ou = Get-ADOrganizationalUnit -Identity $ouPath -Properties gpOptions @serverParams
                if ($ou.gpOptions -ne $null) 
                {
                    if ($ou.gpOptions -eq 1)
                    {
                        $statusValue = 'SUCCESS'
                        Log-Info -Message (" gpInheritance is blocked for the OU : {0} and the gpOptions value : {1} " -f $ouPath, $($ou.gpOptions)) -Type Info -Function "GpoInheritanceIsBlocked"
                    }
                    else
                    {
                        Log-Info -Message (" gpInheritance is not blocked for the OU : {0} and the gpOptions value : {1} " -f $ouPath, $($ou.gpOptions)) -Type Info -Function "GpoInheritanceIsBlocked"
                    }
                }
                else
                {
                    Log-Info -Message (" gpInheritance is not blocked for the OU : {0} and unable to get the gpOptions property." -f $ouPath) -Type Info -Function "GpoInheritanceIsBlocked"
                }
            }
            catch {
                Log-Info -Message (" Failed to get the gpInheritance for the OU : {0} and Inner exception: {1}" -f $ouPath, $_) -Type Info -Function "GpoInheritanceIsBlocked"
            }


            return @{
                Resource    = "OuGpoInheritance"
                Status      = $statusValue
                TimeStamp   = [datetime]::UtcNow
                Source      = $ENV:COMPUTERNAME
                Detail = $testContext["LcAdTxt"].OuInheritanceBlockedMissingRemediation
            }
        }
    }),
    (New-Object -Type ExternalADTest -Property @{
        TestName = "ExecutingAsDeploymentUser"
        ExecutionBlock = {

            Param ([hashtable]$testContext)

            # Values retrieved from the test context
            $adOuPath = $testContext["ADOUPath"]
            [pscredential]$credentials = $testContext["AdCredentials"]
            $credentialName = $null
            $statusValue = 'FAILURE'
            $userHasOuPermissions = $false
            if ($credentials)
            {
                # Get the user SID so we can find it in the ACL
                $credentialParts = $credentials.UserName.Split("\\")
                $credentialName = $credentialParts[$credentialParts.Length-1]
            }
            else
            {
                $credentialName = $env:USERNAME
            }

            $serverParams = @{}
            if ($TestContext["AdServer"])
            {
                $serverParams += @{Server = $TestContext["AdServer"]}
            }
            if ($TestContext["AdCredentials"])
            {
                $serverParams += @{Credential = $TestContext["AdCredentials"]}
            }
            $deploymentUserIdentifier = Get-ADUser -Filter {Name -eq $credentialName} -SearchBase $adOuPath @serverParams

            $failureReasons = @()
            if ($deploymentUserIdentifier)
            {

                Log-Info -Message (" Found user '{0}' in Active Directory" -f $credentialName) -Type Info -Function "ExecutingAsDeploymentUser"

                # Test whether the AdCredentials user has all access rights to the OU
                try {

                    $adDriveName = "AD"
                    $tempDriveName = "hciad"
                    $adDriveObject = $null

                    try
                    {
                        $adProvider = Get-PSProvider -PSProvider ActiveDirectory
                        if ($adProvider -and $adProvider.Drives.Count -gt 0)
                        {
                            $adDriveObject = $adProvider.Drives | Where-Object {$_.Name -eq $adDriveName -or $_.Name -eq $tempDriveName}
                        }
                    }
                    catch {
                        Log-Info -Message (" Error while trying to access active directory PS drive. Will fall back to creating a new PS drive. Inner exception: {0}" -f $_) -Type Warning -Function "ExecutingAsDeploymentUser"
                    }

                    if (-not $adDriveObject)
                    {
                        try {
                            # Add a new drive
                            $adDriveObject = New-PSDrive -Name $tempDriveName -PSProvider ActiveDirectory -Root '' @serverParams
                        }
                        catch {
                            Log-Info -Message (" Error while trying to create active directory PS drive. Inner exception: {0}" -f $_) -Type Error -Function "ExecutingAsDeploymentUser"
                        }
                    }

                    $ouAcl = $null

                    if ($adDriveObject)
                    {
                        $adDriveName = $adDriveObject.Name

                        try
                        {
                            $ouPath = ("{0}:\{1}" -f $adDriveName,$adOuPath)
                            $ouAcl = Get-Acl $ouPath
                        }
                        catch
                        {
                            Log-Info -Message (" Can't get acls from {0}. Inner exception: {1}" -f $ouPath,$_) -Type Error -Function "ExecutingAsDeploymentUser"
                        }
                        finally {
                            # best effort cleanup if we had added the temp drive
                            try
                            {
                                if ($adDriveName -eq $tempDriveName)
                                {
                                    $adDriveObject | Remove-PSDrive
                                }
                            }
                            catch {}
                        }
                    }

                    if ($ouAcl) {
                        try {
                            #Verify whether the user has generic all permissions or not.
                            $genericAllPermissions = $ouAcl.Access | Where-Object { `
                                $_.IdentityReference -eq $deploymentUserIdentifier.SID -and `
                                $_.ObjectType -eq [System.Guid]::Empty -and `
                                $_.InheritedObjectType -eq [System.Guid]::Empty -and `
                                $_.ActiveDirectoryRights -eq [System.DirectoryServices.ActiveDirectoryRights]::GenericAll
                                }
                            if ($genericAllPermissions)
                            {
                                Log-Info -Message (" AD OU ({0}) has genericAll permissions to the SID {1}." -f $ouPath, $deploymentUserIdentifier.SID ) -Type Info -Function "ExecutingAsDeploymentUser"
                            }
                            else
                            {
                                $computerCreateAndDeleteChildPermissions = $ouAcl.Access | Where-Object { `
                                    $_.IdentityReference -eq $deploymentUserIdentifier.SID -and `
                                    $_.ActiveDirectoryRights -eq [System.DirectoryServices.ActiveDirectoryRights]::CreateChild -bor [System.DirectoryServices.ActiveDirectoryRights]::DeleteChild -and `
                                    $_.ObjectType -eq ([System.Guid]::New('bf967a86-0de6-11d0-a285-00aa003049e2'))
                                    }

                                $readPropertyPermissions = $ouAcl.Access | Where-Object { `
                                    $_.IdentityReference -eq $deploymentUserIdentifier.SID -and `
                                    $_.ActiveDirectoryRights -eq [System.DirectoryServices.ActiveDirectoryRights]::ReadProperty -and `
                                    $_.InheritedObjectType -eq [System.Guid]::Empty -and `
                                    $_.ObjectType -eq [System.Guid]::Empty
                                    }

                                $msfveRecoverInformationobjectsPermissions = $ouAcl.Access | Where-Object { `
                                    $_.IdentityReference -eq $deploymentUserIdentifier.SID -and `
                                    $_.ActiveDirectoryRights -eq [System.DirectoryServices.ActiveDirectoryRights]::GenericAll -and `
                                    $_.ObjectType -eq [System.Guid]::Empty -and `
                                    $_.InheritedObjectType -eq ([System.Guid]::New('ea715d30-8f53-40d0-bd1e-6109186d782c'))
                                    }

                                if ($computerCreateAndDeleteChildPermissions)
                                {
                                    Log-Info -Message (" For AD OU ({0}) found active directory rights ({1}) and object type ({2}) " -f $ouPath, $computerCreateAndDeleteChildPermissions.ActiveDirectoryRights, $computerCreateAndDeleteChildPermissions.ObjectType ) -Type Info -Function "ExecutingAsDeploymentUser"
                                }
                                else
                                {
                                    Log-Info -Message (" Found ACLs for AD OU ({0}), but user ({1})'s didn't have access rights to create/delete computer objects. " -f $ouPath,$credentialName) -Type Error -Function "ExecutingAsDeploymentUser"
                                    $failureReasons += ($testContext["LcAdTxt"].CurrentUserMissingCreateAndDeleteComputerObjectPermission -f $adOuPath)
                                }

                                if ($readPropertyPermissions)
                                {
                                    Log-Info -Message (" For AD OU ({0}) found active directory rights ({1}) and object type ({2}) " -f $ouPath, $readPropertyPermissions.ActiveDirectoryRights, $readPropertyPermissions.ObjectType ) -Type Info -Function "ExecutingAsDeploymentUser"
                                }
                                else
                                {
                                    Log-Info -Message (" Found ACLs for AD OU ({0}), but user ({1})'s didn't have access rights to read AD objects. " -f $ouPath,$credentialName) -Type Error -Function "ExecutingAsDeploymentUser"
                                    $failureReasons += ($testContext["LcAdTxt"].CurrentUserMissingReadObjectPermissions -f $adOuPath)
                                }

                                if ($msfveRecoverInformationobjectsPermissions)
                                {
                                    Log-Info -Message (" For AD OU ({0}) found active directory rights ({1}) and object type ({2}) " -f $ouPath, $msfveRecoverInformationobjectsPermissions.ActiveDirectoryRights, $msfveRecoverInformationobjectsPermissions.ObjectType ) -Type Info -Function "ExecutingAsDeploymentUser"
                                }
                                else
                                {
                                    Log-Info -Message (" Found ACLs for AD OU ({0}), but user ({1})'s didn't have access rights to msFVE-RecoverInformationobjects. " -f $ouPath,$credentialName) -Type Error -Function "ExecutingAsDeploymentUser"
                                    $failureReasons += ($testContext["LcAdTxt"].CurrentUserMissingMsfveRecoverInformationobjectsPermissions -f $adOuPath)
                                }

                            }
                        }
                        catch {
                            Log-Info -Message (" Error while trying to get access rules for OU. Inner exception: {0}" -f $_) -Type Error -Function "ExecutingAsDeploymentUser"
                        }

                    }
                }
                catch {
                    Log-Info -Message (" FAILED to look up ACL for AD OU ({0}) and search for GenericAll ACE for user ({1}). Inner exception: {2}" -f $ouPath,$credentialName,$_) -Type Error -Function "ExecutingAsDeploymentUser"
                }
            }
            # If the deployment user is not available in the OUPath then customer may be using the same user for multiple deployments. On a large AD environments we observed that get-aduser is taking long time and timed out hence skipping the rights permission check.
            else
            {
                Log-Info -Message (" User '{0} not found in {1} ' hence skipping the rights permission check. This may cause deployment failure during domain join phase if the user doesn't have the permissions to create or delete computer objects" -f $credentialName, $outPath) -Type Warning -Function "ExecutingAsDeploymentUser"
                #Assuming user has the permissions to create / delete computer objects.
            }

            if ($failureReasons.Count -gt 0) {
                $allFailureReasons = $failureReasons -join "; "
                $detail = ($testContext["LcAdTxt"].CurrentUserFailureSummary -f $credentials.UserName,$allFailureReasons)
            }
            else
            {
                $statusValue = 'SUCCESS'
                $detail = ""
            }
            return @{
                Resource    = "ExecutingAsDeploymentUser"
                Status      = $statusValue
                TimeStamp   = [datetime]::UtcNow
                Source      = $ENV:COMPUTERNAME
                Detail      = $detail
            }
        }
    })
)

function Test-CauClusterRole {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]
        $HciClusterName
    )

    $ErrorActionPreference = 'Stop'

    try {
        Log-Info -Message ("Get CAU cluster role") -Type Info
        $statusValue = 'FAILURE'

        $cauClusterRole = Get-CauClusterRole -ClusterName $HciClusterName -ErrorAction SilentlyContinue
        if ($cauClusterRole)
        {
            Log-Info -Message ("CAU cluster role configured") -Type Info
            $statusValue = 'SUCCESS'
            $detailedResult = "CAU cluster role configured"
        }
        else
        {
            $detailedResult = "CAU cluster role not configured"
            Log-Info -Message ("CAU cluster role not configured") -Type Error
        }
    }
    catch {
        $detailedResult = 'Test-CauClusterRole failed with an exception : ' + $_
        Log-Info -Message (" Test-CauClusterRole Failed. {0}" -f $detailedResult) -Type Error
    }
    
    $result =  @{
        Status      = $statusValue
        TimeStamp   = [datetime]::UtcNow
        Source      = $ENV:COMPUTERNAME
        Detail = $detailedResult
    }
    $params = @{
        Name               = "AzStackHci_ExternalActiveDirectory_Test_CauClusterRole"
        Title              = "Test cau cluster role"
        DisplayName        = "Test cau cluster role"
        Severity           = 'CRITICAL'
        Description        = 'Tests that the cau cluster role is configured or not.'
        Tags               = @{}
        Remediation        = 'https://aka.ms/hci-envch'
        TargetResourceID   = "Test_CauClusterRole"
        TargetResourceName = "Test_CauClusterRole"
        TargetResourceType = 'ActiveDirectory'
        Timestamp          = [datetime]::UtcNow
        Status             = $statusValue
        AdditionalData     = $result
        HealthCheckSource  = $ENV:EnvChkrId
    }
    return @( New-AzStackHciResultObject @params)
}


function Test-LcmUserCredentials {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [pscredential]
        $LcmUserCredentials,
        [Parameter(Mandatory=$true)]
        [string]
        $DomainFQDN
    )
    try {
        Add-Type -AssemblyName "System.DirectoryServices.AccountManagement"
        $statusValue = 'FAILURE'
        $detailedResult = ''
        $contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
        $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($contextType, $DomainFQDN)
        # Extract username and password from PSCredential
        $credentialParts = $LcmUserCredentials.UserName.Split("\\")
        $username = $credentialParts[$credentialParts.Length-1]
        $password = $LcmUserCredentials.GetNetworkCredential().Password
        if ($principalContext.ValidateCredentials($username, $password))
        {
            $statusValue = 'SUCCESS'
            $detailedResult = 'Validated lcm user credentials.'
            Log-Info -Message (" Test_LcmUserCredentials completed with: {0} {1} {2} " -f $statusValue,$username,$password) -Type Info
        }
        else
        {
            $detailedResult = 'Invalid lcm user credentials.'
        }
    }
    catch {
        $detailedResult = 'Test-LcmUserCredentials failed with an exception : ' + $_
        Log-Info -Message (" Test_LcmUserCredentials Failed. {0}" -f $detailedResult) -Type Error
    }
    
    $result =  @{
        Status      = $statusValue
        TimeStamp   = [datetime]::UtcNow
        Source      = $ENV:COMPUTERNAME
        Detail = $detailedResult
    }
    $params = @{
        Name               = "AzStackHci_ExternalActiveDirectory_Test_LcmUserCredentials"
        Title              = "Test lcm user credentials"
        DisplayName        = "Test lcm user credentials"
        Severity           = 'CRITICAL'
        Description        = 'Tests that the lcm user credentials are synchronized with the AD '
        Tags               = @{}
        Remediation        = 'https://aka.ms/hci-envch'
        TargetResourceID   = "Test_LcmUserCredentials"
        TargetResourceName = "Test_LcmUserCredentials"
        TargetResourceType = 'ActiveDirectory'
        Timestamp          = [datetime]::UtcNow
        Status             = $statusValue
        AdditionalData     = $result
        HealthCheckSource  = $ENV:EnvChkrId
    }
    return @( New-AzStackHciResultObject @params)
}

function Test-OrganizationalUnitOnSession {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]
        $ADOUPath,

        [Parameter(Mandatory=$true)]
        [string]
        $DomainFQDN,

        [Parameter(Mandatory=$true)]
        [string]
        $NamingPrefix,

        [Parameter(Mandatory=$true)]
        [string]
        $ClusterName,

        [Parameter(Mandatory)]
        [array]
        $PhysicalMachineNames,

        [Parameter(Mandatory=$false)]
        [System.Management.Automation.Runspaces.PSSession]
        $Session,

        [Parameter(Mandatory=$false)]
        [string]
        $ActiveDirectoryServer,

        [Parameter(Mandatory=$false)]
        [string]
        $OperationType = $null,

        [Parameter(Mandatory=$false)]
        [pscredential]
        $ActiveDirectoryCredentials
    )

    $testContext = @{
        ADOUPath = $ADOUPath
        ComputersADOUPath = "OU=Computers,$ADOUPath"
        UsersADOUPath = "OU=Users,$ADOUPath"
        DomainFQDN = $DomainFQDN
        NamingPrefix = $NamingPrefix
        ClusterName = $ClusterName
        LcAdTxt = $lcAdTxt
        AdServer = $ActiveDirectoryServer
        AdCredentials = $ActiveDirectoryCredentials
        AdCredentialsUserName = if ($ActiveDirectoryCredentials) { $ActiveDirectoryCredentials.UserName } else { "" }
        PhysicalMachineNames = $PhysicalMachineNames
        OperationType = $OperationType 
    }

    $computerName = if ($Session) { $Session.ComputerName } else { $ENV:COMPUTERNAME }

    Log-Info -Message "Executing test on $computerName" -Type Info

    # Reuse the parameters for Invoke-Command so that we only have to set up context and session data once
    $invokeParams = @{
        ScriptBlock = $null
        ArgumentList = $testContext
    }
    if ($Session) {
        $invokeParams += @{Session = $Session}
    }

    # If provided, verify the AD server and credentials are reachable
    if ($ActiveDirectoryServer -or $ActiveDirectoryCredentials)
    {
        $params = @{}
        if ($ActiveDirectoryServer)
        {
            $params["Server"] = $ActiveDirectoryServer
        }
        if ($ActiveDirectoryCredentials)
        {
            $params["Credential"] = $ActiveDirectoryCredentials
        }
        try {
            $null = Get-ADDomain @params
        }
        catch {
            if (-not $ActiveDirectoryServer) {
                $ActiveDirectoryServer = "default"
            }
            $userName = "default"
            if ($ActiveDirectoryCredentials) {
                $userName = $ActiveDirectoryCredentials.UserName
            }
            throw ("Unable to contact AD server {0} using {1} credentials. Internal exception: {2}" -f $ActiveDirectoryServer,$userName,$_)
        }
    }

    # Initialize the array of detailed results
    $detailedResults = @()

    # Test preparation -- fill in more of the test context that needs to be executed remotely
    $ExternalAdTestInitializors | ForEach-Object {
        $invokeParams.ScriptBlock = $_.ExecutionBlock
        $testName = $_.TestName

        Log-Info -Message "Executing test initializer $testName" -Type Info

        try
        {
            $results = Invoke-Command @invokeParams

            if ($results)
            {
                $testContext += $results
            }
        }
        catch {
            throw ("Unable to execute test {0} on {1}. Inner exception: {2}" -f $testName,$computerName,$_)
        }
    }

    Log-Info -Message "Executing tests with parameters: " -Type Info
    foreach ($key in $testContext.Keys)
    {
        if ($key -ne "LcAdTxt")
        {
            Log-Info -Message " $key : $($testContext[$key])" -Type Info
        }
    }

    # Update InvokeParams with the full context
    $invokeParams.ArgumentList = $testContext

    # For each test, call the test execution block and append the results
    $ExternalAdTests | ForEach-Object {
        # override ScriptBlock with the particular test execution block
        $invokeParams.ScriptBlock = $_.ExecutionBlock
        $testName = $_.TestName

        Log-Info -Message "Executing test $testName" -Type Info

        try
        {
            $results = Invoke-Command @invokeParams

            Log-Info -Message ("Test $testName completed with: {0}" -f $results) -Type Info

            $detailedResults += $results
        }
        catch {
            Log-Info -Message ("Test $testName FAILED. Inner exception: {0}" -f $_) -Type Info
        }
    }

    return $detailedResults
}

function Test-OrganizationalUnit {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]
        $ADOUPath,

        [Parameter(Mandatory=$true)]
        [string]
        $DomainFQDN,

        [Parameter(Mandatory=$true)]
        [string]
        $NamingPrefix,

        [Parameter(Mandatory=$true)]
        [string]
        $ClusterName,

        [Parameter(Mandatory=$true)]
        [array]
        $PhysicalMachineNames,

        [Parameter(Mandatory=$false)]
        [System.Management.Automation.Runspaces.PSSession]
        $PsSession,

        [Parameter(Mandatory=$false)]
        [string]
        $ActiveDirectoryServer = $null,

        [Parameter(Mandatory=$false)]
        [string]
        $OperationType = $null,


        [Parameter(Mandatory=$false)]
        [pscredential]
        $ActiveDirectoryCredentials = $null
    )

    $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop

    Log-Info -Message "Executing Test-OrganizationalUnit"
    $fullTestResults = Test-OrganizationalUnitOnSession -ADOUPath $ADOUPath -DomainFQDN $DomainFQDN -NamingPrefix $NamingPrefix -ClusterName $ClusterName -Session $PsSession -ActiveDirectoryServer $ActiveDirectoryServer -ActiveDirectoryCredentials $ActiveDirectoryCredentials -PhysicalMachineNames $PhysicalMachineNames

    # Build the results
    $TargetComputerName = if ($PsSession.PSComputerName) { $PsSession.PSComputerName } else { $ENV:COMPUTERNAME }
    $remediationValues = $fullTestResults | Where-Object -Property Status -NE 'SUCCESS' | Select-Object $Remediation
    $remediationValues = $remediationValues -join "`r`n"
    if (-not $remediationValues)
    {
        $remediationValues = ''
    }

    $testOuResult = @()
    foreach ($result in $fullTestResults)
    {
        $params = @{
            Name               = "AzStackHci_ExternalActiveDirectory_Test_OrganizationalUnit_$($result.Resource)"
            Title              = "Test AD Organizational Unit - $($result.Resource)"
            DisplayName        = "Test AD Organizational Unit - $($result.Resource)"
            Severity           = 'CRITICAL'
            Description        = 'Tests that the specified organizational unit exists and contains the proper OUs'
            Tags               = @{}
            Remediation        = 'https://aka.ms/hci-envch'
            TargetResourceID   = "Test_AD_OU_$TargetComputerName"
            TargetResourceName = "Test_AD_OU_$TargetComputerName"
            TargetResourceType = 'ActiveDirectory'
            Timestamp          = [datetime]::UtcNow
            Status             = $result.Status
            AdditionalData     = $result
            HealthCheckSource  = $ENV:EnvChkrId
        }
        $testOuResult += New-AzStackHciResultObject @params
    }

    return $testOuResult
}
# SIG # Begin signature block
# MIIoRgYJKoZIhvcNAQcCoIIoNzCCKDMCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBE315Xp47fj12p
# DcNMFiWMnZzqw6HgEAurzyXl8gB0p6CCDXYwggX0MIID3KADAgECAhMzAAAEBGx0
# Bv9XKydyAAAAAAQEMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMjQwOTEyMjAxMTE0WhcNMjUwOTExMjAxMTE0WjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
# AQC0KDfaY50MDqsEGdlIzDHBd6CqIMRQWW9Af1LHDDTuFjfDsvna0nEuDSYJmNyz
# NB10jpbg0lhvkT1AzfX2TLITSXwS8D+mBzGCWMM/wTpciWBV/pbjSazbzoKvRrNo
# DV/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