# servicenow cmdb ci dr protection
# vcenter placeholder

$AllVMwareVMs = Get-Datacenter | Where-Object {$_.Name -like "*Primary*" -or $_.Name -like "*Secondary*" -or $_.Name -like "*DCN*"} | Get-VM | Where-Object { $_.Name -notlike "vCLS*" } | Where-Object { $_.ExtensionData.Summary.Config.ManagedBy.Type -ne "placeholderVm" } | Sort-Object Name
$AllVMwarePlaceholders = $AllVMwareVMs | Where-Object { $_.ExtensionData.Summary.Config.ManagedBy.Type -eq "placeholderVm" }
$AllCmdbCi = Get-ITDServiceNowRecord -Table cmdb_ci_server -Filter "operational_status!=6^u_nd_dr_protectionLIKEVMware" -IncludeTotalCount | Select-Object @{n = 'CiName'; e = { $_.name.display_value } }, @{n = 'CiFqdn'; e = { $_.fqdn.display_value } }, @{n = 'CiOpStatus'; e = { $_.operational_status.display_value } }, @{n = 'DRProtection'; e = { $_.u_nd_dr_protection.display_value } } | Sort-Object CiName

$ArrayList = [System.Collections.ArrayList]@()

# check for placeholder
ForEach ($Ci in $AllCmdbCi) {
    $PlaceholderBool = $null
    $VMBool = $null
    
    If($AllVMwareVMs | Where-Object { $_.Name -eq $Ci.CiFqdn }) {
        $VMBool = $true
    } 
    else {
        $VMBool = $false
    }

    If ($AllVMwarePlaceholders | Where-Object { $_.Name -eq $Ci.CiFqdn }) {
        $PlaceholderBool = $true
    } 
    else {
        $PlaceholderBool = $false
    }

    $obj = [PSCustomObject]@{
        CiName       = $Ci.CiName
        CiFqdn       = $Ci.CiFqdn
        CiOpStatus   = $Ci.CiOpStatus
        DRProtection = $Ci.DRProtection
        VMExists     = $VMBool        
        Placeholder  = $PlaceholderBool
    }

    $null = $ArrayList.Add($obj)
}

# verify no extra entries in vm list / confirm all vms have cmdb entries
ForEach ($VM in $AllVMwareVMs) {
    If (-not ($ArrayList | Where-Object { $_.CiFqdn -eq $VM.Name })) {
        #Write-Host "VM $($VM.Name) does not have a corresponding CMDB entry." -ForegroundColor Red
        $obj = [PSCustomObject]@{
            CiName            = $null
            CiFqdn            = $null
            CiOpStatus        = $null
            DRProtection      = $null
            VMExists          = $VM.Name
            PlaceholderExists = $null
        }
        $null = $ArrayList.Add($obj)
    }
}

# verify no extra entries in placeholder list / confirm all placeholders have cmdb entries
ForEach ($Placeholder in $AllVMwarePlaceholders) {
    If (-not ($ArrayList | Where-Object { $_.CiFqdn -eq $Placeholder.Name })) {
        #Write-Host "Placeholder VM $($Placeholder.Name) does not have a corresponding CMDB entry." -ForegroundColor Red
        $obj = [PSCustomObject]@{
            CiName            = $null
            CiFqdn            = $Placeholder.Name
            CiOpStatus        = $null
            DRProtection      = $null
            VMExists          = $null
            PlaceholderExists = $true
        }
        $null = $ArrayList.Add($obj)
    }
}

$ArrayList | Sort-Object CiFqdn | Format-Table -AutoSize