PowerValidatedSolutions.psm1

# PowerShell Module for VMware Validated Solutions for VMware Cloud Foundation
# Contributions are welcome. https://github.com/vmware-samples/power-validated-solutions-for-cloud-foundation/blob/main/CONTRIBUTING.md

# 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.

### Note
# This PowerShell module should be considered entirely experimental. It is still in development & not tested beyond lab
# scenarios. It is recommended you don't use it for any production environment without testing extensively!

# Enable communication with self signed certs when using Powershell Core. If you require all communications to be secure
# and do not wish to allow communication with self-signed certificates remove lines 17-38 before importing the module.

if ($PSEdition -eq 'Core') {
    $PSDefaultParameterValues.Add("Invoke-RestMethod:SkipCertificateCheck", $true)
}

if ($PSEdition -eq 'Desktop') {
    # Enable communication with self signed certs when using Windows Powershell
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;

    if ("TrustAllCertificatePolicy" -as [type]) {} else {
        Add-Type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertificatePolicy : ICertificatePolicy {
        public TrustAllCertificatePolicy() {}
        public bool CheckValidationResult(
            ServicePoint sPoint, X509Certificate certificate,
            WebRequest wRequest, int certificateProblem) {
            return true;
        }
    }
"@

        [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertificatePolicy
    }
}

Function Confirm-PSModule {
    <#
        .SYNOPSIS
        Checks the status of a PowerShell module

        .DESCRIPTION
        Checks the status of the PowerShell module passed. Logic:
        - Check if module is imported into the current session
        - If module is not imported, check if available on disk and try to import
        - If module is not imported & not available on disk, try PSGallery then install and import
        - If module is not imported, not available and not in online gallery then abort

        Informing user only if the module needs importing/installing. If the module is already present nothing will be displayed.

        .EXAMPLE
        Confirm-PSModule -moduleName 'VMware.vSphere.SsoAdmin'
        This example will check if the current PowerShell session has VMware.vSphere.SsoAdmin installed, if not will try to install it
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$moduleName
    )

    # Check if module is imported into the current session
    if (Get-Module -Name $moduleName) {
        $searchResult = "ALREADY_IMPORTED"
    } else {
        # If module is not imported, check if available on disk and try to import
        if (Get-Module -ListAvailable | Where-Object { $_.Name -eq $moduleName }) {
            Try {
                "`n Module $moduleName not loaded, importing now please wait..."
                Import-Module $moduleName
                Write-Output " Module $moduleName imported successfully."
                $searchResult = "IMPORTED"
            }
            Catch {
                $searchResult = "IMPORT_FAILED"
            }
        } else {
            # If module is not imported & not available on disk, try PSGallery then install and import
            if (Find-Module -Name $moduleName | Where-Object { $_.Name -eq $moduleName }) {
                Try {
                    Write-Output "`n Module $moduleName was missing, installing now please wait..."
                    Install-Module -Name $moduleName -Force -Scope CurrentUser
                    Write-Output " Importing module $moduleName, please wait..."
                    Import-Module $moduleName
                    Write-Output " Module $moduleName installed and imported"
                    $searchResult = "INSTALLED_IMPORTED"
                }
                Catch {
                    $searchResult = "INSTALL_IMPORT_FAILED"
                }
            } else {
                # If module is not imported, not available and not in online gallery then abort
                $searchResult = "NOT_AVAILABLE"
            }
        }
    }
    Return $searchResult
}
Export-ModuleMember -Function Confirm-PSModule

#######################################################################################################################
#Region I D E N T I T Y A N D A C C E S S M A N A G E M E N T F U N C T I O N S ###########

Function Add-IdentitySource {
    <#
        .SYNOPSIS
        Add Active Directory over LDAP/LDAPS as an Identity Provider to vCenter Server

        .DESCRIPTION
        The Add-IdentitySource cmdlets adds Active Directory over LDAP/LDAPS as an Identity Provider to the vCenter
        Server and configures is as the default provider. The cmdlet connects to SDDC Manager using the -server,
        -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Verifies a connection to the Active Directory Domain Controller using the -domain and -dcMachineName values
        - Adds the Active Directory Domain as an Identity Provider if not already present
        - Configures the new LDAP/LDAPs Identity Provider as the default

        .EXAMPLE
        Add-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -dcMachineName dc-sfo01 -baseGroupDn "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -baseUserDn "ou=Security Users,dc=sfo,dc=rainpole,dc=io" -protocol ldap
        This example adds the sfo.rainpole.io domain as the default Identity Provider to vCenter Server using LDAP

        .EXAMPLE
        Add-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -dcMachineName dc-sfo01 -baseGroupDn "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -baseUserDn "ou=Security Users,dc=sfo,dc=rainpole,dc=io" -protocol ldaps -certificate F:\certificates\Root64.cer
        This example adds the sfo.rainpole.io domain as the default Identity Provider to vCenter Server using LDAPS
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$dcMachineName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseGroupDn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseUserDn,
        [Parameter (Mandatory = $true)] [ValidateSet("ldap", "ldaps")] [String]$protocol,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificate
    )

    if (!$PsBoundParameters.ContainsKey("certificate") -and ($protocol -eq "ldaps")) {
        $certificate = Get-ExternalFileName -title "Select the Root CA Certificate File (.cer)" -fileType "cer" -location "default"
    } elseif ($protocol -eq "ldaps") {
        if (!(Test-Path -Path $certificate)) {
            Write-Error  "Certificate (cer) for Root Certificate Authority '$certificate' File Not Found"
            Break
        }
    }

    $domainAlias = ($domain.Split("."))[0].ToUpper()
    $bindUser = $domainBindUser + '@' + ($domain.Split("."))[0].ToLower()
    if ($protocol -eq "ldaps") {
        $primaryUrl = 'ldaps://' + $dcMachineName + '.' + $domain + ':636'
    } elseif ($protocol -eq "ldap") {
        $primaryUrl = 'ldap://' + $dcMachineName + '.' + $domain + ':389'
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (!(Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain })) {
                                if (Test-Connection -ComputerName ($dcMachineName + "." + $domain) -Quiet -Count 1) {
                                    if ($protocol -eq "ldaps") {
                                        Add-LDAPIdentitySource -ServerType ActiveDirectory -Name $domain -DomainName $domain -DomainAlias $domainAlias -PrimaryUrl $primaryUrl -BaseDNUsers $baseUserDn -BaseDNGroups $baseGroupDn -Username $bindUser -Password $domainBindPass -Certificate $certificate
                                    } else {
                                        Add-LDAPIdentitySource -ServerType ActiveDirectory -Name $domain -DomainName $domain -DomainAlias $domainAlias -PrimaryUrl $primaryUrl -BaseDNUsers $baseUserDn -BaseDNGroups $baseGroupDn -Username $bindUser -Password $domainBindPass
                                    }
                                    if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) {
                                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                                $scriptCommand = '/opt/vmware/bin/sso-config.sh -set_default_identity_sources -i ' + $domain + ''
                                                Invoke-VMScript -VM $vcfVcenterDetails.vmName -ScriptText $scriptCommand -GuestUser $vcfVcenterDetails.root -GuestPassword $vcfVcenterDetails.rootPass | Out-Null
                                                #$output = Invoke-VMScript -VM $vcfVcenterDetails.vmName -ScriptText $scriptCommand -GuestUser $vcfVcenterDetails.root -GuestPassword $vcfVcenterDetails.rootPass
                                                Write-Output "Adding Identity Source to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): SUCCESSFUL"
                                            }
                                        }
                                    } else {
                                        Write-Error "Adding Identity Source to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): POST_VALIDATION_FAILED"
                                    }
                                    Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue | Out-Null
                                } else {
                                    Write-Error "Unable to communicate with Active Directory Domain Controller ($dcMachineName), check details: PRE_VALIDATION_FAILED"
                                }
                                Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue
                            } else {
                                Write-Warning "Adding Identity Source to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain), already exists: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-IdentitySource

Function Undo-IdentitySource {
    <#
        .SYNOPSIS
        Removes Active Directory over LDAP/LDAPS as an Identity Provider from vCenter Server

        .DESCRIPTION
        The Undo-IdentitySource cmdlets removes Active Directory over LDAP/LDAPS as an Identity Provider from the
        vCenter Server. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Removes the Active Directory Domain as an Identity Provider if its present

        .EXAMPLE
        Undo-IdentitySource -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io
        This example removes the sfo.rainpole.io domain as an Identity Provider from vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) {
                                Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain } | Remove-IdentitySource | Out-Null
                                if (!(Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain })) {
                                    Write-Output "Removing Identity Source from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing Identity Source from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): POST_VALIDATION_FAILED"
                                }                                
                                Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue
                            } else {
                                Write-Warning "Removing Identity Source from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain), does not exist: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-IdentitySource

Function Add-SddcManagerRole {
    <#
        .SYNOPSIS
        Assign SDDC Manager roles to a user/group

        .DESCRIPTION
        The Add-SddcManagerRole cmdlet assigns an SDDC Manager role to the user or group provided. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Verifies that the bind credetials are valid
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Verifies that the domain is present in vCenter Server as an Identity Provider
        - Verifies the user or group exists in Active Directory
        - Assigns the user or group to the SDDC Manager role

        .EXAMPLE
        Add-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vcf-admins -role ADMIN -type group
        This example assigns the group gg-vcf-admins from domain sfo.rainpole.io the SDDC Manager role ADMIN

        .EXAMPLE
        Add-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal compliance -role OPERATOR -type user
        This example assigns the user compliance from domain sfo.rainpole.io the SDDC Manager role OPERATOR
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateSet("ADMIN", "OPERATOR", "VIEWER")] [String]$role,
        [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type
    )

    Try {
        $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue
        if ($checkAdAuthentication[1] -match "Authentication Successful") {
            $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force
            $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass)
            if (Test-VCFConnection -server $server) {
                if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                        if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) {
                                    if ($type -eq "group") { $adObjectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) }
                                    elseif ($type -eq "user") { $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) }
                                    if ($adObjectCheck) {
                                        if ($type -eq "group") {
                                            $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($domain.ToUpper() + "\" + $principal) }
                                            if ($vcfCheck.name -eq $($domain.ToUpper() + "\" + $principal)) {
                                                Write-Warning "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal), already assigned: SKIPPED"
                                            } else {
                                                New-VCFGroup -group $principal -domain $domain -role $role | Out-Null
                                                $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($domain.ToUpper() + "\" + $principal) }
                                                if ($vcfCheck.name -eq $($domain.ToUpper() + "\" + $principal)) {
                                                    Write-Output "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): POST_VALIDATION_FAILED"
                                                }
                                            }
                                        } elseif ($type -eq "user") {
                                            $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($principal + "@" + $domain.ToUpper()) }
                                            if ($vcfCheck.name -eq $($principal + "@" + $domain.ToUpper())) {
                                                Write-Warning "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal), already assigned: SKIPPED"
                                            } else {
                                                New-VCFUser -user ($principal + "@" + $domain.ToUpper()) -role $role | Out-Null
                                                $vcfCheck = Get-VCFUser | Where-Object { $_.name -eq $($principal + "@" + $domain.ToUpper()) }
                                                if ($vcfCheck.name -eq $($principal + "@" + $domain.ToUpper())) {
                                                    Write-Output "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Assigning the role ($role) in SDDC Manager ($server) to Active Directory $type ($principal): POST_VALIDATION_FAILED"
                                                }
                                            }
                                        }
                                    } else {
                                        Write-Error "Unable to find $type ($principal) in the Active Directory Domain: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED"
                                }
                            }
                        }
                    }
                }
            }
        } else {
            Write-Error  "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED"
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-SddcManagerRole

Function Undo-SddcManagerRole {
    <#
        .SYNOPSIS
        Remove access for a user/group in SDDC Manager

        .DESCRIPTION
        The Undo-SddcManagerRole cmdlet removes access for a user or group in SDDC Manager. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Removes the user or group from SDDC Manager if present

        .EXAMPLE
        Undo-SddcManagerRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -principal gg-vcf-admins -type GROUP
        This example removes access for the group gg-vcf-admins from SDDC Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateSet("GROUP","USER")] [String]$type
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFUser -type $type | Where-Object {$_.name -match $principal}) {
                    Remove-VCFUser -id (Get-VCFUser -type $type | Where-Object {$_.name -match $principal}).id
                    if (!(Get-VCFUser -type $type | Where-Object {$_.name -match $principal})) { 
                        Write-Output "Removing $type from SDDC Manager ($server) named ($principal): SUCCESSFUL"
                    } else {
                        Write-Error "Removing $type from SDDC Manager ($server) named ($principal): POST_VALIDATION_FAILED"
                    }
                } else {
                    Write-Warning "Removing $type from SDDC Manager ($server) named ($principal), not assigned: SKIPPED"
                }                                 
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SddcManagerRole

Function Get-EsxiPasswordPolicy {
    <#
        .SYNOPSIS
        Retrieves ESXi Host Password Policies

        .DESCRIPTION
        The Get-EsxiPasswordPolicy cmdlet retrieves a list of ESXi hosts displaying the currently
        configured password policy nested within a vSphere cluster
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that the workload domain exists in the SDDC Manager inventory
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Gathers the ESXi hosts for the cluster specificed
        - Retrieve all ESXi hosts password policies

        .EXAMPLE
        Get-EsxiPasswordPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cluster sfo-m01-cl0l
        This example retrieves all ESXi hosts password policies within the cluster named sfo-m01-cl01 for the workload domain sfo-m01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster
    )
    
    # Create the ESXi Host object
    $esxiPasswdPolicy = New-Object System.Collections.Generic.List[System.Object]
    
    Try {
        if (Test-Connection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-Cluster | Where-Object {$_.Name -eq $cluster}) {
                                    $esxiHosts = Get-Cluster $cluster | Get-VMHost | Sort-Object -Property Name
                                    if ($esxiHosts) {
                                        Foreach ($esxiHost in $esxiHosts) {
                                            # retreving ESXi password policy string
                                            $passwordPolicy = Get-VMHost -name $esxiHost | Where-Object { $_.ConnectionState -eq "Connected" -or $_.ConnectionState -eq "Maintenance"} | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordQualityControl" }
                                            # retreving ESXi password Expiration Period
                                            $passwordExpire = Get-VMHost -name $esxiHost | Where-Object { $_.ConnectionState -eq "Connected" -or $_.ConnectionState -eq "Maintenance"} | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordMaxDays" }
                                            if ($passwordPolicy -and $passwordExpire) {
                                                # parsing ESXi password policy string
                                                $nodePasswdPolicy = New-Object -TypeName psobject
                                                $nodePasswdPolicy | Add-Member -notepropertyname "fqdn" -notepropertyvalue $esxiHost.Name
                                                $nodePasswdPolicy | Add-Member -notepropertyname "PaswordMaxDays" -notepropertyvalue $passwordExpire.Value
                                                $nodePasswdPolicy | Add-Member -notepropertyname "PasswordQualityControl" -notepropertyvalue $passwordPolicy.Value
                                                $esxiPasswdPolicy.Add($nodePasswdPolicy)
                                                Remove-Variable -Name nodePasswdPolicy
                                            } else {
                                                Write-Error "Unable to retrieve password policy from ESXi host '$esxiHost.Name'"
                                            }
                                        }
                                        return $esxiPasswdPolicy
                                    } else {
                                        Write-Warning "No ESXi hosts found within $cluster cluster."
                                    }
                                } else {
                                    Write-Error "Unable to locate Cluster $cluster in $vcfVcenterDetails.fqdn vCenter Server: PRE_VALIDATION_FAILED"
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to locate workload domain $domain in $server SDDC Manager Server: PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-EsxiPasswordPolicy

Function Get-VCServerPasswordPolicy {
    <#
        .SYNOPSIS
        Retrieves a vCenter servers' Password Policies

        .DESCRIPTION
        The Get-VCServerPasswordPolicy cmdlet returns the currently configured password expiration period
        and the email for warning notification settings for the vCenter Server root account
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Retrieves the password expiration period and the email for warning notification settings for the vCenter Server root account

        .EXAMPLE
        Get-VCServerPasswordPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01
        This example retrieves the password expiration period and the email for warning notification settings for the vCenter Server root account
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain
    )

    Try {
        if (Test-Connection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                Request-vSphereApiToken -Fqdn $vcfVcenterDetails.fqdn -Username $vcfVcenterDetails.ssoAdmin -Password $vcfVcenterDetails.ssoAdminPass -admin | Out-Null
                                $pwdExpirySettings = Get-VCPasswordExpiry
                                if ($pwdExpirySettings){
                                    foreach ($configurationString in $pwdExpirySettings.PSObject.Properties) {
                                        if ($configurationString.name -eq "email") {
                                            $passwdNotifyEmail = $configurationString.value
                                        }
                                        if ($configurationString.name -eq "max_days_between_password_change") {
                                            $passwdExpInDays = $configurationString.value
                                        }
                                    }
                                    $vcPasswdPolicy = New-Object -TypeName psobject
                                    $vcPasswdPolicy | Add-Member -notepropertyname "fqdn" -notepropertyvalue $vcfVcenterDetails.fqdn
                                    $vcPasswdPolicy | Add-Member -notepropertyname "email" -notepropertyvalue $passwdNotifyEmail
                                    $vcPasswdPolicy | Add-Member -notepropertyname "max_days_between_password_change" -notepropertyvalue $passwdExpInDays
                                    return $vcPasswdPolicy
                                } else {
                                    Write-Error "Unable to retrieve password policy for vCenter server '$server'"
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to locate workload domain $domain in $server SDDC Manager Server: PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch{
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-VCServerPasswordPolicy

Function Set-vCenterPasswordExpiration {
    <#
        .SYNOPSIS
        Set the password expiration for the root account

        .DESCRIPTION
        The Set-vCenterPasswordExpiration cmdlet configures password expiration settings for the vCenter Server root
        account. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Configures the password expiration either to never expire or to expire in given number of days
        - Sets the email for warning notification to given value

        .EXAMPLE
        Set-vCenterPasswordExpiration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -passwordExpires $true -email "administrator@rainpole.io" -maxDaysBetweenPasswordChange 999
        This example configures the password expiration settings for the vCenter Server root account to expire after 80 days with email for warning set to "admin@rainpole.io"

        .EXAMPLE
        Set-vCenterPasswordExpiration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -passwordExpires $false
        This example configures the password expiration settings for the vCenter Server root account to never expire
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false, ParameterSetName = 'neverexpire')]
        [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [Bool]$passwordExpires,
        [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$email,
        [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$maxDaysBetweenPasswordChange
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            Request-vSphereApiToken -Fqdn $vcfVcenterDetails.fqdn -Username $vcfVcenterDetails.ssoadmin -Password $vcfVcenterDetails.ssoAdminPass -admin | Out-Null
                            $pwdExpirySettings = Get-VCPasswordExpiry
                            if ($passwordExpires) {
                                Set-VCPasswordExpiry -passwordExpires $passwordExpires -email $email -maxDaysBetweenPasswordChange $maxDaysBetweenPasswordChange | Out-Null
                            } else {
                                Set-VCPasswordExpiry -passwordExpires $passwordExpires | Out-Null
                            }
                            $pwdExpirySettings = Get-VCPasswordExpiry
                            if ($pwdExpirySettings.max_days_between_password_change -eq -1) {
                                Write-Output "Configured Password Expiry on vCenter Server Appliance ($($vcfVcenterDetails.fqdn)) to (Never Expire): SUCCESSFUL"
                            } else {
                                Write-Output "Configured Password Expiry on vCenter Server Appliance ($($vcfVcenterDetails.fqdn)) to ($($pwdExpirySettings.max_days_between_password_change) days) and Email Notification to ($($pwdExpirySettings.email)): SUCCESSFUL"
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vCenterPasswordExpiration

Function Set-EsxiPasswordExpirationPeriod {
    <#
        .SYNOPSIS
        Set ESXi password expiration period in days

        .DESCRIPTION
        The Set-EsxiPasswordExpirationPeriod cmdlet configures the password expiration period policies on ESXi.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that the workload domain exists in the SDDC Manager inventory
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Gathers the ESXi hosts for the cluster specificed
        - Configured all ESXi hosts in he provided cluster

        EXAMPLE
        Set-EsxiPasswordExpirationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cluster sfo-m01-cl01 -ExpirationInDays 60
        This example configures all ESXi hosts within the cluster named sfo-m01-cl01 for the workload domain sfo-m01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ExpirationInDays,
        [Parameter (Mandatory = $false)] [ValidateSet("true","false")] [String]$detail="true"
    )
    
    Try {
        if (Test-Connection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-Cluster | Where-Object { $_.Name -eq $cluster }) {
                                    $esxiHosts = Get-Cluster $cluster | Get-VMHost
                                    Foreach ($esxiHost in $esxiHosts) {
                                        $passwordExpire = Get-VMHost -name $esxiHost | Where-Object { $_.ConnectionState -eq "Connected" -or $_.ConnectionState -eq "Maintenance" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordMaxDays" }
                                        if ($passwordExpire) {
                                            Set-AdvancedSetting -AdvancedSetting $passwordExpire -Value $ExpirationInDays -Confirm:$false | Out-Null
                                            $checkSetting = Get-VMHost -name $esxiHost | Where-Object { $_.ConnectionState -eq "Connected" -or $_.ConnectionState -eq "Maintenance" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordMaxDays" }
                                            if ($checkSetting -match $ExpirationInDays) {
                                                if ($detail -eq "true") {
                                                    Write-Output "Updating Advanced System Setting (Security.PasswordMaxDays) on ESXi Host ($esxiHost): SUCCESSFUL"
                                                }
                                            } else {
                                                Write-Error "Updating Advanced System Setting (Security.PasswordMaxDays) on ESXi Host ($esxiHost): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Error applying Advanced System Setting (Security.PasswordMaxDays) on ESXi Host ($esxiHost): POST_VALIDATION_FAILED"
                                        }
                                    }
                                    if ($detail -eq "false") {
                                        Write-Output "Updating Advanced System Setting (Security.PasswordQualityControl) on all ESXi Hosts for Workload Domain ($domain): SUCCESSFUL"
                                    }
                                } else {
                                    Write-Error "Unable to find Cluster ($cluster) in vCenter Server ($vcfVcenterDetails.fqdn), check details and retry: PRE_VALIDATION_FAILED"
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-EsxiPasswordExpirationPeriod

Function Set-EsxiPasswordPolicy {
    <#
        .SYNOPSIS
        Set ESXi password polciies

        .DESCRIPTION
        The Set-EsxiPasswordPolicy cmdlet configures the password and lockout policies on ESXi. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that the workload domain exists in the SDDC Manager inventory
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Gathers the ESXi hosts for the cluster specificed
        - Configured all ESXi hosts in he provided cluster

        EXAMPLE
        Set-EsxiPasswordPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cluster sfo-m01-cl01 -policy "retry=5 min=disabled,disabled,disabled,disabled,15"
        This example configures all ESXi hosts within the cluster named sfo-m01-cl01 of the workload domain sfo-m01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$policy,
        [Parameter (Mandatory = $false)] [ValidateSet("true","false")] [String]$detail="true"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-Cluster | Where-Object {$_.Name -eq $cluster}) {
                                    $esxiHosts = Get-Cluster $cluster | Get-VMHost
                                    $count = 0
                                    Foreach ($esxiHost in $esxiHosts) {
                                        if (($advancedSetting = Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordQualityControl" })) {
                                            Set-AdvancedSetting -AdvancedSetting $advancedSetting -Value $policy -Confirm:$false | Out-Null
                                            $checkSetting = Get-VMHost | Where-Object { $_.ConnectionState -eq "Connected" } | Get-AdvancedSetting | Where-Object { $_.Name -eq "Security.PasswordQualityControl" }
                                            if ($checkSetting -match $policy) {
                                                if ($detail -eq "true") {
                                                    Write-Output "Updating Advanced System Setting (Security.PasswordQualityControl) on ESXi Host ($esxiHost): SUCCESSFUL"
                                                }
                                            } else {
                                                Write-Error "Updating Advanced System Setting (Security.PasswordQualityControl) on ESXi Host ($esxiHost): POST_VALIDATION_FAILED"
                                            }
                                        }
                                        $count = $count + 1
                                    }
                                    if ($detail -eq "false") {
                                        Write-Output "Updating Advanced System Setting (Security.PasswordQualityControl) on all ESXi Hosts for Workload Domain ($domain): SUCCESSFUL"
                                    }
                                } else {
                                    Write-Error "Unable to find Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)), check details and retry: PRE_VALIDATION_FOUND"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }    
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-EsxiPasswordPolicy

Function Install-WorkspaceOne {
    <#
        .SYNOPSIS
        Deploy Workspace ONE Access Virtual Appliance

        .DESCRIPTION
        The Install-WorkspaceOne cmdlet deploys the Workspace ONE Access Virtual Appliance OVA. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Gathers DNS and NTP configuration from SDDC Manager
        - Deploys the Workspace ONE Access Virtual Appliance to the Management Domain vCenter Server

        .EXAMPLE
        Install-WorkspaceOne -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaIpAddress 192.168.31.60 -wsaGateway 192.168.31.1 -wsaSubnetMask 255.255.255.0 -wsaOvaPath F:\identity-manager.ova -wsaFolder sfo-m01-fd-wsa
        This example deploys the Workspace ONE Access Virtual Appliance named sfo-wsa01.sfo.rainpole.io into the sfo-m01-fd-wsa folder of the management domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaIpAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaSubnetMask,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFolder,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$wsaOvaPath
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("wsaOvaPath")) {
            $wsaOvaPath = Get-ExternalFileName -title "Select the Workspace ONE Access OVA file (.ova)" -fileType "ova" -location "default"
        } else {
            if (!(Test-Path -Path $wsaOvaPath)) {
                Write-Error  "Workspace ONE Access OVA '$wsaOvaPath' File Not Found"
                Break
            }
        }
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $wsaHostname = $wsaFqdn.Split(".")[0]
                            if (Get-VM -Name $wsaHostname -ErrorAction Ignore) {
                                Write-Warning "Deploying a virtual machine in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname), already exists: SKIPPED"
                            } else {
                                $dnsServer1 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "True" }).ipAddress
                                $dnsServer2 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "False" }).ipAddress
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" }).clusters.id) }).Name
                                $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" }).clusters.id) }).primaryDatastoreName
                                $datacenter = (Get-Datacenter -Cluster $cluster).Name
                                $avnCheck = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).name
                                if ($avnCheck) {
                                    $regionaPortgroup = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).name
                                    $domain = (Get-VCFApplicationVirtualNetwork | Where-Object { $_.regionType -eq "REGION_A" }).domainName
                                    $command = '"C:\Program Files\VMware\VMware OVF Tool\ovftool.exe" --noSSLVerify --acceptAllEulas --allowAllExtraConfig --diskMode=thin --powerOn --name=' + $wsaHostname + ' --ipProtocol="IPv4" --ipAllocationPolicy="fixedAllocatedPolicy" --vmFolder=' + $wsaFolder + ' --net:"Network 1"=' + $regionaPortgroup + ' --datastore=' + $datastore + ' --X:injectOvfEnv --prop:vamitimezone=' + $timezone + ' --prop:vami.ip0.IdentityManager=' + $wsaIpAddress + ' --prop:vami.netmask0.IdentityManager=' + $wsaSubnetMask + ' --prop:vami.hostname=' + $wsaFqdn + ' --prop:vami.gateway.IdentityManager=' + $wsaGateway + ' --prop:vami.domain.IdentityManager=' + $domain + ' --prop:vami.searchpath.IdentityManager=' + $domain + ' --prop:vami.DNS.IdentityManager=' + $dnsServer1 + ',' + $dnsServer2 + ' "' + $wsaOvaPath + '" "vi://' + $vcfVcenterDetails.ssoAdmin + ':' + $vcfVcenterDetails.ssoAdminPass + '@' + $vcfVcenterDetails.fqdn + '/' + $datacenter + '/host/' + $cluster + '/"'
                                    Invoke-Expression "& $command" -ErrorAction Ignore
                                    if (Get-VM -Name $wsaHostname -ErrorAction Ignore) {
                                        $Timeout = 900  ## seconds
                                        $CheckEvery = 15  ## seconds
                                        Try {
                                            $timer = [Diagnostics.Stopwatch]::StartNew()  ## Start the timer
                                            Write-Output "Waiting for $wsaIpAddress to become pingable."
                                            While (-not (Test-Connection -ComputerName $wsaIpAddress -Quiet -Count 1)) {
                                                ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop
                                                if ($timer.Elapsed.TotalSeconds -ge $Timeout) {
                                                    Throw "Timeout Exceeded. Giving up on ping availability to $wsaIpAddress"
                                                }
                                                Start-Sleep -Seconds $CheckEvery  ## Stop the loop every $CheckEvery seconds
                                            }
                                        } Catch {
                                            Write-Error "Failed to get a Response from Workspace ONE Access Instance ($wsaFqdn): POST_VALIDATION_FAILURE"
                                        } Finally {
                                            $timer.Stop()  ## Stop the timer
                                        }
                                        $Timeout = 900  ## seconds
                                        $CheckEvery = 5  ## seconds
                                        Try {
                                            $timer = [Diagnostics.Stopwatch]::StartNew()  ## Start the timer
                                            $uri = "https://" + $wsaFqdn + "/SAAS/jersey/manager/api/system/health"
                                            Write-Output "Initial connection made, waiting for ($wsaFqdn) to fully boot and services to start. Be warned, this takes a long time."
                                            While ($timer.Elapsed.TotalSeconds -lt $Timeout) {
                                                ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop
                                                Try {
                                                    $response = Invoke-RestMethod $uri -Method 'GET' -SessionVariable webSession -ErrorAction Ignore
                                                    if ($response.AllOk -eq "true") {
                                                        Write-Output "Deploying Workspace ONE Access Instance ($wsaFqdn) using ($wsaOvaPath): SUCCESSFUL"
                                                        break
                                                    }
                                                } Catch {
                                                    Write-Output "Waiting for ($wsaFqdn) to fully boot up. Checking every $CheckEvery seconds"
                                                }
                                                Start-Sleep -Seconds $CheckEvery  ## Stop the loop every $CheckEvery seconds
                                            }
                                            if ($timer.Elapsed.TotalSeconds -ge $Timeout) {
                                                    Write-Error "Workspace ONE Access Instance ($wsaFqdn) failed to initialize properly. Please delete the VM from vCenter Server ($($vcfVcenterDetails.fqdn)) and retry: POST_VAIDATION_FAILED"
                                            }
                                        } Catch {
                                            Debug-ExceptionWriter -object $_
                                        } Finally {
                                            $timer.Stop()  ## Stop the timer
                                        }
                                    } else {
                                        Write-Error "Deployment of Workspace ONE Access Instance ($wsaFqdn): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error  "Application Virtual Networks have not been configured in SDDC Manager ($server), unable to find REGION_A details. Deploy and try again: PRE_VALIDATION_FAILED"
                                }
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-WorkspaceOne

Function Undo-WorkspaceOne {
    <#
        .SYNOPSIS
        Remove Workspace ONE Access Virtual Appliance

        .DESCRIPTION
        The Undo-WorkspaceOne cmdlet removes the Workspace ONE Access Virtual Appliance. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Removes the Workspace ONE Access Virtual Appliance from the Management Domain vCenter Server

        .EXAMPLE
        Undo-WorkspaceOne -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaHostname sfo-wsa01
        This example removes the Workspace ONE Access Virtual Appliance named sfo-wsa01 from the Management Domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaHostname
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-VM -Name $wsaHostname -ErrorAction Ignore) {
                                if ((Get-VM -Name $wsaHostname).PowerState -ne "PoweredOff") {
                                    Stop-VM -VM $wsaHostname -Kill -Confirm:$false | Out-Null
                                    if ((Get-VM -Name $wsaHostname).PowerState -ne "PoweredOff") {
                                        Write-Error "Unable to Power Off virtual machine: PRE_VALIDATION_FAILED"
                                        Break
                                    }
                                }
                                Remove-VM $wsaHostname -DeletePermanently -Confirm:$false | Out-null
                                if (!(Get-VM -Name $wsaHostname -ErrorAction Ignore)) {
                                    Write-Output "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($wsaHostname), already removed: SKIPPED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-WorkspaceOne

Function Initialize-WorkspaceOne {
    <#
        .SYNOPSIS
        Initalize Workspace ONE Access Virtual Appliance

        .DESCRIPTION
        The Initialize-WorkspaceOne cmdlet performs the initial configuration of Workspace ONE Access Virtual Appliance.
        - Validates that network connectivity is possible to Workspace ONE Access
        - Sets the default password for the admin, root and SSH Users
        - Initializes the internal PostgrsSQL database
        - Activates the default connector

        .EXAMPLE
        Initialize-WorkspaceOne -wsaFqdn sfo-wsa01.sfo.rainpole.io -adminPass VMw@re1! -rootPass VMw@re1! -sshUserPass VMw@re1!
        This example initialzes the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io and sets the default passwords for admin, root and SSH User
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sshUserPass
    )

    Try {
        if (Test-WSAConnection -server $wsaFqdn) {
            $baseUri = "https://" + $wsaFqdn + ":8443"
            $uri = $baseUri + "/login"
            $response = Invoke-RestMethod $uri -Method 'GET' -SessionVariable webSession
            $response | Out-File wsaResponse.txt
            $tokenSource = (Select-String -Path wsaResponse.txt -Pattern 'window.ec_wiz.vk =')
            $token = ($tokenSource -Split ("'"))[1]
            Remove-Item wsaResponse.txt
            if ($token) {
                $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
                $headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                $headers.Add("X-Vk", "$token")
                $headers.Add("Accept", "application/json")
                # Set the Admin Password
                $body = "password=" + $adminPass + "&confpassword=" + $adminPass
                $uri = $baseUri + "/cfg/changePassword"
                Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -WebSession $webSession | Out-Null
                # Set the Root & SSHUser Passwords
                $body = "rootPassword=" + $rootPass + "&sshuserPassword=" + $sshUserPass
                $uri = $baseUri + "/cfg/system"
                Invoke-RestMethod $uri -Method 'POST' -Headers $headers -Body $body -WebSession $webSession  | Out-Null
                # Initalize the Internal Database
                $uri = $baseUri + "/cfg/setup/initialize"
                Invoke-RestMethod $uri -Method 'POST' -Headers $headers -WebSession $webSession  | Out-Null
                # Activate the default connector
                $uri = $baseUri + "/cfg/setup/activateConnector"
                Invoke-RestMethod $uri -Method 'POST' -Headers $headers -WebSession $webSession  | Out-Null
                Write-Output "Initial Configuration of Workspace ONE Access Instance ($wsaFqdn): SUCCESSFUL"
            } else {
                Write-Warning "Initial Configuration of Workspace ONE Access Instance ($wsaFqdn), already performed: SKIPPED"
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Initialize-WorkspaceOne

Function Set-WorkspaceOneNtpConfig {
    <#
        .SYNOPSIS
        Configure NTP Server on Workspace ONE Access Appliance

        .DESCRIPTION
        The Set-WorkspaceOneNtpConfig cmdlet configures the NTP Server details of the Workspace ONE Access Appliance
        using the primary NTP Server configured on SDDC Manager if no NTP Server is provided. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Gathers the NTP configuration details from SDDC Manager
        - Configures Workspace ONE Access NTP configuration

        .EXAMPLE
        Set-WorkspaceOneNtpConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -rootPass VMw@re1!
        This example configures the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io with the primary NTP server defined in SDDC Manager

        .EXAMPLE
        Set-WorkspaceOneNtpConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -rootPass VMw@re1! -ntpServer ntp.lax.rainpole.io
        This example adds the NTP server ntp.lax.rainpole.io to the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io

        .EXAMPLE
        Set-WorkspaceOneNtpConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1! -vrslcmIntegrated -ntpServer ntp.lax.rainpole.io
        This example adds the NTP server ntp.lax.rainpole.io to the vRealize Suite Lifecycle Manager integrated Workspace ONE Access nodes

        .EXAMPLE
        Set-WorkspaceOneNtpConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1! -vrslcmIntegrated
        This example adds the primary NTP server defined in SDDC Manager to the vRealize Suite Lifecycle Manager integrated Workspace ONE Access nodes
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false, ParameterSetName = 'standaloneWsa')] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer,
        [Parameter (Mandatory = $false, ParameterSetName = 'vrslcmIntegrated')] [ValidateNotNullOrEmpty()] [Switch]$vrslcmIntegrated
    )
    
    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($ntpServer) {
                                if ((Test-NtpServer -Server $ntpServer) -eq $false) {
                                    Write-Error "Unable to confirm NTP server $ntpServer is valid: PRE_VALIDATION_FAILED"
                                    Break
                                }
                            } else {
                                $ntpServer = (Get-VCFConfigurationNTP).ipAddress[0]
                            }
                            if ($vrslcmIntegrated) {
                                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                                    if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                                        $wsaVms = Get-vRSLCMProductNode -environmentName globalenvironment -product vidm
                                        foreach ($wsaVm in $wsaVms) {
                                            if (Test-WSAConnection -server $wsaVm.hostname) {
                                                if ((Get-VM -Name $wsaVm.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                                    Set-WorkspaceOneApplianceNtpConfig -vmName $wsaVm.vmName -rootPass $rootPass -ntpServer $ntpServer
                                                } else {
                                                    Write-Error "Unable to locate a virtual machine named ($($wsaVm.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                                }
                                            }
                                        }
                                    } else {
                                        Write-Error "Unable to connect to vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn) to gather Workspace ONE Access appliance inventory: PRE_VALIDATION_FAILED"
                                    }
                                    Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                                }
                            } else {
                                if (!$wsaFqdn) {
                                    Write-Error "The FQDN parameter (-wsaFqdn) is required for a standalone Workspace ONE Access instance: PRE_VALIDATION_FAILED"
                                }
                                $vmName = $wsaFqdn.Split(".")[0]
                                if (Test-WSAConnection -server $wsaFqdn) {
                                    if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                        Set-WorkspaceOneApplianceNtpConfig -vmName $vmName -rootPass $rootPass -ntpServer $ntpServer
                                    } else {
                                        Write-Error  "Unable to locate a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                    }
                                    Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-WorkspaceOneNtpConfig

Function Install-WorkspaceOneCertificate {
    <#
        .SYNOPSIS
        Install a Signed Certificate on Workspace ONE Access Appliance

        .DESCRIPTION
        The Install-WorkspaceOneCertificate cmdlet replaces the certificate on the Workspace ONE Access. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Copies over the certificate files to the Workspace ONE Access appliance and installs the certificate

        .EXAMPLE
        Install-WorkspaceOneCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -rootPass VMw@re1! -sshUserPass VMw@re1!
        This example install the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io with a the signed certificate provided
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sshUserPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$rootCa,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$wsaCertKey,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$wsaCert
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("rootCa")) {
            $rootCa = Get-ExternalFileName -title "Select the Root CA Certificate File (.cer)" -fileType "cer" -location "default"
        } elseif ($PsBoundParameters.ContainsKey("rootCa")) {
            if (!(Test-Path -Path $rootCa)) {
                Write-Error  "Certificate (.cer) for Root Certificate Authority ($rootCa) File Not Found"
                Break
            }
        }
        if (!$PsBoundParameters.ContainsKey("wsaCertKey")) {
            $wsaCertKey = Get-ExternalFileName -title "Select the Workspace ONE Access Certificate Key (.key)" -fileType "key" -locaion "default"
        } elseif ($PsBoundParameters.ContainsKey("wsaCertKey")) {
            if (!(Test-Path -Path $wsaCertKey)) {
                Write-Error  "Certificate Key (.key) for Workspace ONE Access ($wsaCertKey) File Not Found"
                Break
            }
        }
        if (!$PsBoundParameters.ContainsKey("wsaCert")) {
            $wsaCert = Get-ExternalFileName -title "Select the Workspace ONE Access Certificate File (.cer)" -fileType "cer" -location "default"
        } elseif ($PsBoundParameters.ContainsKey("wsaCert")) {
            if (!(Test-Path -Path $wsaCert)) {
                Write-Error  "Certificate (.cer) for Workspace ONE Access ($wsaCert) File Not Found"
                Break
            }
        }
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Test-WSAConnection -server $wsaFqdn) {
                                $vmName = $wsaFqdn.Split(".")[0]
                                Get-Item $rootCa | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force
                                Get-Item $wsaCertKey | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force
                                Get-Item $wsaCert | Copy-VMGuestFile -Destination '/tmp' -VM $vmName -LocalToGuest -GuestUser root -GuestPassword $rootPass -Force
                                $scriptCommand = 'echo "yes" | /usr/local/horizon/scripts/installExternalCertificate.hzn --ca /tmp/' + (Split-Path -Leaf $rootCa) + ' --cert /tmp/' + (Split-Path -Leaf $wsaCert) + ' --key /tmp/' + (Split-Path -Leaf $wsaCertKey)
                                $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcenter.fqdn
                                Write-Output "Installing Signed Certifcate on Workspace ONE Access Instance ($wsaFqdn) using ($wsaCert): SUCCESSFUL"
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-WorkspaceOneCertificate

Function Set-WorkspaceOneSmtpConfig {
    <#
        .SYNOPSIS
        Configure SMTP Server on Workspace ONE Access Appliance
        
        .DESCRIPTION
        The Set-WorkspaceOneSmtpConfig cmdlet configures the SMTP Server details of the Workspace ONE Access Appliance.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to Workspace ONE Access
        - Configures the SMTP Server settings

        .EXAMPLE
        Set-WorkspaceOneSmtpConfig -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -smtpFqdn smtp.sfo.rainpole.io -smtpPort 25 -smtpEmail sfo-wsa@rainpole.io
        This example configures the Workspace ONE Access Virtual Appliance sfo-wsa01.sfo.rainpole.io with the SMTP Server details
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpPort,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpEmail,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpEmailPassword
    )

    Try {
        if (Test-WSAConnection -server $server) {
            if (Test-WSAAuthentication -server $server -user $user -pass $pass) {
                if (!(Get-WSASmtpConfiguration | Where-Object {$_.host -eq $smtpFqdn})) {
                    if (-not $PsBoundParameters.ContainsKey("smtpEmailPassword")) {
                        Set-WSASmtpConfiguration -fqdn $smtpFqdn -port $smtpPort -user $smtpEmail | Out-Null
                    }
                    if ($PsBoundParameters.ContainsKey("smtpEmailPassword")) {
                        Set-WSASmtpConfiguration -fqdn $smtpFqdn -port $smtpPort -user $smtpEmail -pass $smtpEmailPassword | Out-Null
                    }
                    if (Get-WSASmtpConfiguration | Where-Object {$_.host -eq $smtpFqdn}) {
                        Write-Output "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn): SUCCESSFUL"
                    } else {
                        Write-Error "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn): POST_VALIDATION_FAILED"
                    }
                } else {
                    Write-Warning "Configuring SMTP Server for Workspace ONE Access Instance ($server) with SMTP Server ($smtpFqdn), already exists: SKIPPED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-WorkspaceOneSmtpConfig

Function Add-WorkspaceOneDirectory {
    <#
        .SYNOPSIS
        Configure Active Directory LDAP Directory in Workspace ONE Access Appliance

        .DESCRIPTION
        The Add-WorkspaceOneDirectory cmdlet configures Active Directory LDAP Directory in Workspace ONE Access
        Appliance. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to Workspace ONE Access
        - Validates that the bind user can authenticate to the domain
        - Creates an identity provider within Workspace ONE Access

        .EXAMPLE
        Add-WorkspaceOneDirectory -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -baseDnUser "OU=Security Users,DC=sfo,DC=rainpole,DC=io" -baseDnGroup "OU=Security Groups,DC=sfo,DC=rainpole,DC=io" -bindUserDn "CN=svc-wsa-ad,OU=Security Users,DC=sfo,DC=rainpole,DC=io" -bindUserPass VMw@re1! -adGroups "gg-nsx-enterprise-admins","gg-nsx-network-admins","gg-nsx-auditors","gg-wsa-admins","gg-wsa-directory-admins","gg-wsa-read-only" -protocol "ldaps" -certificate "F:\platformtools-l1-dev\certificates\Root64.pem"
        This example configures the domain sfo.rainpole.io as a directory source in Workspace ONE Access Virtual Appliance and syncronises the groups provided
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDnUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDnGroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUserDn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUserPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$adGroups,
        [Parameter (Mandatory = $true)] [ValidateSet("ldap", "ldaps")] [String]$protocol,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificate
    )

    if (!$PsBoundParameters.ContainsKey("certificate") -and ($protocol -eq "ldaps")) {
        $certificate = Get-ExternalFileName -title "Select the Root CA Certificate File (.pem)" -fileType "pem" -location "default"
    } elseif ($protocol -eq "ldaps") {
        if (!(Test-Path -Path $certificate)) {
            Write-Error  "Certificate (cer) for Root Certificate Authority ($certificate') File Not Found"
            Break
        }
    }

    Try {
        if (Test-WSAConnection -server $server) {
            if (Test-WSAAuthentication -server $server -user $user -pass $pass) {
                $checkAdAuthentication = Test-ADAuthentication -user ($bindUserDn.Split(",")[0]).Split("=")[1] -pass $bindUserPass -server $domain -domain $domain -ErrorAction SilentlyContinue
                if ($checkAdAuthentication[1] -match "Authentication Successful") {
                    if (!(Get-WSADirectory | Where-Object { ($_.name -eq $domain) })) {
                        if ($protocol -eq "ldaps") {
                            $directory = Add-WSALdapDirectory -domainName $domain -baseDn $baseDnUser -bindDn $bindUserDn -certificate $certificate
                        } else{
                            $directory = Add-WSALdapDirectory -domainName $domain -baseDn $baseDnUser -bindDn $bindUserDn
                        }
                        $connector = Get-WSAConnector | Where-Object {$_.host -eq $server}
                        Set-WSABindPassword -directoryId $directory.directoryConfigId -connectorId $connector.instanceId -pass $bindUserPass | Out-Null
                        $adUserJson = '{ "identityUserInfo": { "' + $bindUserDn + '": { "selected": true }, "' + $baseDnUser + '": { "selected": true }}}'
                        $mappedGroupObject = @()
                        foreach ($group in $adGroups) {
                            $adGroupDetails = Get-ADPrincipalGuid -domain $domain -user ($bindUserDn.Split(',')[0]).Split('=')[1] -pass $bindUserPass -principal $group
                            if ($adGroupDetails) {
                                $groupsObject = @()
                                $groupsObject += [pscustomobject]@{
                                    'horizonName' = $adGroupDetails.Name
                                    'dn'          = $adGroupDetails.DistinguishedName
                                    'objectGuid'  = $adGroupDetails.ObjectGuid
                                    'groupBaseDN' = $baseDnGroup
                                    'source'      = "DIRECTORY"
                                }
                                $mappedGroupObject += [pscustomobject]@{
                                    'mappedGroup' = ($groupsObject | Select-Object -Skip 0)
                                    'selected'    = $true
                                }
                            } else {
                                Write-Error "Group $group is not available in Active Directory Domain: PRE_VALIDATION_FAILED"
                            }
                        }
                        $mappedGroupObjectData = @()
                        $mappedGroupObjectData += [pscustomobject]@{
                            'mappedGroupData' = $mappedGroupObject
                            'selected'        = $false
                        }
                        $identityGroupObject = @()
                        $identityGroupObject += [pscustomobject]@{
                            $baseDnGroup = ($mappedGroupObjectData | Select-Object -Skip 0)
                        }
                        $adGroupObject = @()
                        $adGroupObject += [pscustomobject]@{
                            'identityGroupInfo'         = ($identityGroupObject | Select-Object -Skip 0)
                            'excludeNestedGroupMembers' = $false
                        }
                        $adGroupJson = $adGroupObject | ConvertTo-Json -Depth 10
                        Set-WSADirectoryUser -directoryId $directory.directoryConfigId -json $adUserJson | Out-Null
                        Set-WSADirectoryGroup -directoryId $directory.directoryConfigId -json $adGroupJson | Out-Null
                        Set-WSASyncSetting -directoryId $directory.directoryConfigId | Out-Null
                        Start-WSADirectorySync -directoryId $directory.directoryConfigId | Out-Null
                        Write-Output "Creating Active Directory ($($protocol.ToUpper())) Directory in Workspace ONE Access Instance ($server) named ($domain): SUCCESSFUL"
                    } else {
                        Write-Warning "Creating Active Directory ($($protocol.ToUpper())) Directory in Workspace ONE Access Instance ($server) named ($domain), already exists: SKIPPED"
                    }
                } else {
                    Write-Error "Authenticating as Active Directory Domain User ($(($bindUserDn.Split(",")[0]).Split("=")[1])): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-WorkspaceOneDirectory

Function Set-WorkspaceOneNsxtIntegration {
    <#
        .SYNOPSIS
        Integrate NSX Manager with Workspace ONE Access

        .DESCRIPTION
        The Set-WorkspaceOneNsxtIntegration cmdlet configures integration between NSX Manager and Workspace ONE Access.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Validates that network connectivity and authentication is possible to Workspace ONE Access
        - Creates a service client within Workspace ONE Access
        - Enables the integration between NSX Manager and Workspace ONE Access

        .EXAMPLE
        Set-WorkspaceOneNsxtIntegration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1!
        This example integrates the Management Domain NSX Manager instance with Workspace ONE Access
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                        if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                            if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                if (Test-WSAConnection -server $wsaFqdn) {
                                    if (Test-WSAAuthentication -server $wsaFqdn -user $wsaUser -pass $wsaPass) {
                                        $clientId = $vcfNsxDetails.fqdn.Split(".")[0] + "-oauth"
                                        $command = 'openssl s_client -connect ' + $wsaFqdn + ':443 2>&1 | openssl x509 -sha256 -fingerprint -noout'
                                        $wsaThumbprint = (Invoke-Expression "& $command").Split("=")[1]
                                        if (!$wsaThumbprint) {
                                            Write-Error "Obtaining SSL Thumbprint for Workspace ONE Access Instance ($wsaFqdn): FAILED"
                                            Break
                                        }
                                        $sharedSecret = (Get-WSAOAuthToken).message
                                        if (!(Get-WSAClient | Where-Object { $_.clientId -eq $clientId })) {
                                            Add-WSAClient -clientId $clientId -sharedSecret $sharedSecret | Out-Null
                                            if (Get-WSAClient | Where-Object { $_.clientId -eq $clientId }) {
                                                Write-Output "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId): SUCCESSFUL"
                                            } else {
                                                Write-Error "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId): POST_VALIDATION_FAILED"
                                                Break
                                            }
                                        } else {
                                            Write-Warning "Creating Service Client in Workspace ONE Access Instance ($wsaFqdn) named ($clientId), already exists: SKIPPED"
                                        }
                                        if (Get-NsxtVidm) {
                                            $clientIdSecret = (Get-WSAClient -clientId $clientId).secret
                                            Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $clientIdSecret -nsxHostname $vcfNsxDetails.fqdn | Out-Null
                                            Write-Output "Updating integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL"
                                        } else {
                                            Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $sharedSecret -nsxHostname $vcfNsxDetails.fqdn | Out-Null
                                            Write-Output "Creating integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL"
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-WorkspaceOneNsxtIntegration

Function Undo-WorkspaceOneNsxtIntegration {
    <#
        .SYNOPSIS
        Disables the integrate between NSX Manager with Workspace ONE Access

        .DESCRIPTION
        The Undo-WorkspaceOneNsxtIntegration cmdlet disables integration between NSX Manager and Workspace ONE Access.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Disables the integration between NSX Manager and Workspace ONE Access

        .EXAMPLE
        Undo-WorkspaceOneNsxtIntegration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1!
        This example disables the integration between NSX Manager with Workspace ONE Access
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                        if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                            if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                if (Test-WSAConnection -server $wsaFqdn) {
                                    if (Test-WSAAuthentication -server $wsaFqdn -user $wsaUser -pass $wsaPass) {
                                        if ((Get-NsxtVidm).vidm_enable -match "True") {
                                            $clientId = $vcfNsxDetails.fqdn.Split(".")[0] + "-oauth"
                                            $command = 'openssl s_client -connect ' + $wsaFqdn + ':443 2>&1 | openssl x509 -sha256 -fingerprint -noout'
                                            $wsaThumbprint = (Invoke-Expression "& $command").Split("=")[1]
                                            if (!$wsaThumbprint) {
                                                Write-Error "Obtaining SSL Thumbprint for Workspace ONE Access Instance ($wsaFqdn): FAILED"
                                                Break
                                            }
                                            #$sharedSecret = (Get-WSAOAuthToken).message
                                            #if ((Get-NsxtVidm).vidm_enable -match "True") {
                                            $clientIdSecret = (Get-WSAClient -clientId $clientId).secret
                                            Set-NsxtVidm -wsaHostname $wsaFqdn -thumbprint $wsaThumbprint -clientId $clientId -sharedSecret $clientIdSecret -nsxHostname $vcfNsxDetails.fqdn -disable | Out-Null
                                            if ((Get-NsxtVidm).vidm_enable -match "False") {
                                                Write-Output "Disabling integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): SUCCESSFUL"
                                            } else {
                                                Write-Error "Disabling integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn): POST_VALIDATION_FAILEDg"
                                            }
                                        } else {
                                            Write-Warning "Disabling integration between NSX Manager ($($vcfNsxDetails.fqdn)) and Workspace ONE Acccess Instance ($wsaFqdn), already disabled: SKIPPED"
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-WorkspaceOneNsxtIntegration

Function Add-NsxtVidmRole {
    <#
        .SYNOPSIS
        Configure Role-Based Access Control for NSX Manager

        .DESCRIPTION
        The Add-NsxtVidmRole cmdlet configures role assignments in NSX Manager. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Assigns Active Directory users or groups to NSX Manager roles based on the -type, -principal, and -role values.

        .EXAMPLE
        Add-NsxtVidmRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -type group -principal "gg-nsx-enterprise-admins@sfo.rainpole.io" -role enterprise_admin
        This example assigns the group gg-nsx-enterprise-admins@sfo.rainpole.io with the enterprise_admin role in NSX Manager

        .EXAMPLE
        Add-NsxtVidmRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -type user -principal "svc-vra-nsx@rainpole.io" -role enterprise_admin
        This example assigns the user svc-vra-nsx@rainpole.io with the enterprise_admin role in NSX Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type,
        [Parameter (Mandatory = $true)] [ValidateSet("auditor", "enterprise_admin", "gi_partner_admin", "lb_admin", "lb_auditor", "network_engineer", "network_op", "netx_partner_admin", "security_engineer", "security_op", "vpn_admin")] [string]$role
    )
    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                        if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                            if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                if ((Invoke-Expression "Get-NsxtVidm$type -searchString $principal" | Where-Object { $_.name -eq $principal })) {
                                    if (!(Get-NsxtUser | Where-Object { $_.name -eq $principal })) {
                                        Invoke-Expression "Set-NsxtRole -principal $principal -type remote_$type -role $role -identitySource VIDM | Out-Null"
                                        if (Get-NsxtUser | Where-Object { $_.name -eq $principal }) {
                                            Write-Output "Assigning $type ($principal) the role ($role) in NSX-T Data Center for Workload Domain ($domain): SUCCESSFUL"
                                        } else {
                                            Write-Error "Assigning $type ($principal) the role ($role) in NSX-T Data Center for Workload Domain ($domain): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Assigning $type ($principal) the role ($role) in NSX-T Data Center for Workload Domain ($domain), already exists: SKIPPED"
                                    }    
                                } else {
                                    Write-Error "Unable to find $type ($principal) in Workspace ONE Access for NSX-T Data Center, check $type synchronization: PRE_VALIDATION_FAILED"
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-NsxtVidmRole

Function Undo-NsxtVidmRole {
    <#
        .SYNOPSIS
        Remove Role-Based Access Control from NSX Manager

        .DESCRIPTION
        The Undo-NsxtVidmRole cmdlet removes role assignments in NSX Manager. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Removes user or group's from NSX Manager roles based on the -principal

        .EXAMPLE
        Undo-NsxtVidmRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -principal "gg-nsx-enterprise-admins@sfo.rainpole.io"
        This example removes the group gg-nsx-enterprise-admins@sfo.rainpole.io from NSX Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                        if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                            if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                if (Get-NsxtUser | Where-Object { $_.name -eq $principal }) {
                                    Remove-NsxtRole -id (Get-NsxtUser | Where-Object { $_.name -eq $principal }).id
                                    if (!(Get-NsxtUser | Where-Object { $_.name -eq $principal })) {
                                        Write-Output "Removing access for ($principal) from NSX-T Data Center for Workload Domain ($domain): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing access for ($principal) from NSX-T Data Center for Workload Domain ($domain): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing access for ($principal) from NSX-T Data Center for Workload Domain ($domain), already removed: SKIPPED"
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-NsxtVidmRole

Function Add-WorkspaceOneRole {
    <#
        .SYNOPSIS
        Assign Active Directory Groups to Roles in the Workspace ONE Access

        .DESCRIPTION
        The Add-WorkspaceOneRole cmdlet assigns roles to Active Directory groups provided to manage administrative
        access to the Workspace ONE Access instance. The cmdlet connects to SDDC Manager using the -server, -user,
        and -password values:
        - Validates that network connectivity and authentication is possible to Workspace ONE Access
        - Validates the role exists in Workspace ONE Access
        - Validates the group exists in Workspace ONE Access
        - Assign the role to the group

        .EXAMPLE
        Add-WorkspaceOneRole -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -group "gg-wsa-admins" -role "Super Admin"
        This example adds the group gg-wsa-admins the Super Admin role
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [ValidateSet("Super Admin", "Directory Admin", "ReadOnly Admin")] [String]$role
    )

    Try {
        if (Test-WSAConnection -server $server) {
            if (Test-WSAAuthentication -server $server -user $user -pass $pass) {
                $roleId = Get-WSARoleId -role $role
                if (!$roleId) {
                    Write-Error "Unable to find role id ($roleId) for role ($role) in Workspace ONE Access Instance ($server): PRE_VALIDATION_FAILED"
                } else {
                    $groupDetails = Get-WSAActiveDirectoryGroupDetail -group $group
                    $groupId = $groupDetails.Resources.id
                    if (!$groupId) {
                        Write-Error "Unable to find the group ($group) in Workspace ONE Access Instance ($server): PRE_VALIDATION_FAILED"
                    } else {
                        $associations = Get-WSARoleAssociation -roleId $roleId
                        $assign = $true
                        if ($associations.groups) {
                            if ($associations.groups -contains $groupId) {
                                Write-Warning "Assigning group ($group) to role ($role) in Workspace ONE Access Instance ($server), already exists: SKIPPED"
                                $assign = $false
                            }
                        }
                        if ($assign) {
                            if ($role -ne "ReadOnly Admin") {
                                Write-Output "Update the Administrator Role Member with ($group) group"
                                $administratorRole = Get-WsaRole | Where-Object { $_.displayName -eq "Administrator" }
                                $adminId =  $administratorRole.id
                                Set-WSARoleMember -groupId $groupId -id $adminId
                            }
                            $response = Add-WSARoleAssociation -roleId $roleId -groupId $groupId
                            if ($response.operations.code -eq "200") {
                                Write-Output "Assigning group ($group) to role ($role) in Workspace ONE Access Instance ($server): SUCCESSFUL"
                            } elseif ($response.operations.code -eq "409") {
                                Write-Warning "$($response.operations.reason)"
                            } else {
                                Write-Error "$($response.operations.reason)"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-WorkspaceOneRole

Function Get-NsxtManagerAuthenticationPolicy {
    <#
        .SYNOPSIS
        Retrieve the current Authentication Policy from NSX Manager Nodes

        .DESCRIPTION
        The Get-NsxtManagerAuthenticationPolicy cmdlet retrieves the current Authentication policy from each NSX
        manager nodes for a workload domain. The cmdlet connects to SDDC Manager using the -server, -user, and
        -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Output the following Authentication policy on each NSX manager node.
            a) api_failed_auth_lockout_period (in sec)
            b) api_failed_auth_reset_period (in sec)
            c) api_max_auth_failures (in attempt)
            d) cli_failed_auth_lockout_period (in sec)
            e) cli_max_auth_failures (in attempt)
            f) minimum_password_length (in characters)
        
            .EXAMPLE
        Get-NsxtManagerAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01
        This example retrieves the current Authentication policy from NSX manager nodes in sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes)) {
                        foreach ($nsxtManagerNode in $vcfNsxDetails.nodes) {
                            if (Test-NSXTConnection -server $nsxtManagerNode.fqdn) {
                                if (Test-NSXTAuthentication -server $nsxtManagerNode.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                    $response = Get-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn
                                    Write-Output "Showing $($nsxtManagerNode.fqdn), results: $response"
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-NsxtManagerAuthenticationPolicy

Function Set-NsxtManagerAuthenticationPolicy {
    <#
        .SYNOPSIS
        Configure Authentication Password Policy NSX Manager Nodes

        .DESCRIPTION
        The Set-NsxtManagerAuthenticationPolicy cmdlet configures Authentication policy within NSX manager nodes within
        a workload domain. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Configure the following Authentication password policy on each NSX manager.
            a) api_failed_auth_lockout_period (in sec)
            b) api_failed_auth_reset_period (in sec)
            c) api_max_auth_failures (in attempt)
            d) cli_failed_auth_lockout_period (in sec)
            e) cli_max_auth_failures (in attempt)
            f) minimum_password_length (in characters)

        .EXAMPLE
        Set-NsxtManagerAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -apiLockoutPeriod 900 -apiResetPeriod 120 -apiMaxAttempt 5 -cliLockoutPeriod 900 -cliMaxAttempt 5 -minPasswdLength 15
        This example configures the Authentication password policy in NSX manager nodes in sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$apiLockoutPeriod,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$apiResetPeriod,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$apiMaxAttempt,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cliLockoutPeriod,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cliMaxAttempt,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$minPasswdLength,
        [Parameter (Mandatory = $false)] [ValidateSet("true","false")] [String]$detail="true"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes)) {
                        if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                            if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                foreach ($nsxtManagerNode in $vcfNsxDetails.nodes) {
                                    if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.AdminPass) {
                                        $response = Get-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn
                                        if (!$PsBoundParameters.ContainsKey("apiLockoutPeriod")){
                                            $apiLockoutPeriod = [int]$response.api_failed_auth_lockout_period
                                        }
                                        if (!$PsBoundParameters.ContainsKey("apiResetPeriod")){
                                            $apiResetPeriod = [int]$response.api_failed_auth_reset_period
                                        }
                                        if (!$PsBoundParameters.ContainsKey("apiMaxAttempt")){
                                            $apiMaxAttempt = [int]$response.api_max_auth_failures
                                        }
                                        if (!$PsBoundParameters.ContainsKey("cliLockoutPeriod")){
                                            $cliLockoutPeriod = [int]$response.cli_failed_auth_lockout_period
                                        }
                                        if (!$PsBoundParameters.ContainsKey("cliMaxAttempt")){
                                            $cliMaxAttempt = [int]$response.cli_max_auth_failures
                                        }
                                        if (!$PsBoundParameters.ContainsKey("minPasswdLength")){
                                            $minPasswdLength = [int]$response.minimum_password_length
                                        }
                                        $response = Set-NsxtManagerAuthPolicy -nsxtManagerNode $nsxtManagerNode.fqdn -api_lockout_period $apiLockoutPeriod -api_reset_period $apiResetPeriod -api_max_attempt $apiMaxAttempt -cli_lockout_period $cliLockoutPeriod -cli_max_attempt $cliMaxAttempt -min_passwd_length $minPasswdLength
                                        if ($detail -eq "true") {
                                            Write-Output "Configuring Authentication Policy on NSX Manager ($($nsxtManagerNode.fqdn)) for Workload Domain ($domain): SUCCESSFUL"
                                        }
                                    }
                                }
                                if ($detail -eq "false") {
                                    Write-Output "Configuring Authentication Password Policy for all NSX Manager Nodes in Workload Domain ($domain): SUCCESSFUL"
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-NsxtManagerAuthenticationPolicy

Function Get-NsxtEdgeNodeAuthenticationPolicy {
    <#
        .SYNOPSIS
        Retrieve Authentication Policy from NSX Edge Nodes

        .DESCRIPTION
        The Get-NsxtEdgeNodeAuthenticationPolicy cmdlet retrieves the current Authentication policy from NSX Edge
        nodes within a workload domain. The cmdlet connects to SDDC Manager using the -server, -user, and -password
        values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Output the following Authentication policy on each NSX Edge Nodes.
            a) cli_failed_auth_lockout_period (in sec)
            b) cli_max_auth_failures (in attempt)
            c) minimum_password_length (in characters)

        .EXAMPLE
        Get-NsxtEdgeNodeAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01
        This example retrieving the Authentication policy for NSX Edge nodes in sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes)) {
                        if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                            if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                $nsxtEdgeNodes = (Get-NsxtEdgeCluster | Where-Object {$_.member_node_type -eq "EDGE_NODE"})
                                foreach ($nsxtEdgeNode in $nsxtEdgeNodes.members) {
                                    $response = Get-NsxtEdgeNodeAuthPolicy -nsxtManager $vcfNsxDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id
                                    Write-Output "Retrieving $($nsxtEdgeNode.transport_node_id), results: $response"
                                }
                            }
                        }
                    }
                }
            }
        }   
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-NsxtEdgeNodeAuthenticationPolicy

Function Set-NsxtEdgeNodeAuthenticationPolicy {
    <#
        .SYNOPSIS
        Configure Authentication Policy NSX Edge Nodes

        .DESCRIPTION
        The Set-NsxtEdgeNodeAuthenticationPolicy cmdlet configures the Authentication policy within NSX Edge nodes.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Configure the following Authentication policy on each NSX Edge Node.
            a) cli_failed_auth_lockout_period (in sec)
            b) cli_max_auth_failures (in attempt)
            c) minimum_password_length (in characters)

        .EXAMPLE
        Set-NsxtEdgeNodeAuthenticationPolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -cliLockoutPeriod 900 -cliMaxAttempt 5 -minPasswdLength 15
        This example configures the Authentication policy of the NSX Edges nodes in sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cliLockoutPeriod,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cliMaxAttempt,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$minPasswdLength,
        [Parameter (Mandatory = $false)] [ValidateSet("true","false")] [String]$detail="true"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                    if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes)) {
                        if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                            if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                                $nsxtEdgeNodes = (Get-NsxtEdgeCluster | Where-Object {$_.member_node_type -eq "EDGE_NODE"})
                                foreach ($nsxtEdgeNode in $nsxtEdgeNodes.members) {
                                    $response = Get-NsxtEdgeNodeAuthPolicy -nsxtManager $vcfNsxDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id
                                    if (!$PsBoundParameters.ContainsKey("cliLockoutPeriod")){
                                        $cliLockoutPeriod = [int]$response.cli_failed_auth_lockout_period
                                    }
                                    if (!$PsBoundParameters.ContainsKey("cliMaxAttempt")){
                                        $cliMaxAttempt = [int]$response.cli_max_auth_failures
                                    }
                                    if (!$PsBoundParameters.ContainsKey("minPasswdLength")){
                                        $minPasswdLength = [int]$response.minimum_password_length
                                    }
                                    $response = Set-NsxtEdgeNodeAuthPolicy -nsxtManager $vcfNsxDetails.fqdn -nsxtEdgeNodeID $nsxtEdgeNode.transport_node_id -cli_lockout_period $cliLockoutPeriod -cli_max_attempt $cliMaxAttempt -min_passwd_length $minPasswdLength
                                    if ($detail -eq "true") {
                                        Write-Output "Configuring Authentication Policy on NSX Edge Node ($nsxtEdgeNode) for Workload Domain ($domain): SUCCESSFUL"
                                    }
                                }
                                if ($detail -eq "false") {
                                    Write-Output "Configuring Authentication Password Policy on all NSX Edge Nodes for Workload Domain ($domain): SUCCESSFUL"
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-NsxtEdgeNodeAuthenticationPolicy

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region S I T E P R O T E C T I O N & D I S A S T E R R E C O V E R Y F U N C T I O N S ###########

Function Install-SiteRecoveryManager {
    <#
        .SYNOPSIS
        Deploy Site Recovery Manager Virtual Appliance

        .DESCRIPTION
        The Install-SiteRecoveryManager cmdlet deploys the Site Recovery Manager Virtual Appliance OVA. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values to retrive the management domain
        vCenter Server details from its inventory and then:
        - Gathers vSphere configuration from vCenter Server
        - Gathers DNS and NTP configuration from SDDC Manager
        - Deploys the Site Recovery Manage Virtual Appliance

        .EXAMPLE
        Install-SiteRecoveryManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -srmFqdn sfo-wsa01.sfo.rainpole.io -srmIpAddress 192.168.31.60 -srmGateway 192.168.31.1 -srmNetPrefix 255.255.255.0 -srmNetworkSearchPath sfo.rainpole.io -srmFolder sfo-m01-fd-srm -srmVaRootPassword VMw@re1! -srmVaAdminPassword VMw@re1! -srmDbPassword VMw@re1! -deploymentOption standard -srmOvfPath F:\identity-manager.ova
        This example deploys the Site Recovery Manager Virtual Appliance into the sfo-m01-fd-srm folder of the management domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmIpAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmNetPrefix,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmNetworkSearchPath,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmFolder,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmVaRootPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmVaAdminPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmDbPassword,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$srmOvfPath,
        [Parameter (Mandatory = $false)] [ValidateSet("Standard", "Large")] [String]$deploymentOption,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmwareOvfToolPath='C:\Program Files\VMware\VMware OVF Tool\ovftool.exe'
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("srmOvfPath")) {
            $srmOvfPath = Get-ExternalFileName -title "Select the Site Recovery Manager OVF file (.ovf)" -fileType "ovf"
        } else {
            if (!(Test-Path -Path $srmOvfPath)) {
                Write-Error  "Site Recovery Manager OVA ($srmOvfPath) File Not Found"
                Break
            }
        }
        if (!(Test-Path -Path $vmwareOvfToolPath)) {
            Write-Error  "VMware OVF Tool ($vmwareOvfToolPath) Not Found, Run again with parameter -vmwareOvfToolPath <path to exe file>"
            Break
        }
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $srmHostname = $srmFqdn.Split(".")[0]
                            $srmDomain = $srmFQDN.Substring($srmFQDN.IndexOf(".") + 1)
                            if (Get-VM -Name $srmHostname -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) {
                                Write-Warning "Deploying a virtual machine in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($srmHostname), already exists: SKIPPED"
                            } else {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName
                                $datacenter = (Get-Datacenter -Cluster $cluster).Name
                                if (((Get-VCFConfigurationDNS).ipAddress).Count -gt 1) {
                                    $dnsServer = (Get-VCFConfigurationDNS).ipAddress[0] + "," + (Get-VCFConfigurationDNS).ipAddress[1]
                                } else { 
                                    $dnsServer = (Get-VCFConfigurationDNS).ipAddress
                                }
                                if (((Get-VCFConfigurationNTP).ipAddress).Count -gt 1) {
                                    $ntpServer = (Get-VCFConfigurationNTP).ipAddress[0] + "," + (Get-VCFConfigurationNTP).ipAddress[1]
                                } else { 
                                    $ntpServer = (Get-VCFConfigurationNTP).ipAddress
                                }
                                $mgmtPortgroup = ((Get-VMHost)[0] | Get-VMHostNetwork | Select-Object Hostname, VMkernelGateway -ExpandProperty VirtualNic | Where-Object {$_.DeviceName -eq "vmk0"}).PortGroupName
                                $netMode = "static"
                                $command = '" ' + $vmwareOvfToolPath + '" --noSSLVerify --acceptAllEulas --allowAllExtraConfig --diskMode=thin --powerOn --name=' + $srmHostname + ' --ipProtocol="IPv4" --ipAllocationPolicy="fixedAllocatedPolicy" --vmFolder=' + $srmFolder + ' --net:"Network 1"=' + $mgmtPortgroup + ' --datastore=' + $datastore + ' --deploymentOption=' + $deploymentOption + ' --prop:varoot-password=' + $srmVaRootPassword + ' --prop:vaadmin-password=' + $srmVaAdminPassword +' --prop:dbpassword=' + $srmDbPassword + ' --prop:network.netmode.VMware_Site_Recovery_Manager_Appliance=' + $netMode + ' --prop:network.ip0.VMware_Site_Recovery_Manager_Appliance=' + $srmIpAddress + ' --prop:network.netprefix0.VMware_Site_Recovery_Manager_Appliance=' + $srmNetPrefix + ' --prop:vami.hostname=' + $srmFqdn + ' --prop:network.domain.VMware_Site_Recovery_Manager_Appliance=' + $srmDomain + ' --prop:network.searchpath.VMware_Site_Recovery_Manager_Appliance=' + $srmNetworkSearchPath + ' --prop:ntpserver=' + $ntpServer +' --prop:network.gateway.VMware_Site_Recovery_Manager_Appliance=' + $srmGateway + ' --prop:network.DNS.VMware_Site_Recovery_Manager_Appliance=' + $dnsServer + ' --prop:enableFileIntegrity= ' + $enableFileIntegrity +' ' + $srmOvfPath + ' "vi://' + $vcfVcenterDetails.ssoAdmin + ':' + $vcfVcenterDetails.ssoAdminPass + '@' + $vcfVcenterDetails.fqdn + '/' + $datacenter + '/host/' + $cluster + '/"'
                                Invoke-Expression "& $command" -ErrorAction Ignore
                                (Get-VM -Name $srmHostname -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)
                                $Timeout = 900  ## seconds
                                $CheckEvery = 15  ## seconds
                                Try {
                                    $timer = [Diagnostics.Stopwatch]::StartNew()  ## Start the timer
                                    Write-Output "Waiting for Site Recovery Manager Instance ($srmFqdn) using IP Address ($srmIpAddress) to Become Pingable."
                                    While (!(Test-NetConnection $srmIpAddress -Port 5480 -WarningAction silentlyContinue | Where-Object { $_.TcpTestSucceeded -eq $True })) {
                                        ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop
                                        if ($timer.Elapsed.TotalSeconds -ge $Timeout) {
                                            Write-Error "Site Recovery Manager Instance ($srmFqdn) failed to initialize properly. Please delete the VM from vCenter Server ($($vcfVcenterDetails.fqdn)) and retry: POST_VAIDATION_FAILED"
                                        }
                                        Start-Sleep -Seconds $CheckEvery  ## Stop the loop every $CheckEvery seconds
                                    }
                                } Catch {
                                    Write-Error "Failed to get a Response from Site Recovery Manager Instance ($srmFqdn): POST_VALIDATION_FAILURE"
                                } Finally {
                                    $timer.Stop()  ## Stop the timer
                                    Do {
                                        $vamiStatus = Test-SrmVamiAuthentication -server $srmFqdn -user admin -pass $srmVaAdminPassword -ErrorAction SilentlyContinue
                                    } Until (($vamiStatus -eq $true))
                                    Write-Output "Deploying a virtual machine in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($srmHostname): SUCCESSFUL"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-SiteRecoveryManager

Function Undo-SiteRecoveryManager {
    <#
        .SYNOPSIS
        Remove vSphere Replication Virtual Appliance

        .DESCRIPTION
        The Undo-SiteRecoveryManager cmdlet removes the vSphere Replication Virtual Appliance. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes the vSphere Replication Virtual Appliance from vCenter Server

        .EXAMPLE
        Undo-SiteRecoveryManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -srmHostname sfo-m01-srm01
        This example removes the vSphere Replication Virtual Appliance named sfo-m01-vrms01 from the Management Domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmHostname
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-VM -Name $srmHostname -ErrorAction Ignore) {
                                if ((Get-VM -Name $srmHostname).PowerState -ne "PoweredOff") {
                                    Stop-VM -VM $srmHostname -Kill -Confirm:$false | Out-Null
                                    if ((Get-VM -Name $srmHostname).PowerState -ne "PoweredOff") {
                                        Write-Error "Unable to Power Off virtual machine ($srmHostname): PRE_VALIDATION_FAILED"
                                        Break
                                    }
                                }
                                Remove-VM $srmHostname -DeletePermanently -Confirm:$false | Out-null
                                if (!(Get-VM -Name $srmHostname -ErrorAction Ignore)) {
                                    Write-Output "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($srmHostname): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($srmHostname): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($srmHostname), already removed: SKIPPED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SiteRecoveryManager

Function Install-vSphereReplicationManager {
    <#
        .SYNOPSIS
        Deploy vSphere Replication Manager Virtual Appliance

        .DESCRIPTION
        The Install-vSphereReplicationManager cmdlet deploys the vSphere Replication Manager Virtual Appliance OVA.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the management domain
        vCenter Server details from its inventory and then:
        - Gathers vSphere configuration from vCenter Server
        - Gathers DNS and NTP configuration from SDDC Manager
        - Deploys the vSphere Replication Manager Virtual Appliance

        .EXAMPLE
        Install-vSphereReplicationManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vrmsFqdn sfo-m01-vrms01.sfo.rainpole.io -vrmsIpAddress 192.168.31.60 -vrmsGateway 192.168.31.1 -vrmsNetPrefix 255.255.255.0 -vrmsNetworkSearchPath sfo.rainpole.io -vrmsFolder sfo-m01-fd-vrms -vrmsVaRootPassword VMw@re1! -vrmsVaAdminPassword VMw@re1! -vrmsOvfPath F:\vrms.ova
        This example deploys the vSphere Replication Manager Virtual Appliance into the sfo-m01-fd-vrms folder of the management domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsIpAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsNetPrefix,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsNetworkSearchPath,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsFolder,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsVaRootPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsVaAdminPassword,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vrmsOvfPath,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmwareOvfToolPath='C:\Program Files\VMware\VMware OVF Tool\ovftool.exe'
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("vrmsOvfPath")) {
            $vrmsOvfPath = Get-ExternalFileName -title "Select the vSphere Replication Manager OVF file (.ovf)" -fileType "ovf"
        } else {
            if (!(Test-Path -Path $vrmsOvfPath)) {
                Write-Error  "vSphere Replication Manager OVA '$vrmsOvfPath' File Not Found"
                Break
            }
        }
        if (!(Test-Path -Path $vmwareOvfToolPath)) {
            Write-Error  "VMware OVF Tool ($vmwareOvfToolPath) Not Found, Run again with parameter -vmwareOvfToolPath <path to exe file>"
            Break
        }
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrmsHostname = $vrmsFqdn.Split(".")[0]
                            $vrmsDomain = $vrmsFQDN.Substring($vrmsFQDN.IndexOf(".") + 1)
                            if (Get-VM -Name $vrmsHostname -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) {
                                Write-Warning "Deploying a virtual machine in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($vrmsHostname), already exists: SKIPPED"
                            } else {
                                # $dnsServer1 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "True" }).ipAddress
                                # $dnsServer2 = (Get-VCFConfigurationDNS | Where-Object { $_.isPrimary -Match "False" }).ipAddress
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName
                                $datacenter = (Get-Datacenter -Cluster $cluster).Name
                                if (((Get-VCFConfigurationDNS).ipAddress).Count -gt 1) {
                                    $dnsServer = (Get-VCFConfigurationDNS).ipAddress[0] + "," + (Get-VCFConfigurationDNS).ipAddress[1]
                                } else { 
                                    $dnsServer = (Get-VCFConfigurationDNS).ipAddress
                                }
                                if (((Get-VCFConfigurationNTP).ipAddress).Count -gt 1) {
                                    $ntpServer = (Get-VCFConfigurationNTP).ipAddress[0] + "," + (Get-VCFConfigurationNTP).ipAddress[1]
                                } else { 
                                    $ntpServer = (Get-VCFConfigurationNTP).ipAddress
                                }
                                $mgmtPortgroup = ((Get-VMHost)[0] | Get-VMHostNetwork | Select-Object Hostname, VMkernelGateway -ExpandProperty VirtualNic | where-object {$_.DeviceName -eq "vmk0"}).PortGroupName
                                $netMode = "static"
                                $command = '" ' + $vmwareOvfToolPath + '" --noSSLVerify --acceptAllEulas --allowAllExtraConfig --diskMode=thin --powerOn --name=' + $vrmsHostname + ' --ipProtocol="IPv4" --ipAllocationPolicy="fixedAllocatedPolicy" --vmFolder=' + $vrmsFolder + ' --net:"Network 1"=' + $mgmtPortgroup + ' --datastore=' + $datastore + ' --prop:varoot-password=' + $vrmsVaRootPassword + ' --prop:vaadmin-password=' + $vrmsVaAdminPassword +' --prop:network.netmode.vSphere_Replication_Appliance=' + $netMode + ' --prop:network.ip0.vSphere_Replication_Appliance=' + $vrmsIpAddress + ' --prop:network.netprefix0.vSphere_Replication_Appliance=' + $vrmsNetPrefix + ' --prop:vami.hostname=' + $vrmsFqdn + ' --prop:network.domain.vSphere_Replication_Appliance=' + $vrmsDomain + ' --prop:network.searchpath.vSphere_Replication_Appliance=' + $vrmsNetworkSearchPath + ' --prop:ntpserver=' + $ntpServer +' --prop:network.gateway.vSphere_Replication_Appliance=' + $vrmsGateway + ' --prop:network.DNS.vSphere_Replication_Appliance=' + $dnsServer + ' --prop:enableFileIntegrity= ' + $enableFileIntegrity +' --vService:installation=com.vmware.vim.vsm:extension_vservice ' + $vrmsOvfPath + ' "vi://' + $vcfVcenterDetails.ssoAdmin + ':' + $vcfVcenterDetails.ssoAdminPass + '@' + $vcfVcenterDetails.fqdn + '/' + $datacenter + '/host/' + $cluster + '/"'
                                Invoke-Expression "& $command"
                                if (Get-VM -Name $vrmsHostname -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) {
                                    $Timeout = 900  ## seconds
                                    $CheckEvery = 15  ## seconds
                                    Try {
                                        $timer = [Diagnostics.Stopwatch]::StartNew()  ## Start the timer
                                        Write-Output "Waiting for vSphere Replication Instance ($vrmsFQDN) using IP Address ($vrmsIpAddress) to Become Pingable."
                                        While (!(Test-NetConnection $vrmsIpAddress -Port 5480 -WarningAction silentlyContinue | Where-Object { $_.TcpTestSucceeded -eq $True })) {
                                        ## If the timer has waited greater than or equal to the timeout, throw an exception exiting the loop
                                        if ($timer.Elapsed.TotalSeconds -ge $Timeout) {
                                            Throw "Timeout Exceeded. Giving up on ping availability to $vrmsIpAddress"
                                        }
                                        Start-Sleep -Seconds $CheckEvery  ## Stop the loop every $CheckEvery seconds
                                        }
                                    } Catch {
                                        Write-Error "Failed to get a Response from vSphere Replication Instance ($vrmsFQDN): POST_VALIDATION_FAILURE"
                                    } Finally {
                                        $timer.Stop()  ## Stop the timer
                                        Write-Output "Deploying a virtual machine in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($vrmsHostname): SUCCESSFUL"
                                    }       
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-vSphereReplicationManager

Function Undo-vSphereReplicationManager {
    <#
        .SYNOPSIS
        Remove vSphere Replication Virtual Appliance

        .DESCRIPTION
        The Undo-vSphereReplicationManager cmdlet removes the vSphere Replication Virtual Appliance. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes the vSphere Replication Virtual Appliance from vCenter Server

        .EXAMPLE
        Undo-vSphereReplicationManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vrmsHostname sfo-m01-vrms01
        This example removes the vSphere Replication Virtual Appliance named sfo-m01-vrms01 from the Management Domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsHostname
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-VM -Name $vrmsHostname -ErrorAction Ignore) {
                                if ((Get-VM -Name $vrmsHostname).PowerState -ne "PoweredOff") {
                                    Stop-VM -VM $vrmsHostname -Kill -Confirm:$false | Out-Null
                                    if ((Get-VM -Name $vrmsHostname).PowerState -ne "PoweredOff") {
                                        Write-Error "Unable to Power Off virtual machine ($vrmsHostname): PRE_VALIDATION_FAILED"
                                        Break
                                    }
                                }
                                Remove-VM $vrmsHostname -DeletePermanently -Confirm:$false | Out-null
                                if (!(Get-VM -Name $vrmsHostname -ErrorAction Ignore)) {
                                    Write-Output "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($vrmsHostname): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($vrmsHostname): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing virtual machine from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($vrmsHostname), already removed: SKIPPED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vSphereReplicationManager

Function Connect-DRSolutionTovCenter {
    <#
        .SYNOPSIS
        Register Site Recovery Manager or vSphere Replication with vCenter Server

        .DESCRIPTION
        The Connect-DRSolutionTovCenter cmdlet registers Site Recovery Manager or vSphere Replication with a vCenter
        Server. The cmdlet connects to SDDC Manager using the -server, -user, and -password:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Validates that network connectivity and authentication is possible to the vSphere Replication or Site
        Recovery Manaeger instance
        - Validates if the solution has already been registerd and if not proceeds with the registration

        .EXAMPLE
        Connect-DRSolutionTovCenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -applianceFqdn sfo-m01-srm01.sfo.rainpole.io -vamiAdminPassword VMw@re1! -siteName SFO-M01 -adminEmail "srm-administrator@rainpole.io" -solution SRM
        This example registers Site Recovery Manager with the vCenter Server of the Management Domain

        .EXAMPLE
        Connect-DRSolutionTovCenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -applianceFqdn sfo-m01-vrms01.sfo.rainpole.io -vamiAdminPassword VMw@re1! -siteName SFO-M01 -adminEmail "vrms-administrator@rainpole.io" -solution VRMS
        This example registers Site Recovery Manager with the vCenter Server of the Management Domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$applianceFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vamiAdminPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmail,
        [Parameter (Mandatory = $true)] [ValidateSet("SRM", "VRMS")] [String]$solution
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($solution -eq "VRMS") {
                                if (Test-VrmsVamiConnection -server $applianceFqdn) {
                                    if (Test-VrmsVamiAuthentication -server $applianceFqdn -user admin -pass $vamiAdminPassword) {
                                        if (!((Get-VrmsConfiguration -ErrorAction SilentlyContinue).connection.vc_instance_id -eq ($global:DefaultVIServer.InstanceUuid))) {
                                            $configTask = Set-VrmsConfiguration -vcenterFqdn $vcfVcenterDetails.fqdn -vcenterInstanceId ($global:DefaultVIServer.InstanceUuid) -ssoUser $vcfVcenterDetails.ssoAdmin -ssoPassword $vcfVcenterDetails.ssoAdminPass -adminEmail $adminEmail -siteName $siteName
                                            Do {
                                                Start-Sleep 2
                                                $vamiStatus = Test-VrmsVamiAuthentication -server $applianceFqdn -user admin -pass $vamiAdminPassword -ErrorAction SilentlyContinue
                                                $taskStatus = Get-VrmsTask -taskId $configTask.id
                                            } Until (($taskStatus.Status -ne "RUNNING") -and ($vamiStatus -eq $true))
                                            if ($taskStatus.Status -eq "SUCCESS") {
                                                Write-Output "Registering $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Registering $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Registering $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)), already registered: SKIPPED"
                                        }
                                    }
                                }
                            } elseif ($solution -eq "SRM") {
                                if (Test-SrmVamiConnection -server $applianceFqdn) {
                                    if (Test-SrmVamiAuthentication -server $applianceFqdn -user admin -pass $vamiAdminPassword) {
                                        if (!((Get-SrmConfiguration -ErrorAction SilentlyContinue).connection.vc_instance_id -eq ($global:DefaultVIServer.InstanceUuid))) {
                                            $configTask = Set-SrmConfiguration -vcenterFqdn $vcfVcenterDetails.fqdn -vcenterInstanceId ($global:DefaultVIServer.InstanceUuid) -ssoUser $vcfVcenterDetails.ssoAdmin -ssoPassword $vcfVcenterDetails.ssoAdminPass -adminEmail $adminEmail -siteName $siteName
                                            Do {
                                                Start-Sleep 2
                                                $vamiStatus = Test-VrmsVamiAuthentication -server $applianceFqdn -user admin -pass $vamiAdminPassword -ErrorAction SilentlyContinue
                                                $taskStatus = Get-VrmsTask -taskId $configTask.id
                                            } Until (($taskStatus.Status -ne "RUNNING") -and ($vamiStatus -eq $true))
                                            if ($taskStatus.Status -eq "SUCCESS") {
                                                Write-Output "Registering $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Registering $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Registering $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)), already registered: SKIPPED"
                                        }
                                    }
                                }
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Connect-DRSolutionTovCenter

Function Undo-DRSolutionTovCenter {
    <#
        .SYNOPSIS
        Remove registration of Site Recovery Manager or vSphere Replication with vCenter Server

        .DESCRIPTION
        The Undo-DRSolutionTovCenter cmdlet removes registration of Site Recovery Manager or vSphere Replication with
        a vCenter Server. The cmdlet connects to SDDC Manager using the -server, -user, and -password:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Validates that network connectivity and authentication is possible to the vSphere Replication or Site
        Recovery Manaeger instance
        - Validates if the solution is registerd and if so proceeds to unregister

        .EXAMPLE
        Undo-DRSolutionTovCenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -applianceFqdn sfo-m01-srm01.sfo.rainpole.io -vamiAdminPassword VMw@re1! -solution SRM
        This example registers Site Recovery Manager with the vCenter Server of the Management Domain

        .EXAMPLE
        Undo-DRSolutionTovCenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -applianceFqdn sfo-m01-vrms01.sfo.rainpole.io -vamiAdminPassword VMw@re1! -solution VRMS
        This example registers Site Recovery Manager with the vCenter Server of the Management Domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$applianceFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vamiAdminPassword,
        [Parameter (Mandatory = $true)] [ValidateSet("SRM", "VRMS")] [String]$solution
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($solution -eq "VRMS") {
                                if (Test-VrmsVamiConnection -server $applianceFqdn) {
                                    if (Test-VrmsVamiAuthentication -server $applianceFqdn -user admin -pass $vamiAdminPassword) {
                                        if ((Get-VrmsConfiguration -ErrorAction SilentlyContinue).connection.vc_instance_id -eq ($global:DefaultVIServer.InstanceUuid)) {
                                            Remove-VrmsConfiguration -ssoUser $vcfVcenterDetails.ssoAdmin -ssoPassword $vcfVcenterDetails.ssoAdminPass | Out-Null
                                            if (!((Get-VrmsConfiguration -ErrorAction SilentlyContinue).connection.vc_instance_id -eq ($global:DefaultVIServer.InstanceUuid))) {
                                                Write-Output "Removing registration for $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Removing registration for $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Removing registration for $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)), not registered: SKIPPED"
                                        }
                                    }
                                }
                            } elseif ($solution -eq "SRM") {
                                if (Test-SrmVamiConnection -server $applianceFqdn) {
                                    if (Test-SrmVamiAuthentication -server $applianceFqdn -user admin -pass $vamiAdminPassword) {
                                        if ((Get-SrmConfiguration -ErrorAction SilentlyContinue).connection.vc_instance_id -eq ($global:DefaultVIServer.InstanceUuid)) {
                                            Remove-SrmConfiguration -ssoUser $vcfVcenterDetails.ssoAdmin -ssoPassword $vcfVcenterDetails.ssoAdminPass | Out-Null
                                            if (!((Get-SrmConfiguration -ErrorAction SilentlyContinue).connection.vc_instance_id -eq ($global:DefaultVIServer.InstanceUuid))) {
                                                Write-Output "Removing registration for $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Removing registration for $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Removing registration for $solution instance ($applianceFqdn) with vCenter Server ($($vcfVcenterDetails.fqdn)), not registered: SKIPPED"
                                        }
                                    }
                                }
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-DRSolutionTovCenter

Function Install-VamiCertificate {
    <#
        .SYNOPSIS
        Install a new certificate for a VAMI interface

        .DESCRIPTION
        The Install-VamiCertificate cmdlet allows you to replace the certificate of a VAMI interface. Supports:
        - vSphere Replication Appliance
        - Site Recovery Manager Appliance

        .EXAMPLE
        Install-VamiCertificate -server sfo-m01-vrms01.sfo.rainpole.io -user admin -pass VMw@re1! -certFile C:\Certs\sfo-m01-vrms01.4.p12 -certPassword VMw@re1! -solution VRMS
        This example replaces the certificate for the VAMI interface of the vSphere Replication
        
        .EXAMPLE
        Install-VamiCertificate -server sfo-m01-srm01.sfo.rainpole.io -user admin -pass VMw@re1! -certFile C:\Certs\sfo-m01-vrms01.4.p12 -certPassword VMw@re1! -solution SRM
        This example replaces the certificate for the VAMI interface of the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certFile,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certPassword,
        [Parameter (Mandatory = $true)] [ValidateSet("SRM", "VRMS")] [String]$solution
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("certFile")) {
            $certFile = Get-ExternalFileName -title "Select the Appliance Certificate File (.p12)" -fileType "p12"
        } elseif ($PsBoundParameters.ContainsKey("certFile")) {
            if (!(Test-Path -Path $certFile)) {
                Write-Error  "Certificate (.p12) '$certFile' File Not Found"
            }
        }
        
        if ($solution -eq "VRMS") {
            if (Test-VrmsVamiConnection -server $server) {
                if (Test-VrmsVamiAuthentication -server $server -user $user -pass $pass) {
                    Set-VrmsVamiCertificate -pkcs12CertFile $certFile -certPassword $certPassword | Out-Null
                    Write-Output "Installing Signed Certifcate on vSphere Replication appliance ($server) using ($certFile): SUCCESSFUL"
                }
            
            }
        } elseif ($solution -eq "SRM") {
            if (Test-SrmVamiConnection -server $server) {
                if (Test-SrmVamiAuthentication -server $server -user $user -pass $pass) {
                    Set-SrmVamiCertificate -pkcs12CertFile $certFile -certPassword $certPassword | Out-Null
                    Write-Output "Installing Signed Certifcate on Site Recovery Manager appliance ($server) using ($certFile): SUCCESSFUL"
                }
            
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-VamiCertificate

Function Add-VrmsNetworkAdapter {
    <#
        .SYNOPSIS
        Adds a second ethernet adapter and configures the required routing for vSphere Replication appliance

        .DESCRIPTION
        The Add-VrmsNetworkAdapter cmdlet adds a second ethernet adapter and configures the required routing for the
        vSphere Replication appliance. The cmdlet connects to SDDC Manager using the -server, -user, and -password
        values:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Validates that network connectivity and authentication is possible to the vSphere Replication instance
        - Configures the secondary ethernet adapter and configures the required routing for the replication network

        .EXAMPLE
        Add-VrmsNetworkAdapter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vrmsFqdn sfo-m01-vrms01.sfo.rainpole.io -vrmsRootPass VMw@re1! -vrmsAdminPass VMw@re1! -vrmsIpAddress 172.18.95.125 -replicationSubnet 172.18.111.0/24 -replicationIpAddress 172.18.111.125 -replicationGateway 172.18.111.1 -replicationPortgroup sfo-m01-cl01-vds01-pg-vrms -replicationRemoteNetwork 172.18.96.0/24
        This example configures the protected and recovery site vSphere Replication appliances to use a secondary ethernet adapter for vSphere Replication traffic.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsRootPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsAdminPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsIpAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$replicationSubnet,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$replicationIpAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$replicationGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$replicationPortgroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$replicationRemoteNetwork
    )

    Try {

        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrmsVmName = $vrmsFqdn.Split(".")[0]
                            if (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {$_.Name -eq $replicationPortgroup}) {
                                if (Test-VrmsVamiAuthentication -server $vrmsFqdn -user admin -pass $vrmsAdminPass) {
                                    if (((Get-VM -Name $vrmsVmName -Server $vcfVcenterDetails.fqdn | Get-NetworkAdapter).Count) -le 1) {
                                        # Add the second NIC to the vSphere Replication Appliance and Restart
                                        Get-VM -Name $vrmsVmName -Server $vcfVcenterDetails.fqdn | New-NetworkAdapter -Server $vcfVcenterDetails.fqdn -NetworkName $replicationPortgroup -Type vmxnet3 -StartConnected:$true -Confirm:$false -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
                                        Set-VrmsApplianceState -action restart | Out-Null
                                        Do {
                                            Start-Sleep 2
                                            $vmObject = Get-VMGuest -VM $vrmsVmName -Server $vcfVcenterDetails.fqdn-ErrorAction SilentlyContinue
                                            $vamiStatus = Test-VrmsVamiAuthentication -server $vrmsFqdn -user admin -pass $vrmsAdminPass -ErrorAction SilentlyContinue
                                        } Until (($vmObject.IPAddress) -and ($vamiStatus -eq $true))
                                        # Configure the IP via API and Restart the vSphere Replication Appliance
                                        Set-VrmsNetworkInterface -interface eth1 -ipAddress $replicationIPAddress -gateway $replicationGateway -prefix $replicationSubnet.Split("/")[1]  | Out-Null
                                        Set-VrmsApplianceState -action restart | Out-Null
                                        Do {
                                            Start-Sleep 2
                                            $vmObject = Get-VMGuest -VM $vrmsVmName -Server $vcfVcenterDetails.fqdn-ErrorAction SilentlyContinue
                                            $vamiStatus = Test-VrmsVamiAuthentication -server $vrmsFqdn -user admin -pass $vrmsAdminPass -ErrorAction SilentlyContinue
                                        } Until (($vmObject.IPAddress) -and ($vamiStatus -eq $true))
                                        # Configure a static route for the replication network
                                        $scriptCommand = "sed -i '/^Gateway*/a Destination=$replicationRemoteNetwork' /etc/systemd/network/10-eth1.network | systemctl restart systemd-networkd.service"
                                        Invoke-VMScript -ScriptType bash -VM $vrmsVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrmsRootPass -Server $vcfVcenterDetails.fqdn | Out-Null
                                        # Configure the Incoming Storage Replication Port
                                        Request-VrmsToken -fqdn $vrmsFqdn -username admin -password $vrmsAdminPass | Out-Null
                                        Set-VrmsReplication -filterIp $replicationIpAddress -managementIp $vrmsIpAddress | Out-Null
                                        #Set-vSRIncomingStorageTraffic -fqdn $vrmsFqdn -username admin -password $vrmsAdminPass -ipAddress $replicationIpAddress -ErrorAction SilentlyContinue | Out-Null
                                        if (!((Get-VrmsConfiguration -replication).filter_ip -match $replicationIpAddress)) {                                                
                                            Write-Error "Setting Incoming Storage Traffic IP Address for vSphere Replication Appliance ($vrmsFqdn): POST_VALIDATION_FAILED"
                                        } else {
                                            Write-Output "Adding Ethernet Adapter to vSphere Replication Instance ($vrmsFqdn): SUCCESSFUL"
                                        }
                                    } else {
                                        Write-Warning "Adding Ethernet Adapter to vSphere Replication Instance ($vrmsFqdn), already exists: SKIPPING" 
                                    }
                                } else {
                                    Write-Error "Unable to find vSphere Distributed Port Group ($replicationPortgroup) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                }
                                Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-VrmsNetworkAdapter

Function Backup-VMOvfProperties {
    <#
        .SYNOPSIS
        Backup-VMOvfProperties

        .DESCRIPTION
        The Backup-VMOvfProperties cmdlet creates a backup of the OVF properties for each supplied VM.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the DR protected VMs from its inventory and then:
        - Creates a backup of the VM OVF environment

        .EXAMPLE
        Backup-VMOvfProperties -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example creates a backup of the OVF properties for each supplied VM.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$fileDir
    )
        
    Try {
        if (!$PsBoundParameters.ContainsKey("fileDir")) {
            $fileDir = Get-ExternalDirectoryPath
        } else {
            if (!(Test-Path -Path $fileDir)) {
                Write-Error  "Directory '$fileDir' Not Found"
                Break
            }
        } 
        # Disconnect all connected vCenters to ensure only the desired vCenter is available
        if ($defaultviservers) {
            $server = $defaultviservers.Name
            foreach ($server in $defaultviservers) {            
                Disconnect-VIServer -Server $server -Confirm:$False
            }
        }
        $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT
        # Retrieve vRSLCM VM Name
        $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass
        if ($vrslcmDetails) {
            Write-Output "Getting vRealize Suite Lifecycle Manager VM Name"
            Connect-VIServer -server $vcenter.fqdn -user $vcenter.ssoAdmin -password $vcenter.ssoAdminPass | Out-Null
            $vrslcmVMName = Get-VM * | Where-Object {$_.Guest.Hostname -eq $vrslcmDetails.fqdn} | Select-Object Name
            $vrslcmVMName = $vrslcmVMName.Name
            $vmsToBackup = @("$vrslcmVMName")                
            Disconnect-VIServer -server $vcenter.fqdn -Confirm:$False
        }
        # Retrieve WSA VM Names
        $wsaDetails = Get-WSAServerDetail -fqdn $server -username $user -password $pass
        if ($wsaDetails) {
            Write-Output "Getting Workspace ONE Access VM Names"
            Connect-VIServer -server $vcenter.fqdn -user $vcenter.ssoAdmin -password $vcenter.ssoAdminPass | Out-Null
            Foreach ($wsaFQDN in $wsaDetails.fqdn) {
                $wsaVMName = Get-VM * | Where-Object {$_.Guest.Hostname -eq $wsaFQDN} | Select-Object Name
                $wsaVMName = $wsaVMName.Name
                $vmsToBackup += ,$wsaVMName
            }
            Disconnect-VIServer -server $vcenter.fqdn -Confirm:$False
        }
        # Retrieve vROPs VM Names
        $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass
        if ($vropsDetails) {
            Write-Output "Getting vRealize Operations Manager VM Names"
            Connect-VIServer -server $vcenter.fqdn -user $vcenter.ssoAdmin -password $vcenter.ssoAdminPass | Out-Null
            Foreach ($vropsFQDN in $vropsDetails.fqdn) {
                $vropsVMName = Get-VM * | Where-Object{$_.Guest.Hostname -eq $vropsFQDN} | Select-Object Name
                $vropsVMName = $vropsVMName.Name
                $vmsToBackup += ,$vropsVMName
            }
            Disconnect-VIServer -server $vcenter.fqdn -Confirm:$False
        }
        # Retrieve vRA VM Names
        $vraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass
        if ($vraDetails) {
            Write-Output "Getting vRealize Automation VM Names"
            Connect-VIServer -server $vcenter.fqdn -user $vcenter.ssoAdmin -password $vcenter.ssoAdminPass | Out-Null
            Foreach ($vraFQDN in $vraDetails.fqdn) {
                $vraVMName = Get-VM * | Where-Object {$_.Guest.Hostname -eq $vraFQDN} | Select-Object Name
                $vraVMName = $vraVMName.Name
                $vmsToBackup += ,$vraVMName
            }
            Disconnect-VIServer -server $vcenter.fqdn -Confirm:$False
        }
        Connect-VIServer -server $vcenter.fqdn -user $vcenter.ssoAdmin -password $vcenter.ssoAdminPass | Out-Null
        Foreach ($vm in $vmsToBackup) {
            $vmToBackup = Get-VM -Name $vm
            Get-VMvAppConfig -vm $vmToBackup
        }
        Disconnect-VIServer -server $vcenter.fqdn -Confirm:$False
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Backup-VMOvfProperties

Function Restore-VMOvfProperties {
    <#
        .SYNOPSIS
        Restore-VMOvfProperties

        .DESCRIPTION
        The Restore-VMOvfProperties cmdlet creates a backup of the OVF properties for each supplied VM.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the DR protected VMs from its inventory and then:
        - Creates a restore of the VM OVF environment

        .EXAMPLE
        Restore-VMOvfProperties -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example creates a backup of the OVF properties for each supplied VM.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$fileDir
    )

    Try {       
        if (!$PsBoundParameters.ContainsKey("fileDir")) {
            $fileDir = Get-ExternalDirectoryPath
        } else {
            if (!(Test-Path -Path $fileDir)) {
                Write-Error  "Directory '$fileDir' Not Found"
                Break
            }
        } 
        $fileNames = @()
        $fileNames = Get-ChildItem -File "$($fileDir)\*-property-backup.json" -Recurse
        # Disconnect all connected vCenters to ensure only the desired vCenter is available
        if ($defaultviservers) {
            $server = $defaultviservers.Name
            foreach ($server in $defaultviservers) {            
                Disconnect-VIServer -Server $server -Confirm:$False
            }
        }
        $vCenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT
        Connect-VIServer -server $vcenter.fqdn -user $vcenter.ssoAdmin -password $vcenter.ssoAdminPass | Out-Null
        Foreach ($fileName in $fileNames) {
            $fileName = $fileName.Name
            $separator = "-property-backup.json"
            $restoredVM = ($filename -split $separator)[0]

            $vmSettings = Get-content "$($fileDir)\$($restoredVM)-property-backup.json" | convertfrom-json
            if ($vmSettings) {
                $foundVM = Get-VM -Name $restoredVM -ErrorAction SilentlyContinue
                if ($foundVM) {
                    Write-Output "Restoring VM OVF Settings for $restoredVM"
                    Set-VMOvfIPAssignment -vm $foundVM -assignment $vmSettings.IpAssignment
                    if ($vmSettings.eula) {
                        Set-VMOvfEULA -vm $foundVM -eula $vmSettings.eula    
                    }
                    Set-VMOvfEnvTransport -vm $foundVM -transport $vmSettings.ovfEnvironmentTransport
                    foreach ($product in $vmSettings.product) {
                        New-VMOvfProduct -vm $foundVM -product $product
                    }
                    foreach ($property in $vmSettings.property) {
                        New-VMOvfProperty -vm $foundVM -property $property
                    }                   
                } else {
                    Write-Output "Placeholder $restoredVM not found in $($vcenter.fqdn)"
                }
            }
        }
        Disconnect-VIServer -server $vcenter.fqdn -Confirm:$False
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Restore-VMOVFProperties

Function Get-VMvAppConfig {
    <#
        .SYNOPSIS
        Retrieves the full OVF environment settings from a standard VM.

        .DESCRIPTION
        Saves the setting of the passed VM object to a JSON file

        .EXAMPLE
        Get-VMAppConfig -vm $vm
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$vm
    )

    $targetFile = $fileDir + "\" + $vm.name + "-property-backup.json"
    Write-Output "Initating Backup of OVF Properties for $vm"
    Try {
        if ($vm.ExtensionData.Config.VAppConfig) {
            $vmVappConfig = $vm.ExtensionData.Config.VAppConfig | ConvertTo-Json | Out-File $targetFile
            Write-Output "OVF Properties successfully captured"
            return $vmVappConfig
        } else {
            Write-Output "No OVF properties were detected on $($vm.name). You may ignore this message if this is correct." -colour magenta
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-VMvAppConfig

Function New-VMOvfProperty {
    <#
        .SYNOPSIS
        Create a single OVF Property on a standard VM.

        .DESCRIPTION
        Accepts a object with propery details, parses it and adds it to supplied VM

        .EXAMPLE
        New-VMOvfProperty -vm $vm -property $propertyObject
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$vm,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$property
    )

    #define spec
    $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $spec.vAppConfig = New-Object VMware.Vim.VmConfigSpec
    $propertySpec = New-Object VMware.Vim.VAppPropertySpec
    
    #populate spec
    $propertySpec.Operation = "Add"
    $propertySpec.Info = New-Object VMware.Vim.VAppPropertyInfo
    $propertySpec.info.category = $property.category 
    $propertySpec.info.classId = $property.classId
    $propertySpec.info.defaultValue = $property.defaultValue 
    $propertySpec.info.description = $property.description   
    $propertySpec.info.id = $property.id 
    $propertySpec.info.instanceId = $property.instanceId      
    $propertySpec.info.key = $property.key
    $propertySpec.info.label = $property.label   
    $propertySpec.info.type = $property.type 
    $propertySpec.info.typeReference = $property.typeReference 
    $propertySpec.info.userConfigurable = $property.userConfigurable 
    $propertySpec.info.value = $property.value
    $spec.VAppConfig.Property = $propertySpec

    #write spec
    Write-Output "Creating OVF Property $($property.id) on $($vm.name)"
    $task = $vm.ExtensionData.ReconfigVM_Task($spec)
    $task1 = Get-Task -Id ("Task-$($task.value)")
    $waitask = $task1 | Wait-Task 
}
Export-ModuleMember -Function New-VMOvfProperty

Function Set-VMOvfIPAssignment {
    <#
        .SYNOPSIS
        Sets the IP Assignment OVF Setting

        .DESCRIPTION
        Accepts a object with IP Assigment details and assigns it to the supplied VM

        .EXAMPLE
        Set-VMOvfIPAssignment -vm $vm -assignment $assignmentObject
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$vm,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$assignment
    )

    #define spec
    $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $spec.vAppConfig = New-Object VMware.Vim.VmConfigSpec
    $assignmentSpec = New-Object VMware.Vim.VAppIPAssignmentInfo

    #populate spec
    $assignmentSpec.ipAllocationPolicy = $assignment.ipAllocationPolicy
    $assignmentSpec.SupportedAllocationScheme = $assignment.SupportedAllocationScheme
    $assignmentSpec.SupportedIpProtocol = $assignment.SupportedIpProtocol
    $assignmentSpec.IpProtocol = $assignment.IpProtocol
    $spec.vAppConfig.IpAssignment = $assignmentSpec

    #write spec
    Write-Output "Configuring IP Assignment setting on $($vm.name)"
    $task = $vm.ExtensionData.ReconfigVM_Task($spec)
    $task1 = Get-Task -Id ("Task-$($task.value)")
    $waitask = $task1 | Wait-Task 
}
Export-ModuleMember -Function Set-VMOvfIPAssignment

Function Set-VMOvfEnvTransport {
    <#
        .SYNOPSIS
        Sets the Environment Transport setting for OVF properties

        .DESCRIPTION
        Accepts a object with Environment Transport details and assigns it to the supplied VM

        .EXAMPLE
        Set-VMOvfEnvTransport -vm $vm -transport $transportObject
    #>
 

    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$vm,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$transport
    )

    #define spec
    $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $spec.vAppConfig = New-Object VMware.Vim.VmConfigSpec

    #populate spec
    $spec.vAppConfig.ovfEnvironmentTransport = $transport
    
    #write spec
    Write-Output "Configuring Environment Transport setting on $($vm.name)"
    $task = $vm.ExtensionData.ReconfigVM_Task($spec)
    $task1 = Get-Task -Id ("Task-$($task.value)")
    $waitask = $task1 | Wait-Task 
}
Export-ModuleMember -Function Set-VMOvfEnvTransport

Function New-VMOvfProduct {
    <#
        .SYNOPSIS
        Create a single OVF Product on a standard VM.

        .DESCRIPTION
        Accepts a object with produt details, parses it and adds it to supplied VM

        .EXAMPLE
        New-VMOvfProduct -vm $vm -product $productObject
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()][PSObject]$vm,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$product
    )

    #define spec
    $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $spec.vAppConfig = New-Object VMware.Vim.VmConfigSpec
    $productSpec = New-Object VMware.Vim.VAppProductSpec

    #populate spec
    $productSpec.Operation = "Add"
    $productSpec.Info = New-Object VMware.Vim.VAppProductInfo
    $productSpec.info.appUrl = $product.appUrl
    $productSpec.info.classId = $product.classId 
    $productSpec.info.fullVersion = $product.fullVersion 
    $productSpec.info.instanceId = $product.instanceId   
    $productSpec.info.key = $product.key 
    $productSpec.info.name = $product.name 
    $productSpec.info.productUrl = $product.productUrl   
    $productSpec.info.vendor = $product.vendor
    $productSpec.info.vendorUrl = $product.vendorUrl
    $productSpec.info.version = $product.version
    $spec.VAppConfig.Product = $productSpec

    #write spec
    Write-Output "Adding Product Setting on $($vm.name)"
    $task = $vm.ExtensionData.ReconfigVM_Task($spec)
    $task1 = Get-Task -Id ("Task-$($task.value)")
    $waitask = $task1 | Wait-Task 
}
Export-ModuleMember -Function New-VMOvfProduct

Function Set-VMOvfEULA {
    <#
        .SYNOPSIS
        Sets the EULA setting for OVF properties

        .DESCRIPTION
        Accepts a object with EULA details and assigns it to the supplied VM

        .EXAMPLE
        Set-VMOvfEULA -vm $vm -eula $eulaObject
    #>
    

    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$vm,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$eula
    )

    #define spec
    $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $spec.vAppConfig = New-Object VMware.Vim.VmConfigSpec

    #populate spec
    $spec.vAppConfig.eula = $eula

    #write spec
    Write-Output "Setting EULA on $($vm.name)"
    $task = $vm.ExtensionData.ReconfigVM_Task($spec)
    $task1 = Get-Task -Id ("Task-$($task.value)")
    $waitask = $task1 | Wait-Task 
}
Export-ModuleMember -Function Set-VMOvfEULA

Function Get-VMOvfProperty {
    <#
        .SYNOPSIS
        Get OVF properties of a virtual appliance

        .DESCRIPTION
        Returns OVF properties of a virtual appliance

        .EXAMPLE
        Get-VMOvfProperty -vm (Get-VM -Name xreg-wsa01a)
        This example returns an object that contains a full list of OVF properties for xreg-wsa01a
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [psObject]$vm
    )

    $vappProperties = $VM.ExtensionData.Config.VAppConfig.Property
    $results = @()
    foreach ($vappProperty in $vappProperties | Sort-Object -Property Id) {
        $tmp = [pscustomobject] @{
            Id = $vappProperty.Id;
            Value = $vappProperty.Value
        }
        $results+=$tmp
    }
    $results
}
Export-ModuleMember -Function Get-VMOvfProperty

Function Set-VMOvfProperty {
    <#
        .SYNOPSIS
        Sets OVF properties on a virtual appliance

        .DESCRIPTION
        Accepts a hash table with property ID and value and sets the defined OVF property and value for a virtual
        appliance.

        .EXAMPLE
        Set-VMOvfProperty -vm (Get-VM -Name xreg-wsa01a) -Properties @{"DNS"="172.16.11.4,172.16.11.5"}
        This example sets the DNS servers to 172.16.11.4 and 172.16.11.5 in the OVF properties for xreg-wsa01a
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [PSObject]$vm,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [hashtable]$properties
    )

    $vappProperties = $VM.ExtensionData.Config.VAppConfig.Property
    
    #define spec
    $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $spec.vAppConfig = New-Object VMware.Vim.VmConfigSpec
    $propertySpec = New-Object VMware.Vim.VAppPropertySpec[]($properties.count)

    #populate spec
    foreach ($vappProperty in $vappProperties) {
        if($properties.ContainsKey($vappProperty.Id)) {
            $tmp = New-Object VMware.Vim.VAppPropertySpec
            $tmp.Operation = "edit"
            $tmp.Info = New-Object VMware.Vim.VAppPropertyInfo
            $tmp.Info.Key = $vappProperty.Key
            $tmp.Info.value = $properties[$vappProperty.Id]
            $propertySpec+=($tmp)
        }
    }
    $spec.VAppConfig.Property = $propertySpec

    #write spec
    Write-Output "Setting vApp properties on $($vm.name)"
    $task = $vm.ExtensionData.ReconfigVM_Task($spec)
    $task1 = Get-Task -Id ("Task-$($task.value)")
    $waitask = $task1 | Wait-Task 
}
Export-ModuleMember -Function Set-VMOvfProperty

Function Get-NSXLBDetails {
    <#
        .SYNOPSIS
        Get-NSXLBDetails

        .DESCRIPTION
        The Get-NSXLBDetails cmdlet gets the IP addresses of the VIPs & pool members for the NSX-T Load Balancer for vRealize.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values to retrive the NSX load balancer configurationn

        .EXAMPLE
        Get-NSXLBDetails -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example gets the IP addresses of the VIPs & pool members for the NSX-T Load Balancer for vRealize.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        # Retrieve WSA VIP
        $wsaDetails = Get-WSAServerDetail -fqdn $server -username $user -password $pass
        if ($wsaDetails) {
            Write-Output "Found Workspace ONE Access. Getting Virtual Server & Node IPs"
                $wsaVIP = $wsaDetails.loadBalancerIpAddress
                $wsaNode1IP = $wsaDetails.node1IpAddress
                $wsaNode2IP = $wsaDetails.node2IpAddress
                $wsaNode3IP = $wsaDetails.node3IpAddress
            }
        # Retrieve vROPs VM Names
        $vropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass
        if ($vropsDetails) {
            Write-Output "Found vRealize Operations. Getting Virtual Server & Node IPs"                
                $vropsVIP = $vropsDetails.loadBalancerIpAddress
                $vopsNode1IP = $vropsDetails.node1IpAddress
                $vopsNode2IP = $vropsDetails.node2IpAddress
                $vopsNode3IP = $vropsDetails.node3IpAddress
            }
        # Retrieve vRA VM Names
        $vraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass
        if ($vraDetails) {
            Write-Output "Found vRealize Automation. Getting Virtual Server & Node IPs"
                $vraVIP = $vraDetails.loadBalancerIpAddress
                $vraNode1IP = $vraDetails.node1IpAddress
                $vraNode2IP = $vraDetails.node2IpAddress
                $vraNode3IP = $vraDetails.node3IpAddress
        }
        # Gather NSX-T Manager Details
        Write-Output "Getting NSX-T Login Details"
        $nsxt = Get-NsxtServerDetail -fqdn $server -user $user -pass $pass -domainType MANAGEMENT
        $nsxtFQDN = $nsxt.fqdn
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-NSXLBDetails

Function Add-vRSLCMNtpServer {
    <#
        .SYNOPSIS
        Add an NTP Server for the vRealize Suite Lifecycle Manager appliance

        .DESCRIPTION
        The Add-vRSLCMNtpServer cmdlet configures the NTP Server details of the vRealize Suite Lifecycle Manager
        appliance using one or more NTP servers passed as a parameter. The cmdlet connects to SDDC Manager using
        the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures the vRealize Suite Lifecycle Manager appliance NTP configuration
        
        .EXAMPLE
        Add-vRSLCMNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -ntpServer ntp.lax.rainpole.io -ntpServerDesc "VCF NTP Server 2"
        This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to add ntp.lax.rainpole.io to its list of NTP servers
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServerDesc
    )

    $testNtp = Test-NtpServer -Server $ntpServer
    if ($testNtp -eq $false) {
        Write-Error "Unable to confirm NTP server $ntpServer is valid: PRE_VALIDATION_FAILED"
        Break
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) {
                                $vmName = $vrslcmDetails.fqdn.Split(".")[0]
                                if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                    $vrslcmProductNtpServers = Get-vRSLCMProductNtpServer
                                    if ($vrslcmProductNtpServers -match $ntpServer) {
                                        Write-Warning "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) product NTP server list, already performed: SKIPPED"
                                    } else {
                                        $addvRSLCMProductNtp = Add-vRSLCMProductNtpServer -ntpServer $ntpServer -ntpServerDesc $ntpServerDesc -ErrorAction SilentlyContinue
                                        if ($addvRSLCMProductNtp -match $ntpServer) {
                                            Write-Output "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) product NTP server list: SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) product NTP server list: POST_VALIDATION_FAILED"
                                        }
                                    }
                                    $vRSLCMAppliancePreCheck = Get-vRSLCMProductNtpServer
                                    if ($vRSLCMAppliancePreCheck -match $ntpServer) {
                                        $vrslcmApplianceNtpConfig = Get-vRSLCMApplianceNtpConfig
                                        if ($vrslcmApplianceNtpConfig.ntpServers -match $ntpServer) {
                                            Write-Warning "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration, already performed: SKIPPED"
                                        } else {
                                            $addvRSLCMApplianceNtp = Add-vRSLCMApplianceNtpConfig -ntpServer $ntpServer -ErrorAction SilentlyContinue
                                            if ($addvRSLCMApplianceNtp.ntpServers -match $ntpServer) {
                                                Write-Output "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration: SUCCESSFUL"
                                            } else {
                                                Write-Error "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration: POST_VALIDATION_FAILED"
                                            }
                                        }
                                    } else {
                                        Write-Error "Adding NTP server ($ntpServer) to vRealize Suite Lifecycle Manager ($vmName) appliance NTP configuration: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to authenticate with vRealize Suite Lifecycle Manager ($vmName) appliance: PRE_VALIDATION_FAILED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRSLCMNtpServer

Function Set-vRSLCMDnsConfig {
    <#
        .SYNOPSIS
        Configure DNS Server and/or DNS search domains on vRealize Suite Lifecycle Manager appliance

        .DESCRIPTION
        The Set-vRSLCMDnsConfig cmdlet configures the DNS server and search domain details of the vRealize Suite
        Lifecycle Manager appliance using one or more DNS servers and/or DNS search domains passed as a parameter.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures the vRealize Suite Lifecycle Manager appliance DNS configuration

        .EXAMPLE
        Set-vRSLCMDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1! -dnsServers "172.16.11.4 172.16.11.5" -dnsSearchDomains rainpole.io
        This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4 and 172.16.11.5 as its DNS servers and rainpole.io as its search domain

        .EXAMPLE
        Set-vRSLCMDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1! -dnsServers "172.16.11.4 172.16.11.5 172.17.11.4 172.17.11.5" -dnsSearchDomains "rainpole.io sfo.rainpole.io lax.rainpole.io"
        This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4, 172.16.11.5, 172.17.11.4, and 172.17.11.5 as its DNS servers and rainpole.io, sfo.rainpole.io, and lax.rainpole.io as its DNS search domains
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsServers,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsSearchDomains
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) {
                                $vmName = $vrslcmDetails.fqdn.Split(".")[0]
                                if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                    if ($dnsServers) {
                                        $scriptCommand = "sed -i '/#DNS=/d' /etc/systemd/resolved.conf"
                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn
                                        $scriptCommand = "sed -i '/^DNS=/c\DNS=$dnsServers' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn
                                        $scriptCommand = "cat /etc/systemd/resolved.conf"
                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn
                                        if (($output.ScriptOutput).Contains("DNS=$dnsServers")) {
                                            Write-Output "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS Server(s) ($dnsServers): SUCCESSFUL"
                                        } else {
                                            Write-Error "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS Server(s) ($dnsServers): POST_VALIDATION_FAILED"
                                        }
                                    }
                                    if ($dnsSearchDomains) {
                                        if (($output.ScriptOutput).Contains("#Domains")) {
                                            $scriptCommand = "sed -i '/#Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                        } else {
                                            $scriptCommand = "sed -i '/^Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                        } 
                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn   
                                        $scriptCommand = "cat /etc/systemd/resolved.conf"
                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vrslcmDetails.rootPassword -Server $vcfVcenterDetails.fqdn
                                        if (($output.ScriptOutput).Contains("Domains=$dnsSearchDomains")) {
                                            Write-Output "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS search domain(s) ($dnsSearchDomains): SUCCESSFUL"
                                        } else {
                                            Write-Error "Configuring vRealize Suite Lifecycle Manager ($vmName) to use DNS search domain(s) ($dnsSearchDomains): POST_VALIDATION_FAILED"
                                        }
                                    }
                                } else {
                                    Write-Error "Unable to locate a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vRSLCMDnsConfig

Function Undo-vRSLCMNtpServer {
    <#
        .SYNOPSIS
        Set the NTP Server configuration of vRealize Suite Lifecycle Manager to match SDDC Manager

        .DESCRIPTION
        The Undo-vRSLCMNtpServer cmdlet sets the NTP Server details of the vRealize Suite Lifecycle Manager appliance
        back to what is stored in SDDC Manager. The cmdlet connects to SDDC Manager using the -server, -user, and
        -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Retrieves NTP server configuration from SDDC Manager
        - Configures the vRealize Suite Lifecycle Manager to use only the values stored in SDDC Manager
        
        .EXAMPLE
        Undo-vRSLCMNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use only the NTP servers found in SDDC Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    $sddcManagerNtpServers = Get-VCFConfigurationNTP | Select-Object -ExpandProperty ipAddress
                    if ($sddcManagerNtpServers.count -gt 1) {
                        $sddcManagerNtpServers = $sddcManagerNtpServers -join ","
                    }
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) {
                                $vmName = $vrslcmDetails.fqdn.Split(".")[0]
                                if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                    $evaluatevRSLCMApplianceNtpConfig = Get-vRSLCMApplianceNtpConfig | Select-Object -ExpandProperty ntpServers
                                    if ($evaluatevRSLCMApplianceNtpConfig -ne $sddcManagerNtpServers) {
                                        Set-vRSLCMApplianceNtpConfig -ntpServer $sddcManagerNtpServers -ErrorAction SilentlyContinue | Out-Null
                                        $validateApplianceNtpConfig = Get-vRSLCMApplianceNtpConfig | Select-Object -ExpandProperty ntpServers
                                        if ($validateApplianceNtpConfig -eq $sddcManagerNtpServers) {
                                            Write-Output "Restoring vRealize Suite Lifecycle Manager ($vmName) appliance NTP servers to SDDC Manager defaults: SUCCESSFUL"
                                        } else {
                                            Write-Error "Restoring vRealize Suite Lifecycle Manager ($vmName) appliance NTP servers to SDDC Manager defaults: POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Restoring vRealize Suite Lifecycle Manager ($vmName) appliance NTP servers to SDDC Manager defaults: SKIPPED"
                                    }
                                    $sddcManagerNtpServers = $null
                                    $currentProductNtpServers = Get-vRSLCMProductNtpServer | Select-Object -ExpandProperty hostName
                                    $sddcManagerNtpServers = Get-VCFConfigurationNTP | Select-Object -ExpandProperty ipAddress
                                    foreach ($currentProductNtpServer in $currentProductNtpServers) {
                                        if ($sddcManagerNtpServers -notContains $currentProductNtpServer) {
                                            Remove-vRSLCMProductNtpServer -ntpServer $currentProductNtpServer -ErrorAction SilentlyContinue | Out-Null
                                            $removedvRSLCMProductNtpServer = 1
                                        }
                                    }
                                    if ($removedvRSLCMProductNtpServer -eq 1) {
                                        $validateProductNtpServers = Get-vRSLCMProductNtpServer | Select-Object -ExpandProperty hostName
                                        $validateProductNtpServerSuccess = 1
                                        foreach ($validateProductNtpServer in $validateProductNtpServers) {
                                            if ($sddcManagerNtpServers -notContains $validateProductNtpServer) {
                                                $validateProductNtpServerSuccess = 0
                                                Write-Error "Restoring vRealize Suite Lifecycle Manager ($vmName) product NTP servers to SDDC Manager defaults: POST_VALIDATION_FAILED"
                                            }
                                        }
                                        if ($validateProductNtpServerSuccess -eq 1) {
                                            Write-Output "Restoring vRealize Suite Lifecycle Manager ($vmName) product NTP servers to SDDC Manager defaults: SUCCESSFUL"
                                        }
                                    } else {
                                        Write-Warning "Restoring vRealize Suite Lifecycle Manager ($vmName) product NTP servers to SDDC Manager defaults: SKIPPED"
                                    }
                                } else {
                                    Write-Error "Unable to authenticate with vRealize Suite Lifecycle Manager ($vmName) appliance: PRE_VALIDATION_FAILED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRSLCMNtpServer

Function Undo-vRSLCMDnsConfig {
    <#
        .SYNOPSIS
        Sets the DNS Server and/or DNS search domains on vRealize Suite Lifecycle Manager to match SDDC Manager

        .DESCRIPTION
        The Undo-vRSLCMDnsConfig cmdlet configures the DNS server and search domain details of the vRealize Suite
        Lifecycle Manager appliance to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager using
        the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Retrieves the DNS server and search domain values from SDDC Manager
        - Configures the vRealize Suite Lifecycle Manager appliance DNS configuration to match the values retrieved from SDDC Manager

        .EXAMPLE
        Undo-vRSLCMDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example configures the vRealize Suite Lifecycle Manager appliance managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use values for DNS servers and search domains to the values stored in SDDC Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                $sddcManagerInstance = Get-VCFManager
                $sddcManagerVmName = $sddcManagerInstance.fqdn.Split(".")[0]
                $sddcManagerDnsServers = Get-VCFConfigurationDNS | Select-Object -ExpandProperty ipAddress
                if ($sddcManagerDnsServers.Count -gt 1) {
                    $sddcManagerDnsServers = $sddcManagerDnsServers -Join " "
                }
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) {
                                $vmName = $vrslcmDetails.fqdn.Split(".")[0]
                                if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                    Try {
                                        $sddcManagerSearchDomains = Get-VCFDnsSearchDomain -sddcManagerVmName $sddcManagerVmName -sddcManagerRootPass $sddcManagerRootPass -ErrorAction Stop
                                    } Catch [System.Security.Authentication.InvalidCredentialException]{
                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                    }                                
                                    if (!$sddcManagerDnsServers -or !$sddcManagerSearchDomains) {
                                        Write-Error "Unable to undo DNS configuration on vRealize Suite Lifecycle Manager ($vmName) appliance: PRE_VALIDATION_FAILED"
                                    } else {
                                        Try {
                                            Set-vRSLCMDnsConfig -server $server -user $user -pass $pass -dnsServers $sddcManagerDnsServers -dnsSearchDomains $sddcManagerSearchDomains
                                        } Catch {
                                            Write-Error "Unable to undo DNS configuration on vRealize Suite Lifecycle Manager ($vmName) appliance: POST_VALIDATION_FAILED"
                                        }
                                    }
                                }
                            } else {
                                Write-Error "Unable to locate a virtual machine named ($sddcManagerVmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRSLCMDnsConfig

Function Set-WorkspaceOneDnsConfig {
    <#
        .SYNOPSIS
        Sets the DNS server and/or DNS search domains for all Workspace ONE Access appliances

        .DESCRIPTION
        The Set-WorkspaceOneDnsConfig cmdlet configures the DNS server and search domain details of all Workspace ONE
        Access appliances to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager using the -server,
        -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures the DNS configuration for all Workspace ONE Access appliances

        .EXAMPLE
        Set-WorkspaceOneDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -dnsServers "172.16.11.4 172.16.11.5" -dnsSearchDomains "rainpole.io sfo.rainpole.io lax.rainpole.io"
        This example configures all Workspace ONE Access appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4 amd 172.16.11.5 as its DNS servers and rainpole.io, sfo.rainpole.io, and lax.rainpole.io as its DNS search domains
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsServers,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsSearchDomains
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                                Try {
                                    $newRequest = Stop-vRSLCMProductNode -environment globalenvironment -product vidm -ErrorAction Stop
                                } Catch {
                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                }
                                if ($newRequest) {
                                    Write-Output "Powering off Workspace ONE Access appliances. This may take quite a while."
                                    Start-Sleep 10
                                    Watch-vRSLCMRequest -vmid $($newRequest.requestId) | Out-Null
                                } else {
                                    Write-Error "Power off request of Workspace ONE Access failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED"
                                } 
                                $productVMs = Get-vRSLCMProductNode -environmentName globalenvironment -product vidm              
                                foreach ($productVM in $productVMs) {
                                    if ((Get-VM -Name $productVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                        if ($dnsServers) {
                                            $existingDNS = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "DNS"} | Select-Object -ExpandProperty Value
                                            if ($existingDNS -eq $dnsServers) {
                                                Write-Warning "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS Server(s) ($dnsServers) already done: SKIPPED"
                                            } else {
                                                Set-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) -properties @{"DNS"="$dnsServers"} | Out-Null
                                            }
                                            $validateDNS = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "DNS"} | Select-Object -ExpandProperty Value
                                            if ($validateDNS -eq $dnsServers) {
                                                Write-Output "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS server(s) ($dnsServers): SUCCESSFUL"
                                            } else {
                                                Write-Error "Configuring Workspace ONE Access appliance $($ProductVM.vmName) to use DNS server(s) ($dnsServers): POST_VALIDATION_FAILED"
                                            }
                                        }
                                        if ($dnsSearchDomains) {
                                            $existingSearchDomains = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "searchpath"} | Select-Object -ExpandProperty Value
                                            if ($existingSearchDomains -eq $dnsSearchDomains) {
                                                Write-Warning "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS search domain(s) ($dnsSearchDomains) already done: SKIPPED"
                                            } else {
                                                Set-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) -properties @{"searchpath"="$dnsSearchDomains"} | Out-Null
                                            }
                                            $validateSearchDomains = Get-VMOvfProperty -vm (Get-VM -Name $productVM.vmName) | Where-Object {$_.Id -eq "searchpath"} | Select-Object -ExpandProperty Value
                                            if ($validateSearchDomains -eq $dnsSearchDomains) {
                                                Write-Output "Configuring Workspace ONE Access appliance $($productVM.vmName) to use DNS search domain(s) ($dnsSearchDomains): SUCCESSFUL"
                                            } else {
                                                Write-Error "Configuring Workspace ONE Access appliance $($ProductVM.vmName) to use DNS search domain(s) ($dnsSearchDomains): POST_VALIDATION_FAILED"
                                            }
                                        }
                                    } else {
                                        Write-Error "Unable to locate a virtual machine named $($productVM.vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                    }
                                }
                                $newRequest = Start-vRSLCMProductNode -environment globalenvironment -product vidm
                                if ($newRequest) {
                                    Write-Output "Powering on Workspace ONE Access appliances and bringing up services. This may take quite a while."
                                    Start-Sleep 10
                                    Watch-vRSLCMRequest -vmid $($newRequest.requestId) | Out-Null                                    
                                } else {
                                    Write-Error "Power on request of Workspace ONE Access appliance(s) failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-WorkspaceOneDnsConfig

Function Undo-WorkspaceOneDnsConfig {
    <#
        .SYNOPSIS
        Sets the DNS Server and/or DNS search domains on Workspace ONE Access to match SDDC Manager

        .DESCRIPTION
        The Undo-WorkspaceOneDnsConfig cmdlet configures the DNS server and search domain details of all Workspace
        ONE Access appliances to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Retrieves the DNS server and search domain values from SDDC Manager
        - Configures all Workspace ONE appliance DNS configuration to match the values retrieved from SDDC Manager

        .EXAMPLE
        Undo-WorkspaceOneDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcManagerRootPass VMw@re1!
        This example configures all Workspace ONE Access appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use values for DNS servers and search domains to the values stored in SDDC Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                $sddcManagerInstance = Get-VCFManager
                $sddcManagerVmName = $sddcManagerInstance.fqdn.Split(".")[0]
                $sddcManagerDnsServers = Get-VCFConfigurationDNS | Select-Object -ExpandProperty ipAddress
                if ($sddcManagerDnsServers.Count -gt 1) {
                    $sddcManagerDnsServers = $sddcManagerDnsServers -Join ","
                }
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) {
                                if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                    Try {
                                        $sddcManagerSearchDomains = Get-VCFDnsSearchDomain -sddcManagerVmName $sddcManagerVmName -sddcManagerRootPass $sddcManagerRootPass -ErrorAction Stop
                                    } Catch [System.Security.Authentication.InvalidCredentialException]{
                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                    }                                
                                    if (!$sddcManagerDnsServers -or !$sddcManagerSearchDomains) {
                                        Write-Error "Unable to undo DNS configuration on Workspace ONE Access ($vmName) appliance: PRE_VALIDATION_FAILED"
                                    } else {
                                        Try {
                                            Set-WorkspaceOneDnsConfig -server $server -user $user -pass $pass -dnsServers $sddcManagerDnsServers -dnsSearchDomains $sddcManagerSearchDomains -ErrorAction Stop -WarningAction SilentlyContinue
                                        } Catch {
                                            Write-Error $_.Exception.Message
                                        }
                                    }
                                }
                            } else {
                                Write-Error "Unable to locate a virtual machine named ($sddcManagerVmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-WorkspaceOneDnsConfig

Function Set-vROPSDnsConfig {
    <#
        .SYNOPSIS
        Configure DNS Server and/or DNS search domains on vRealize Operations Manager appliance

        .DESCRIPTION
        The Set-vROPSDnsConfig cmdlet configures the DNS server and search domain details of all vRealize Operations
        Manager analytics cluster appliances to the values passed as parameters. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures all vRealize Operations Manager analytics cluster appliance DNS configuration to the values
        passed to the function using -dnsServers and -dnsSearchDomains.

        .EXAMPLE
        Set-vROPSDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName xint-env -dnsServers "172.16.11.4 172.16.11.5" -dnsSearchDomains rainpole.io
        This example configures the vRealize Operations Manager analytics cluster appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4 and 172.16.11.5 as its DNS servers and rainpole.io as its search domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsServers,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsSearchDomains
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                $vropsVMs = (Get-VCFvROPs).nodes.fqdn
                                Try {
                                    $productVMs = Get-vRSLCMProductNode -environmentName $environmentName -product vrops -ErrorAction Stop
                                } Catch [System.Net.WebException] {
                                    $PSCmdlet.ThrowTerminatingError(
                                        [System.Management.Automation.ErrorRecord]::new(
                                            ([System.Management.Automation.GetValueException]"Retrieving vRealize Operations Manager appliance information from vRealize Suite Lifecycle Manager: PRE_VALIDATION_FAILED"),
                                            'Get-vRSLCMProductNode',
                                            [System.Management.Automation.ErrorCategory]::ReadError,
                                            ""
                                        )
                                    )
                                }
                                $vropsXregVMs = @()
                                foreach ($productVM in $productVMs) {
                                    if ($vropsVMs -contains $productVM.hostName) {
                                        $vropsXregVMs += $productVM
                                    }
                                }
                                foreach ($vropsXregVM in $vropsXregVMs){
                                    $vropsRootPass = (Get-VCFCredential | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VROPS" -and $_.resource.resourceName -eq $vropsXregVM.hostName}).password
                                    if ((Get-VM -Name $vropsXregVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                        if ($dnsServers) {
                                            $scriptCommand = "sed -i '/#DNS=/d' /etc/systemd/resolved.conf"
                                            $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                            $scriptCommand = "sed -i '/^DNS=/c\DNS=$dnsServers' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                            $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                            $scriptCommand = "cat /etc/systemd/resolved.conf"
                                            $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                            if (($output.ScriptOutput).Contains("DNS=$dnsServers")) {
                                                Write-Output "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS Server(s) ($dnsServers): SUCCESSFUL"
                                            } else {
                                                Write-Error "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS Server(s) ($dnsServers): POST_VALIDATION_FAILED"
                                            }
                                        }
                                        if ($dnsSearchDomains) {
                                            $scriptCommand = "cat /etc/systemd/network/10-eth0.network"
                                            $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                            if (($output.ScriptOutput).Contains("Domains=")) {
                                                $scriptCommand = "sed -i '/^Domains=/d' /etc/systemd/network/10-eth0.network | systemctl restart systemd-networkd"
                                                $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                            } 
                                            $scriptCommand = "cat /etc/systemd/resolved.conf"
                                            $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                            if (($output.ScriptOutput).Contains("#Domains")) {
                                                $scriptCommand = "sed -i '/#Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                            } else {
                                                $scriptCommand = "sed -i '/^Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                            } 
                                            $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn   
                                            $scriptCommand = "cat /etc/systemd/resolved.conf"
                                            $output = Invoke-VMScript -VM $vropsXregVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                            if (($output.ScriptOutput).Contains("Domains=$dnsSearchDomains")) {
                                                Write-Output "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS search domain(s) ($dnsSearchDomains): SUCCESSFUL"
                                            } else {
                                                Write-Error "Configuring vRealize Operations Manager appliance ($($vropsXregVM.vmName)) to use DNS search domain(s) ($dnsSearchDomains): POST_VALIDATION_FAILED"
                                            }
                                        }
                                    } else {
                                        Write-Error "Unable to locate a virtual machine named ($($vropsXregVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                    }
                                } 
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }  
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vROPSDnsConfig

Function Undo-vROPSDnsConfig {
    <#
        .SYNOPSIS
        Sets the DNS Server and/or DNS search domains on vRealize Operations Manager appliances to match SDDC Manager

        .DESCRIPTION
        The Undo-vROPSDnsConfig cmdlet configures the DNS server and search domain details of vRealize Operations
        Manager analytics cluster appliances to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Retrieves the DNS server and search domain values from SDDC Manager
        - Configures vRealize Operations Manager analytics cluster appliance DNS configuration to match the values
        retrieved from SDDC Manager

        .EXAMPLE
        Undo-vROPSDnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcManagerRootPass VMw@re1! -environmentName xint-env
        This example configures all vRealize Operations Manager analytics cluster appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use values for DNS servers and search domains to the values stored in SDDC Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                $sddcManagerInstance = Get-VCFManager
                $sddcManagerVmName = $sddcManagerInstance.fqdn.Split(".")[0]
                $sddcManagerDnsServers = Get-VCFConfigurationDNS | Select-Object -ExpandProperty ipAddress
                if ($sddcManagerDnsServers.Count -gt 1) {
                    $sddcManagerDnsServers = $sddcManagerDnsServers -Join " "
                }
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass
                            if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) {
                                if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                    $vcfvROPSDetails = Get-VCFvROPS
                                    if (Test-vROPSConnection -server $vcfVROPSDetails.loadBalancerFqdn) {
                                        Try {
                                            $sddcManagerSearchDomains = Get-VCFDnsSearchDomain -sddcManagerVmName $sddcManagerVmName -sddcManagerRootPass $sddcManagerRootPass -ErrorAction Stop 
                                        } Catch [System.Security.Authentication.InvalidCredentialException]{
                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                        }                                
                                        if (!$sddcManagerDnsServers -or !$sddcManagerSearchDomains) {
                                            Write-Error "Unable to undo DNS configuration for vRealize Operations Manager analytics cluster appliances: PRE_VALIDATION_FAILED"
                                        } else {
                                            Try {
                                                Set-vROPSDnsConfig -server $server -user $user -pass $pass -environmentName $environmentName -dnsServers $sddcManagerDnsServers -dnsSearchDomains $sddcManagerSearchDomains -ErrorAction Stop -WarningAction SilentlyContinue
                                            } Catch {
                                                Write-Error $_.Exception.Message
                                            }
                                        }                                    
                                    } else {
                                        Write-Error "Unable connect to vRealize Operations Manager: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to authenticate with vRealize Suite Lifecycle Manager to retrieve vRealize Operations Manager analytics cluster appliances: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to connect to vRealize Suite Lifecycle Manager ($($vrslcmDetails.fqdn.Split(".")[0])): PRE_VALIDATION_FAILED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        } else {
                            Write-Error "Unable to locate a virtual machine named ($sddcManagerVmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vROPSDnsConfig

Function Add-vROPSNtpServer {
    <#
        .SYNOPSIS
        Adds an NTP server to all vRealize Operations Manager appliances

        .DESCRIPTION
        The Add-vROPSNtpServer cmdlet adds an NTP server to all vRealize Operations Manager appliances. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures all vRealize Operations Manager appliances to use an additional NTP server defined using the value
        passed to the function using -ntpServer.

        .EXAMPLE
        Add-vROPSNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName xint-env -ntpServer ntp.lax.rainpole.io
        This example configures the vRealize Operations Manager appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to add the NTP server ntp.lax.rainpole.io.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer
    )

    $testNtp = Test-NtpServer -Server $ntpServer
    if ($testNtp -eq $false) {
        Write-Error "Unable to confirm NTP server $ntpServer is valid: PRE_VALIDATION_FAILED"
        break
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                Try {
                                    $productVM = (Get-vRSLCMProductNode -environmentName $environmentName -product vrops -ErrorAction Stop)[0]
                                } Catch [System.Net.WebException] {
                                    $PSCmdlet.ThrowTerminatingError(
                                        [System.Management.Automation.ErrorRecord]::new(
                                            ([System.Management.Automation.GetValueException]"Retrieving vRealize Operations Manager appliance information from vRealize Suite Lifecycle Manager: PRE_VALIDATION_FAILED"),
                                            'Get-vRSLCMProductNode',
                                            [System.Management.Automation.ErrorCategory]::ReadError,
                                            ""
                                        )
                                    )
                                }
                                $vropsRootPass = (Get-VCFCredential | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VROPS" -and $_.resource.resourceName -eq $productVM.hostName}).password
                                if ((Get-VM -Name $productVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                    $scriptCommand = "python /usr/lib/vmware-casa/bin/ntp_list.py"
                                    $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                    $existingNtpServers = ($output.ScriptOutput | ConvertFrom-JSON).time_servers
                                    $ntpServers = @()
                                    foreach ($existingNtpServer in $existingNtpServers) {
                                        $ntpServers += $existingNtpServer.address
                                    }
                                    $ntpServers += $ntpServer
                                    $ntpServersJson = $ntpServers | ConvertTo-JSON
                                    $ntpServersJson = $ntpServersJson -replace "`r`n","" -replace " ",""
                                    $scriptCommand = "echo '$ntpServersJson' | python /usr/lib/vmware-casa/bin/ntp_update.py > /dev/null 2>&1"
                                    $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                    $scriptCommand = "python /usr/lib/vmware-casa/bin/ntp_list.py"
                                    $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                    $vropsNtpServers = ($output.ScriptOutput | ConvertFrom-JSON).time_servers
                                    $vropsNtpServerArray = @()
                                    foreach ($vropsNtpServer in $vropsNtpServers) {
                                        $vropsNtpServerArray += $vropsNtpServer.address
                                    }
                                    $compareArrays = Compare-Object -ReferenceObject $ntpServers -DifferenceObject $vropsNtpServerArray
                                    if (!$compareArrays) {
                                        Write-Output "Configuring vRealize Operations Manager appliances to use NTP servers ($($ntpServers -Join ", ")): SUCCESSFUL"
                                    } else {
                                        Write-Output "Unable to validate vRealize Operations Manager appliances were configured to use NTP servers ($($ntpServers -Join ", ")): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to locate a virtual machine named ($($productVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                } 
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }  
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSNtpServer

Function Undo-vROPSNtpServer {
    <#
        .SYNOPSIS
        Configure NTP settings for all vRealize Operations Manager appliances to match SDDC Manager

        .DESCRIPTION
        The Undo-vROPSNtpServer cmdlet removes any added NTP server(s) to all vRealize Operations Manager appliances by
        returning their configuration to match that of SDDC Manager. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures all vRealize Operations Manager appliances to the use NTP server(s) defined in SDDC Manager.

        .EXAMPLE
        Undo-vROPSNtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName xint-env
        This example configures the vRealize Operations Manager appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use the NTP server(s) defined in SDDC Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                            if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                Try {
                                    $productVM = (Get-vRSLCMProductNode -environmentName $environmentName -product vrops -ErrorAction Stop)[0] 
                                } Catch [System.Net.WebException] {
                                    $PSCmdlet.ThrowTerminatingError(
                                        [System.Management.Automation.ErrorRecord]::new(
                                            ([System.Management.Automation.GetValueException]"Retrieving vRealize Operations Manager appliance information from vRealize Suite Lifecycle Manager: PRE_VALIDATION_FAILED"),
                                            'Get-vRSLCMProductNode',
                                            [System.Management.Automation.ErrorCategory]::ReadError,
                                            ""
                                        )
                                    )
                                }
                                $vropsRootPass = (Get-VCFCredential | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VROPS" -and $_.resource.resourceName -eq $productVM.hostName}).password
                                if ((Get-VM -Name $productVM.vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                    $ntpServers = (Get-VCFConfigurationNTP).ipAddress
                                    if ($ntpServers.count -eq 1) {
                                        $ntpServersJson = $ntpServers | ConvertTo-JSON
                                        $ntpServersJson = "[$ntpServersJson]" 
                                    } else {
                                        $ntpServersJson = $ntpServers | ConvertTo-JSON
                                        $ntpServersJson = $ntpServersJson -replace "`r`n","" -replace " ",""
                                    }
                                    $scriptCommand = "echo '$ntpServersJson' | python /usr/lib/vmware-casa/bin/ntp_update.py > /dev/null 2>&1"
                                    $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                    $scriptCommand = "python /usr/lib/vmware-casa/bin/ntp_list.py"
                                    $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vropsRootPass -Server $vcfVcenterDetails.fqdn
                                    $vropsNtpServers = ($output.ScriptOutput | ConvertFrom-JSON).time_servers
                                    $vropsNtpServerArray = @()
                                    foreach ($vropsNtpServer in $vropsNtpServers) {
                                        $vropsNtpServerArray += $vropsNtpServer.address
                                    }
                                    $compareArrays = Compare-Object -ReferenceObject $ntpServers -DifferenceObject $vropsNtpServerArray
                                    if (!$compareArrays) {
                                        Write-Output "Configuring vRealize Operations Manager appliances to use NTP servers ($($ntpServers -Join ", ")): SUCCESSFUL"
                                    } else {
                                        Write-Output "Unable to validate vRealize Operations Manager appliances were configured to use NTP servers ($($ntpServers -Join ", ")): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to locate a virtual machine named ($($productVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                } 
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }  
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vROPSNtpServer

Function Set-vRADnsConfig {
    <#
        .SYNOPSIS
        Configure DNS Server and/or DNS search domains on vRealize Automation appliances

        .DESCRIPTION
        The Set-vRADnsConfig cmdlet configures the DNS server and search domain details of all vRealize Automation
        appliances to the values passed as parameters. The cmdlet connects to SDDC Manager using the -server, -user,
        and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures all vRealize Automation appliance DNS configuration to the values passed to the function using
        -dnsServers and -dnsSearchDomains.

        .EXAMPLE
        Set-vRADnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -environmentName xint-env -dnsServers "172.16.11.4 172.17.11.4" -dnsSearchDomains rainpole.io
        This example configures the vRealize Automation appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use 172.16.11.4 and 172.17.11.4 as its DNS servers and rainpole.io as its search domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsServers,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$dnsSearchDomains
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                        if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                            if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                                if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                                        if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                            Try {
                                                $productVMs = Get-vRSLCMProductNode -environmentName $environmentName -product vra -ErrorAction Stop
                                            } Catch [System.Net.WebException] {
                                                $PSCmdlet.ThrowTerminatingError(
                                                    [System.Management.Automation.ErrorRecord]::new(
                                                        ([System.Management.Automation.GetValueException]"Retrieving vRealize Automation appliance information from vRealize Suite Lifecycle Manager: PRE_VALIDATION_FAILED"),
                                                        'Get-vRSLCMProductNode',
                                                        [System.Management.Automation.ErrorCategory]::ReadError,
                                                        ""
                                                    )
                                                )
                                            }
                                            $vraRootPass = (Get-VCFCredential -ErrorAction Stop | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VRA" -and $_.resource.resourceName -match $productVMs[0].hostName}).password
                                            if ((Get-VM -Name $productVMs[0].vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                                if ($dnsServers) {
                                                    $scriptCommand = "cat /etc/resolv.conf"
                                                    $output = Invoke-VMScript -VM $productVMs[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn                                            
                                                    [Array]$dnsServersArray = $dnsServers.Split(" ")
                                                    $alreadyConfigured = @()
                                                    Foreach ($dnsServer in $dnsServersArray) {
                                                        if ($output.ScriptOutput -Match $dnsServer) {
                                                            $alreadyConfigured += $dnsServer
                                                        }
                                                    }                               
                                                    $compareArrays = Compare-Object -ReferenceObject $dnsServersArray -DifferenceObject $alreadyConfigured
                                                    if (!$compareArrays) {
                                                        Write-Warning "Configuring vRealize Automation appliances to use DNS Server(s) ($dnsServers) already done: SKIPPED"
                                                    } else {
                                                        $dnsServers = $dnsServers.Split(" ") -Join(",")
                                                        $scriptCommand = "vracli network dns set --servers $dnsServers"
                                                        $output = Invoke-VMScript -VM $productVMs[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                        $scriptCommand = "vracli network dns status"
                                                        $output = Invoke-VMScript -VM $productVMs[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                        [Array]$checkDns = $output.ScriptOutput
                                                        foreach ($item in $checkDns) {
                                                            $alreadyConfigured = @()
                                                            foreach ($dnsServer in $dnsServersArray) {
                                                                if ($item -Match $dnsServer) {
                                                                    $alreadyConfigured += $dnsServer
                                                                }
                                                            }
                                                        }
                                                        $compareArrays = Compare-Object -ReferenceObject $dnsServersArray -DifferenceObject $alreadyConfigured        
                                                        if ($compareArrays){
                                                            Write-Error "Unable to validate vRealize Automation appliances using DNS Server(s) ($dnsServers): POST_VALIDATION_FAILED"
                                                            Break
                                                        } else {
                                                            $dnsServersVracliValidated = $true
                                                            $scriptCommand = "cat /etc/resolv.conf"
                                                            $output = Invoke-VMScript -VM $productVMs[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn                                            
                                                            [Array]$dnsServersArray = $dnsServers.Split(",")
                                                            $alreadyConfigured = @()
                                                            Foreach ($dnsServer in $dnsServersArray) {
                                                                if ($output.ScriptOutput -Match $dnsServer) {
                                                                    $alreadyConfigured += $dnsServer
                                                                }
                                                            }                               
                                                            $compareArrays = Compare-Object -ReferenceObject $dnsServersArray -DifferenceObject $alreadyConfigured
                                                            if ($compareArrays) {
                                                                Write-Error "Configuring vRealize Automation appliances to use DNS Server(s) ($dnsServers): POST_VALIDATION_FAILED"
                                                                Break
                                                            } else {
                                                                $dnsServersResolvConfValidated = $true
                                                                Write-Output "Configuring vRealize Automation appliances to use DNS Server(s) ($dnsServers): SUCCESSFUL"
                                                            }
                                                        } 
                                                    }
                                                }
                                                if ($dnsSearchDomains) {
                                                    Foreach ($productVM in $productVMs) {
                                                        $scriptCommand = "cat /etc/resolv.conf"
                                                        $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                        if (($output.ScriptOutput).Contains("search $dnsSearchDomains")) {
                                                            Write-Warning "Configuring vRealize Automation appliance ($($productVM.vmName)) to use DNS search domain(s) ($dnsSearchDomains) already done: SKIPPED" 
                                                        } else {
                                                            $scriptCommand = "cat /etc/systemd/resolved.conf"
                                                            $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                            if (($output.ScriptOutput).Contains("#Domains")) {
                                                                $scriptCommand = "sed -i '/#Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                                            } else {
                                                                $scriptCommand = "sed -i '/^Domains=/c\Domains=$dnsSearchDomains' /etc/systemd/resolved.conf | systemctl restart systemd-resolved"
                                                            } 
                                                            $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn   
                                                            $scriptCommand = "cat /etc/resolv.conf"
                                                            $output = Invoke-VMScript -VM $productVM.vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                            if (($output.ScriptOutput).Contains("search $dnsSearchDomains")) {
                                                                $dnsSearchDomainsResolvConfValidated = $true
                                                                Write-Output "Configuring vRealize Automation appliance ($($productVM.vmName)) to use DNS search domain(s) ($dnsSearchDomains): SUCCESSFUL" 
                                                            } else {
                                                                Write-Error "Configuring vRealize Automation appliance ($($productVM.vmName)) to use DNS search domain(s) ($dnsSearchDomains): POST_VALIDATION_FAILED"
                                                            }
                                                        }
                                                    }
                                                }
                                                if (($dnsServers -and $dnsServersVracliValidated -eq $true -and $dnsServersResolvConfValidated -eq $true) -or ($dnsSearchDomains -and $dnsSearchDomainsResolvConfValidated -eq $true)) {
                                                    Write-Output "Restarting vRealize Automation appliances and starting services upon bootup. This can take quite a while."
                                                    $scriptCommand = "/opt/scripts/svc-stop.sh"
                                                    $output = Invoke-VMScript -VM $productVM[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                    $scriptCommand = "/opt/scripts/deploy.sh --shutdown"
                                                    $output = Invoke-VMScript -VM $productVM[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                    Foreach ($productVM in $productVMs) {
                                                        Get-VM -Name $productVM.vmName | Restart-VMGuest | Out-Null
                                                    }
                                                    Start-Sleep -Seconds 15
                                                    Foreach ($productVM in $productVMs) {
                                                        Do {
                                                            $toolsStatus = (Get-VM -Name $productVM.vmName -ErrorAction SilentlyContinue).ExtensionData.Guest.ToolsRunningStatus
                                                            if ($toolsStatus -ne "guestToolsRunning") {
                                                                Start-Sleep -Seconds 15
                                                            }
                                                        }
                                                        Until ($toolsStatus -eq "guestToolsRunning")
                                                    }
                                                    Foreach ($productVM in $productVMs) {
                                                        Do {
                                                            $testvRA = Test-vRAConnection -server $productVM.hostname
                                                            if ($testvRA -eq $false) {
                                                                Start-Sleep -Seconds 15
                                                            }
                                                        }
                                                        Until ($testvRA -eq $true)
                                                    }
                                                    $scriptCommand = "ln -s /opt/vmware/bin/vamicli /usr/sbin/vamicli | /opt/scripts/deploy.sh"
                                                    $output = Invoke-VMScript -VM $productVM[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                    Do {
                                                        $checkVraAuth = Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass -ErrorAction SilentlyContinue
                                                        if ($checkVraAuth -eq $false) {
                                                            Start-Sleep -Seconds 60
                                                        }
                                                    }
                                                    Until ($checkVraAuth -eq $true)
                                                    $scriptCommand = "unlink /usr/sbin/vamicli"
                                                    $output = Invoke-VMScript -VM $productVM[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn

                                                }
                                            } else {
                                                Write-Error "Unable to locate a virtual machine named ($($productVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                            } 
                                        }
                                    }  
                                    Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vRADnsConfig

Function Undo-vRADnsConfig {
    <#
        .SYNOPSIS
        Sets the DNS Server and/or DNS search domains on vRealize Automation appliances to match SDDC Manager

        .DESCRIPTION
        The Undo-vROPSDnsConfig cmdlet configures the DNS server and search domain details of vRealize Automation
        appliances to the values stored in SDDC Manager. The cmdlet connects to SDDC Manager using the -server,
        -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Retrieves the DNS server and search domain values from SDDC Manager
        - Configures vRealize Automation appliance DNS configuration to match the values retrieved from SDDC Manager

        .EXAMPLE
        Undo-vRADnsConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcManagerRootPass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -environmentName xint-env
        This example configures all vRealize Automation appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use values for DNS servers and search domains to the values stored in SDDC Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                $sddcManagerInstance = Get-VCFManager
                $sddcManagerVmName = $sddcManagerInstance.fqdn.Split(".")[0]
                $sddcManagerDnsServers = Get-VCFConfigurationDNS | Select-Object -ExpandProperty ipAddress
                if ($sddcManagerDnsServers.Count -gt 1) {
                    $sddcManagerDnsServers = $sddcManagerDnsServers -Join " "
                }
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass) {
                                if ($vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass) {
                                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                                        if (Test-vRSLCMConnection -server $vrslcmDetails.fqdn) {
                                            if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                                if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                                                    Try {
                                                        $sddcManagerSearchDomains = Get-VCFDnsSearchDomain -sddcManagerVmName $sddcManagerVmName -sddcManagerRootPass $sddcManagerRootPass -ErrorAction Stop                               
                                                    } Catch [System.Security.Authentication.InvalidCredentialException]{
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                    if (!$sddcManagerDnsServers -or !$sddcManagerSearchDomains) {
                                                        Write-Error "Unable to undo DNS configuration for vRealize Automation appliances: PRE_VALIDATION_FAILED"
                                                    } else {
                                                        Set-vRADnsConfig -server $server -user $user -pass $pass -vraUser $vraUser -vraPass $vraPass -environmentName $environmentName -dnsServers $sddcManagerDnsServers -dnsSearchDomains $sddcManagerSearchDomains -ErrorAction Stop
                                                    }                                    
                                                } else {
                                                    Write-Error "Unable connect to vRealize Automation appliances: PRE_VALIDATION_FAILED"
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        } else {
                            Write-Error "Unable to locate a virtual machine named ($sddcManagerVmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRADnsConfig

Function Set-vRANtpConfig {
    <#
        .SYNOPSIS
        Configure NTP servers on vRealize Automation appliances

        .DESCRIPTION
        The Set-vRANtpConfig cmdlet configures the NTP server details of all vRealize Automation appliances to the
        values passed as parameters. The cmdlet connects to SDDC Manager using the -server, -user, and -password
        values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures all vRealize Automation appliance NTP configuration to the values passed to the function using
        -ntpServers.

        .EXAMPLE
        Set-vRANtpConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -environmentName xint-env -ntpServers "ntp.sfo.rainpole.io ntp.lax.rainpole.io"
        This example configures the vRealize Automation appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use ntp.sfo.rainpole.io and ntp.lax.rainpole.io as their NTP servers
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServers
    )

    [Array]$ntpServersArray = $ntpServers.Split(" ")
    foreach ($ntpServer in $ntpServersArray) {
        $testNtp = Test-NtpServer -Server $ntpServer
        if ($testNtp -eq $false) {
            $PSCmdlet.ThrowTerminatingError(
                [System.Management.Automation.ErrorRecord]::new(
                    ([System.Management.Automation.GetValueException]"Unable to confirm NTP server $ntpServer is valid: PRE_VALIDATION_FAILED"),
                    'Test-NtpServer',
                    [System.Management.Automation.ErrorCategory]::InvalidArgument,
                    ""
                )
            )
        }
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                        if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                            if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                                if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        $vrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop
                                        if (Test-vRSLCMAuthentication -server $vrslcmDetails.fqdn -user $vrslcmDetails.adminUser -pass $vrslcmDetails.adminPass) {
                                            Try {
                                                $productVMs = Get-vRSLCMProductNode -environmentName $environmentName -product vra -ErrorAction Stop
                                            } Catch [System.Net.WebException] {
                                                $PSCmdlet.ThrowTerminatingError(
                                                    [System.Management.Automation.ErrorRecord]::new(
                                                        ([System.Management.Automation.GetValueException]"Retrieving vRealize Automation appliance information from vRealize Suite Lifecycle Manager: PRE_VALIDATION_FAILED"),
                                                        'Get-vRSLCMProductNode',
                                                        [System.Management.Automation.ErrorCategory]::ReadError,
                                                        ""
                                                    )
                                                )
                                            }
                                            $vraRootPass = (Get-VCFCredential -ErrorAction Stop | Where-Object {$_.credentialType -eq "SSH" -and $_.resource.resourceType -eq "VRA" -and $_.resource.resourceName -match $productVMs[0].hostName}).password
                                            if ((Get-VM -Name $productVMs[0].vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                                $scriptCommand = "vracli ntp show-config"
                                                $output = Invoke-VMScript -VM $productVMs[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn                                            
                                                $outputComparison = (($output.ScriptOutput -Split "`n")[1]).Split("'") | Select-String -pattern "\w\.\w"
                                                if (!$outputComparison) {
                                                    $outputComparison = (($output.ScriptOutput -Split "`n")[1]).Split("'") | Select-String -pattern "\d{1,3}(\.\d{1,3}){3}"
                                                }
                                                $alreadyConfigured = @()
                                                Foreach ($ntpServer in $ntpServersArray) {
                                                    if ($outputComparison -Match $ntpServer) {
                                                        $alreadyConfigured += $ntpServer
                                                    }
                                                }
                                                if (($alreadyConfigured.Count -eq $outputComparison.Count) -and ($alreadyConfigured.Count -eq $ntpServersArray.Count) ) {
                                                    $compareArrays = Compare-Object -ReferenceObject $ntpServersArray -DifferenceObject $alreadyConfigured
                                                    if (!$compareArrays) {
                                                        Write-Warning "Configuring vRealize Automation appliances to use NTP Server(s) ($ntpServers) already done: SKIPPED"
                                                    } 
                                                } elseif ($compareArrays -or ($alreadyConfigured.Count -ne $outputComparison.Count) -or ($alreadyConfigured.Count -ne $ntpServersArray.Count)) {
                                                    if ($ntpServersArray.Count -gt 1){
                                                        [String]$ntpServersString = $null
                                                        Foreach ($ntpServer in $ntpServersArray) {
                                                            $ntpServersString = $ntpServersString+"'$($ntpServer)',"
                                                        }
                                                        $ntpServersString = $ntpServersString.Substring(0,$ntpServersString.Length-1)
                                                        $scriptCommand = "vracli ntp systemd --set $ntpServersString"
                                                    } else {
                                                        $scriptCommand = "vracli ntp systemd --set $ntpServers"
                                                    }
                                                    $output = Invoke-VMScript -VM $productVMs[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                    $scriptCommand = "vracli ntp show-config"
                                                    $output = Invoke-VMScript -VM $productVMs[0].vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vraRootPass -Server $vcfVcenterDetails.fqdn
                                                    [Array]$ntpServersArray = $ntpServers.Split(" ")
                                                    $outputComparison = (($output.ScriptOutput -Split "`n")[1]).Split("'") | Select-String -pattern "\w\.\w"
                                                    if (!$outputComparison) {
                                                        $outputComparison = (($output.ScriptOutput -Split "`n")[1]).Split("'") | Select-String -pattern "\d{1,3}(\.\d{1,3}){3}"
                                                    }                                                    
                                                    $alreadyConfigured = @()
                                                    Foreach ($ntpServer in $ntpServersArray) {
                                                        if ($outputComparison -Match $ntpServer) {
                                                            $alreadyConfigured += $ntpServer
                                                        }
                                                    }
                                                    if ($alreadyConfigured.Count -eq $outputComparison.Count) {
                                                        $compareArrays = Compare-Object -ReferenceObject $ntpServersArray -DifferenceObject $alreadyConfigured
                                                        if ($compareArrays) {
                                                            Write-Error "Unable to configure vRealize Automation appliances to use NTP Server(s) ($ntpServers): POST_VALIDATION_FAILED"
                                                        } else {
                                                            Write-Output "Configuring vRealize Automation appliances to use NTP Server(s) ($ntpServers): SUCCESSFUL"
                                                        }
                                                    }
                                                }
                                            } else {
                                                Write-Error "Unable to locate a virtual machine named ($($productVM.vmName)) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"
                                            } 
                                        }
                                    }  
                                    Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vRANtpConfig

Function Undo-vRANtpConfig {
    <#
        .SYNOPSIS
        Configure NTP settings for all vRealize Automation appliances to match SDDC Manager

        .DESCRIPTION
        The Undo-vRANtpServer cmdlet removes any added NTP server(s) on all vRealize Automation appliances by
        returning their configuration to match that of SDDC Manager. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Configures all vRealize Automation appliances to the use NTP server(s) defined in SDDC Manager.

        .EXAMPLE
        Undo-vRANtpServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -environmentName xint-env
        This example configures the vRealize Automation appliances managed by SDDC Manager sfo-vcf01.sfo.rainpole.io to use the NTP server(s) defined in SDDC Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                $ntpServers = (Get-VCFConfigurationNTP).ipAddress
                [String]$ntpServersString = $null
                if ($ntpServers.count -gt 1) {
                    Foreach ($ntpServer in $ntpServers) {
                        $ntpServersString = $ntpServersString + "$ntpServer "
                    }
                    $ntpServersString = $ntpServersString.Substring(0,$ntpServersString.Length-1)
                } else {
                    $ntpServersString = $ntpServers
                }
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            Try {
                                Set-vRANtpConfig -server $server -user $user -pass $pass -vraUser $vraUser -vraPass $vraPass -environmentName $environmentName -ntpServers $ntpServersString -ErrorAction Stop
                            } Catch {
                                $PSCmdlet.ThrowTerminatingError($PSItem)
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRANtpConfig

Function Add-SRMMapping {
    <#
        .SYNOPSIS
        Create a mapping between objects (folder, network, or compute resource) in the protected and failover VCF
        instances in Site Recovery Manager

        .DESCRIPTION
        The Add-SRMMapping cmdlet creates a mapping between objects (folder, network, or compute resource) in the
        protected and failover VCF instances in Site Recovery Manager. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Create a mapping between objects in the protected and failover VCF instances in Site Recovery Manager as
        defined by the -type, -protected, and -recovery parameters.

        .EXAMPLE
        Add-SRMMapping -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -type Folder -protected xint-m01-fd-vrslcm -recovery xint-m01-fd-vrslcm
        This example creates a mapping between protected site folder xint-m01-fd-vrslcm01 and recovery site folder xint-m01-fd-vrslcm01 in Site Recovery Manager.
        
        .EXAMPLE
        Add-SRMMapping -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -type Network -protected xint-m01-seg01 -recovery xint-m01-seg01
        This example creates a mapping between protected site network xint-m01-seg01 and recovery site network xint-m01-seg01 in Site Recovery Manager.
        
        .EXAMPLE
        Add-SRMMapping -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -type Resource -protected sfo-m01-cl01 -recovery lax-m01-cl01
        This example creates a mapping between protected site compute resource vSphere Cluster sfo-m01-cl01 and recovery site compute resource vSphere Cluster lax-m01-cl01 in Site Recovery Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateSet("Folder","Network","Resource")] [String]$type,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$protected,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$recovery
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $srmAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $srmBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                                $global:DefaultSrmServers = $null
                                                if ((Test-SRMConnection -server $srmAFqdn) -and (Test-SRMConnection -server $srmBFqdn)) {
                                                    if (Test-SRMAuthentication -server $srmAFqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass -remoteUser $siteBvCenterDetails.ssoAdmin -remotePass $siteBvCenterDetails.ssoAdminPass) {
                                                        $siteASrmServer = $global:DefaultSrmServers | Where-Object {$_.Name -match $srmAFqdn}
                                                        if ($type -eq "Folder") {
                                                            Try {
                                                                $protectedMoRef = (Get-Folder -Server $siteAvCenterDetails.fqdn -Name $protected -ErrorAction Stop | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}).id
                                                                $recoveryMoRef = (Get-Folder -Server $siteBvCenterDetails.fqdn -Name $recovery -ErrorAction Stop | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}).id
                                                                $existingSiteAMappings = $siteASrmServer.extensionData.InventoryMapping.GetFolderMappings()    
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Network") {
                                                            Try {
                                                                $protectedMoRef = (Get-VirtualNetwork -Server $siteAvCenterDetails.fqdn -Name $protected -ErrorAction Stop | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}).id
                                                                $recoveryMoRef = (Get-VirtualNetwork -Server $siteBvCenterDetails.fqdn -Name $recovery -ErrorAction Stop | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}).id  
                                                                $existingSiteAMappings = $siteASrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Resource") {
                                                            Try {
                                                                $protectedCluster = Get-Cluster -Server $SiteAvCenterDetails.fqdn -Name $protected -ErrorAction SilentlyContinue | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}
                                                                if ($protectedCluster) {
                                                                    $protectedMoRef = ($protectedCluster | Get-ResourcePool -Name "Resources").id
                                                                } else {
                                                                    $protectedMoRef = (Get-ResourcePool -Server $siteAvCenterDetails.fqdn -Name $protected -ErrorAction Stop | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}).id
                                                                }
                                                                $recoveryCluster = Get-Cluster -Server $SiteBvCenterDetails.fqdn -Name $recovery -ErrorAction SilentlyContinue | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}
                                                                if ($recoveryCluster) {
                                                                    $recoveryMoRef = ($recoveryCluster | Get-ResourcePool -Name "Resources").id
                                                                } else {
                                                                    $recoveryMoRef = (Get-ResourcePool -Server $siteBvCenterDetails.fqdn -Name $recovery -ErrorAction Stop | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}).id
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                            $existingSiteAMappings = $siteASrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()
                                                        }
                                                        if ($existingSiteAMappings) {
                                                            $forwardMappingExists = $null
                                                            foreach ($existingSiteAMapping in $existingSiteAMappings) {
                                                                if (($protectedMoRef -match $existingSiteAMapping.primaryObject.Value) -and ($recoveryMoRef -match $existingSiteAMapping.secondaryObject.Value)) {
                                                                    $forwardMappingExists = $true
                                                                }
                                                            }
                                                        }
                                                        if (!$forwardMappingExists) {
                                                            if ($type -eq "Folder") {
                                                                Try {
                                                                    $SiteASrmServer.extensionData.InventoryMapping.AddFolderMapping($protectedMoRef,$recoveryMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteAMappings = $SiteASrmServer.extensionData.InventoryMapping.GetFolderMappings()
                                                            } elseif ($type -eq "Network") {
                                                                Try {
                                                                    $SiteASrmServer.extensionData.InventoryMapping.AddNetworkMapping($protectedMoRef,$recoveryMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteAMappings = $SiteASrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } elseif ($type -eq "Resource") {
                                                                Try {
                                                                    $SiteASrmServer.extensionData.InventoryMapping.AddResourcePoolMapping($protectedMoRef,$recoveryMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteAMappings = $SiteASrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()
                                                            }
                                                            $forwardMappingValidated = $null
                                                            Foreach ($validateSiteAMapping in $validateSiteAMappings) {
                                                                if (($protectedMoRef -match $validateSiteAMapping.primaryObject.Value) -and ($recoveryMoRef -match $validateSiteAMapping.secondaryObject.Value)) {
                                                                    $forwardMappingValidated = $true
                                                                }
                                                            }
                                                            if ($forwardMappingValidated -eq $true) {
                                                                Write-Output "Create $type mapping between protected $type ($protected) and recovery $type ($recovery): SUCCESSFUL"
                                                            } else {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.GetValueException]"Create $type mapping between protected $type ($protected) and recovery $type ($recovery): POST_VALIDATION_FAILED"),
                                                                        'Add-SRMMapping',
                                                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                                        ""
                                                                    )
                                                                )
                                                            }
                                                        } else {
                                                            Write-Warning "$type mapping between protected $type ($protected) and recovery $type ($recovery) already exists: SKIPPING"
                                                        }
                                                        Disconnect-SrmServer -Server $srmAFqdn -Confirm:$False
                                                    }
                                                    if (Test-SRMAuthentication -server $srmBFqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass -remoteUser $siteAvCenterDetails.ssoAdmin -remotePass $siteAvCenterDetails.ssoAdminPass) {
                                                        $siteBSrmServer = $global:DefaultSrmServers | Where-Object {$_.Name -match $srmBFqdn}
                                                        if ($type -eq "Folder") {
                                                            Try {
                                                                $existingSiteBMappings = $siteBSrmServer.extensionData.InventoryMapping.GetFolderMappings()    
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Network") {
                                                            Try {
                                                                $existingSiteBMappings = $siteBSrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Resource") {
                                                            Try {
                                                                $existingSiteBMappings = $siteBSrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()   
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                        if ($existingSiteBMappings) {
                                                            $reverseMappingExists = $null
                                                            Foreach ($existingSiteBMapping in $existingSiteBMappings) {
                                                                if (($recoveryMoRef -match $existingSiteBMapping.primaryObject.Value) -and ($protectedMoRef -match $existingSiteBMapping.secondaryObject.Value)) {
                                                                    $reverseMappingExists = $true
                                                                }
                                                            }
                                                        }  
                                                        if (!$reverseMappingExists) {
                                                            if ($type -eq "Folder") {
                                                                Try {
                                                                    $SiteBSrmServer.extensionData.InventoryMapping.AddFolderMapping($recoveryMoRef,$protectedMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteBMappings = $SiteBSrmServer.extensionData.InventoryMapping.GetFolderMappings()
                                                            } elseif ($type -eq "Network") {
                                                                Try {
                                                                    $SiteBSrmServer.extensionData.InventoryMapping.AddNetworkMapping($recoveryMoRef,$protectedMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteBMappings = $SiteBSrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } elseif ($type -eq "Resource") {
                                                                Try {
                                                                    $SiteBSrmServer.extensionData.InventoryMapping.AddResourcePoolMapping($recoveryMoRef,$protectedMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteBMappings = $SiteBSrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()
                                                            }
                                                            $reverseMappingValidated = $null
                                                            Foreach ($validateSiteBMapping in $validateSiteBMappings) {
                                                                if (($recoveryMoRef -match $validateSiteBMapping.primaryObject.Value) -and ($protectedMoRef -match $validateSiteBMapping.secondaryObject.Value)) {
                                                                    $reverseMappingValidated = $true
                                                                }
                                                            }
                                                            if ($reverseMappingValidated -eq $true) {
                                                                Write-Output "Create $type mapping between recovery $type ($recovery) and protected $type ($protected): SUCCESSFUL"
                                                            } else {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.GetValueException]"Create $type mapping between recovery $type ($recovery) and protected $type ($protected): POST_VALIDATION_FAILED"),
                                                                        'Add-SRMMapping',
                                                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                                        ""
                                                                    )
                                                                )
                                                            }
                                                        } else {
                                                            Write-Warning "$type mapping between recovery $type ($recovery) and protected $type ($protected) already exists: SKIPPING"
                                                        }
                                                        Disconnect-SrmServer -Server $srmBFqdn -Confirm:$false
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-SRMMapping

Function Undo-SRMMapping {
    <#
        .SYNOPSIS
        Remove a mapping between objects (folder, network, or compute resource) in the protected and failover VCF
        instances in Site Recovery Manager

        .DESCRIPTION
        The Undo-SRMMapping cmdlet removes a mapping between objects (folder, network, or compute resource) in the
        protected and failover VCF instances in Site Recovery Manager. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Removes a mapping between objects in the protected and failover VCF instances in Site Recovery Manager as
        defined by the -type, -protected, and -recovery parameters.

        .EXAMPLE
        Undo-SRMMapping -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -type Folder -protected xint-m01-fd-vrslcm -recovery xint-m01-fd-vrslcm
        This example removes a mapping between protected site folder xint-m01-fd-vrslcm01 and recovery site folder xint-m01-fd-vrslcm01 in Site Recovery Manager.
        
        .EXAMPLE
        Undo-SRMMapping -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -type Network -protected xint-m01-seg01 -recovery xint-m01-seg01
        This example removes a mapping between protected site network xint-m01-seg01 and recovery site network xint-m01-seg01 in Site Recovery Manager.
        
        .EXAMPLE
        Undo-SRMMapping -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -type Resource -protected sfo-m01-cl01 -recovery lax-m01-cl01
        This example removes a mapping between protected site compute resource vSphere Cluster sfo-m01-cl01 and recovery site compute resource vSphere Cluster lax-m01-cl01 in Site Recovery Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateSet("Folder","Network","Resource")] [String]$type,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$protected,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$recovery
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $srmAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $srmBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                                $global:DefaultSrmServers = $null
                                                if ((Test-SRMConnection -server $srmAFqdn) -and (Test-SRMConnection -server $srmBFqdn)) {
                                                    if (Test-SRMAuthentication -server $srmAFqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass -remoteUser $siteBvCenterDetails.ssoAdmin -remotePass $siteBvCenterDetails.ssoAdminPass) {
                                                        $siteASrmServer = $global:DefaultSrmServers | Where-Object {$_.Name -match $srmAFqdn}
                                                        if ($type -eq "Folder") {
                                                            Try {
                                                                $protectedMoRef = (Get-Folder -Server $siteAvCenterDetails.fqdn -Name $protected -ErrorAction Stop | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}).id
                                                                $recoveryMoRef = (Get-Folder -Server $siteBvCenterDetails.fqdn -Name $recovery -ErrorAction Stop | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}).id
                                                                $existingSiteAMappings = $siteASrmServer.extensionData.InventoryMapping.GetFolderMappings()    
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Network") {
                                                            Try {
                                                                $protectedMoRef = (Get-VirtualNetwork -Server $siteAvCenterDetails.fqdn -Name $protected -ErrorAction Stop | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}).id
                                                                $recoveryMoRef = (Get-VirtualNetwork -Server $siteBvCenterDetails.fqdn -Name $recovery -ErrorAction Stop | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}).id  
                                                                $existingSiteAMappings = $siteASrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Resource") {
                                                            Try {
                                                                $protectedCluster = Get-Cluster -Server $SiteAvCenterDetails.fqdn -Name $protected -ErrorAction SilentlyContinue | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}
                                                                if ($protectedCluster) {
                                                                    $protectedMoRef = ($protectedCluster | Get-ResourcePool -Name "Resources").id
                                                                } else {
                                                                    $protectedMoRef = (Get-ResourcePool -Server $siteAvCenterDetails.fqdn -Name $protected -ErrorAction Stop | Where-Object {$_.Uid -match $siteAvCenterDetails.fqdn}).id
                                                                }
                                                                $recoveryCluster = Get-Cluster -Server $SiteBvCenterDetails.fqdn -Name $recovery -ErrorAction SilentlyContinue | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}
                                                                if ($recoveryCluster) {
                                                                    $recoveryMoRef = ($recoveryCluster | Get-ResourcePool -Name "Resources").id
                                                                } else {
                                                                    $recoveryMoRef = (Get-ResourcePool -Server $siteBvCenterDetails.fqdn -Name $recovery -ErrorAction Stop | Where-Object {$_.Uid -match $siteBvCenterDetails.fqdn}).id
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                            $existingSiteAMappings = $siteASrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()
                                                        }
                                                        if ($existingSiteAMappings) {
                                                            $forwardMappingExists = $null
                                                            Foreach ($existingSiteAMapping in $existingSiteAMappings) {
                                                                if (($protectedMoRef -match $existingSiteAMapping.primaryObject.Value) -and ($recoveryMoRef -match $existingSiteAMapping.secondaryObject.Value)) {
                                                                    $forwardMappingExists = $true
                                                                }
                                                            }
                                                        }
                                                        if ($forwardMappingExists -eq $true) {
                                                            if ($type -eq "Folder") {
                                                                Try {
                                                                    $SiteASrmServer.extensionData.InventoryMapping.RemoveFolderMapping($protectedMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteAMappings = $SiteASrmServer.extensionData.InventoryMapping.GetFolderMappings()
                                                            } elseif ($type -eq "Network") {
                                                                Try {
                                                                    $SiteASrmServer.extensionData.InventoryMapping.RemoveNetworkMapping($protectedMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteAMappings = $SiteASrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } elseif ($type -eq "Resource") {
                                                                Try {
                                                                    $SiteASrmServer.extensionData.InventoryMapping.RemoveResourcePoolMapping($protectedMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteAMappings = $SiteASrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()
                                                            }
                                                            $forwardMappingValidated = $null
                                                            Foreach ($validateSiteAMapping in $validateSiteAMappings) {
                                                                if (($protectedMoRef -match $validateSiteAMapping.primaryObject.Value) -and ($recoveryMoRef -match $validateSiteAMapping.secondaryObject.Value)) {
                                                                    $forwardMappingValidated = $true
                                                                }
                                                            }
                                                            if (!$forwardMappingValidated) {
                                                                Write-Output "Remove $type mapping between protected $type ($protected) and recovery $type ($recovery): SUCCESSFUL"
                                                            } else {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.GetValueException]"Remove $type mapping between protected $type ($protected) and recovery $type ($recovery): POST_VALIDATION_FAILED"),
                                                                        'Add-SRMMapping',
                                                                        [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                        ""
                                                                    )
                                                                )
                                                            }
                                                        } else {
                                                            Write-Warning "$type mapping between protected $type ($protected) and recovery $type ($recovery) does not exist: SKIPPING"
                                                        }
                                                        Disconnect-SrmServer -Server $srmAFqdn -Confirm:$False
                                                    }
                                                    if (Test-SRMAuthentication -server $srmBFqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass -remoteUser $siteAvCenterDetails.ssoAdmin -remotePass $siteAvCenterDetails.ssoAdminPass) {
                                                        $siteBSrmServer = $global:DefaultSrmServers | Where-Object {$_.Name -match $srmBFqdn}
                                                        if ($type -eq "Folder") {
                                                            Try {
                                                                $existingSiteBMappings = $siteBSrmServer.extensionData.InventoryMapping.GetFolderMappings()    
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Network") {
                                                            Try {
                                                                $existingSiteBMappings = $siteBSrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        } elseif ($type -eq "Resource") {
                                                            Try {
                                                                $existingSiteBMappings = $siteBSrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()   
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                        if ($existingSiteBMappings) {
                                                            $reverseMappingExists = $null
                                                            Foreach ($existingSiteBMapping in $existingSiteBMappings) {
                                                                if (($recoveryMoRef -match $existingSiteBMapping.primaryObject.Value) -and ($protectedMoRef -match $existingSiteBMapping.secondaryObject.Value)) {
                                                                    $reverseMappingExists = $true
                                                                }
                                                            }
                                                        }  
                                                        if ($reverseMappingExists -eq $true) {
                                                            if ($type -eq "Folder") {
                                                                Try {
                                                                    $SiteBSrmServer.extensionData.InventoryMapping.RemoveFolderMapping($recoveryMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteBMappings = $SiteBSrmServer.extensionData.InventoryMapping.GetFolderMappings()
                                                            } elseif ($type -eq "Network") {
                                                                Try {
                                                                    $SiteBSrmServer.extensionData.InventoryMapping.RemoveNetworkMapping($recoveryMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteBMappings = $SiteBSrmServer.extensionData.InventoryMapping.GetNetworkMappings()
                                                            } elseif ($type -eq "Resource") {
                                                                Try {
                                                                    $SiteBSrmServer.extensionData.InventoryMapping.RemoveResourcePoolMapping($recoveryMoRef)
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                                $validateSiteBMappings = $SiteBSrmServer.extensionData.InventoryMapping.GetResourcePoolMappings()
                                                            }
                                                            $reverseMappingValidated = $null
                                                            Foreach ($validateSiteBMapping in $validateSiteBMappings) {
                                                                if (($recoveryMoRef -match $validateSiteBMapping.primaryObject.Value) -and ($protectedMoRef -match $validateSiteBMapping.secondaryObject.Value)) {
                                                                    $reverseMappingValidated = $true
                                                                }
                                                            }
                                                            if (!$reverseMappingValidated) {
                                                                Write-Output "Remove $type mapping between recovery $type ($recovery) and protected $type ($protected): SUCCESSFUL"
                                                            } else {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.GetValueException]"Remove $type mapping between recovery $type ($recovery) and protected $type ($protected): POST_VALIDATION_FAILED"),
                                                                        'Add-SRMMapping',
                                                                        [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                        ""
                                                                    )
                                                                )
                                                            }
                                                        } else {
                                                            Write-Warning "$type mapping between recovery $type ($recovery) and protected $type ($protected) does not exist: SKIPPING"
                                                        }
                                                        Disconnect-SrmServer -Server $srmBFqdn -Confirm:$false
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SRMMapping

Function New-SRMSitePair {
    <#
        .SYNOPSIS
        Create a site pair between Site Recovery Manager instances

        .DESCRIPTION
        The New-SRMSitePair cmdlet creates a site pair between Site Recovery Manager instances. The cmdlet connects to
        SDDC Manager in both the protected and recovery sites using the -sddcManagerAFqdn, -sddcManagerAUser,
        -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Create a site pair between the Site Recovery Manager instances integrated with their respective vCenter
        Server instances.

        .EXAMPLE
        New-SRMSitePair -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1!
        This example creates a site pair between Site Recovery Manager instances integrated with the management vCenter Server instance in each site.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $srmAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $srmBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                                $global:DefaultSrmServers = $null
                                                if ((Test-SRMConnection -server $srmAFqdn) -and (Test-SRMConnection -server $srmBFqdn)) {
                                                    if (Test-SRMAuthentication -server $srmAFqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                                                        if (Test-SRMAuthentication -server $srmBFqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                            Try {
                                                                $existingSitePair = $null
                                                                $getPairedSite = '$global:DefaultSrmServers[1].ExtensionData.GetPairedSite()'
                                                                $existingSitePair = Invoke-Expression $getPairedSite -ErrorAction SilentlyContinue
                                                            } Catch {
                                                            }
                                                            if ($existingSitePair.VcHost -eq $siteBvCenterDetails.fqdn) {
                                                                Write-Warning "Create Site Recovery Manager pair between local server $($srmAFqdn.Split(".")[0]) and remote server $($srmBFqdn.Split(".")[0]) already done: SKIPPING"
                                                                Break
                                                            }
                                                            $creds = @{
                                                                user = $siteBvCenterDetails.ssoAdmin
                                                                password = $siteBvCenterDetails.ssoAdminPass
                                                            }
                                                            $thumbprints = $global:DefaultSrmServers[1].ExtensionData.ProbeSsl($siteBvCenterDetails.fqdn)
                                                            $connectionSpec = @{
                                                                host = $siteBvCenterDetails.fqdn
                                                                thumbprints = $thumbprints
                                                                creds = $creds
                                                            }
                                                            Try {
                                                                $global:DefaultSrmServers[1].ExtensionData.PairSrm_Task($connectionSpec) | Out-Null
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                            Try {
                                                                Start-Sleep -Seconds 5
                                                                $existingSitePair = $null
                                                                $getPairedSite = '$global:DefaultSrmServers[1].ExtensionData.GetPairedSite()'
                                                                $existingSitePair = Invoke-Expression $getPairedSite -ErrorAction SilentlyContinue
                                                                if ($existingSitePair.VcHost -eq $siteBvCenterDetails.fqdn) {
                                                                    Write-Output "Create Site Recovery Manager pair between local server $($srmAFqdn.Split(".")[0]) and remote server $($srmBFqdn.Split(".")[0]) : SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.GetValueException]"Create Site Recovery Manager pair between local server $($srmAFqdn.Split(".")[0]) and remote server $($srmBFqdn.Split(".")[0]): POST_VALIDATION_FAILED"),
                                                                        'New-SRMSitePair',
                                                                        [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                        ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-SRMSitePair

Function Undo-SRMSitePair {
    <#
        .SYNOPSIS
        Removes an existing site pair between Site Recovery Manager instances

        .DESCRIPTION
        The Undo-SRMSitePair cmdlet removes an existing site pair between Site Recovery Manager instances. The cmdlet
        connects to SDDC Manager in both the protected and recovery sites using the -sddcManagerAFqdn,
        -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Removes an existing site pair between the Site Recovery Manager instances integrated with their respective
        vCenter Server instances.

        .EXAMPLE
        Undo-SRMSitePair -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1!
        This example removes a site pair between Site Recovery Manager instances integrated with the management vCenter Server instance in each site.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $srmAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $srmBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                                $global:DefaultSrmServers = $null
                                                if ((Test-SRMConnection -server $srmAFqdn) -and (Test-SRMConnection -server $srmBFqdn)) {
                                                    if (Test-SRMAuthentication -server $srmAFqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                                                        Try {
                                                            $existingSitePair = $null
                                                            $getPairedSite = '$global:DefaultSrmServers[0].ExtensionData.GetPairedSite()'
                                                            $existingSitePair = Invoke-Expression $getPairedSite -ErrorAction SilentlyContinue
                                                        } Catch {
                                                            if (!$existingSitePair) {
                                                                Write-Warning "Site Recovery Manager pair between local server $($srmAFqdn.Split(".")[0]) and remote server $($srmBFqdn.Split(".")[0]) does not exist: SKIPPING"
                                                                Break
                                                            } else {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                        Try {
                                                            $global:DefaultSrmServers[0].ExtensionData.BreakPairing_Task($existingSitePair) | Out-Null
                                                        } Catch {
                                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                                        }
                                                        Try {
                                                            Start-Sleep -Seconds 5
                                                            $existingSitePair = $null
                                                            $getPairedSite = '$global:DefaultSrmServers[0].ExtensionData.GetPairedSite()'
                                                            $existingSitePair = Invoke-Expression $getPairedSite -ErrorAction SilentlyContinue
                                                            else {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                [System.Management.Automation.ErrorRecord]::new(
                                                                    ([System.Management.Automation.GetValueException]"Remove Site Recovery Manager pair between local server $($srmAFqdn.Split(".")[0]) and remote server $($srmBFqdn.Split(".")[0]): POST_VALIDATION_FAILED"),
                                                                    'New-SRMSitePair',
                                                                    [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                    ""
                                                                    )
                                                                )
                                                            }
                                                        } Catch {
                                                            if (!$existingSitePair) {
                                                                Write-Output "Remove Site Recovery Manager pair between local server $($srmAFqdn.Split(".")[0]) and remote server $($srmBFqdn.Split(".")[0]) : SUCCESSFUL"
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SRMSitePair

Function Add-EsxiVrmsVMkernelPort {
    <#
        .SYNOPSIS
        Create a VMkernel port on ESXi hosts

        .DESCRIPTION
        The Add-EsxiVrmsVMkernelPort cmdlet creates a VMkernel port on each ESXi host for vSphere Replication traffic. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Creates a VMkernel port on each ESXi host for vSphere Replication traffic

        .EXAMPLE
        Add-EsxiVrmsVMkernelPort -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -portgroup sfo-m01-cl01-vds01-pg-vrms -netmask 255.255.255.0 -ipAddresses @("172.27.15.101","172.27.15.102","172.27.15.103","172.27.15.104")
        This example creates a VMkernel port for each ESXi host Management Domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$portgroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$netmask,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$ipAddresses
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)}) {
                                $vdswitchName = (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)}).VDSwitch.Name
                                $esxiHosts = Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain -and $_.vcenters.fqdn -eq $vcfVcenterDetails.fqdn}).clusters.id)}
                                if ($esxiHosts.Count -eq $ipAddresses.Count) {
                                    if ((Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VirtualSwitch $vdswitchName -PortGroup $portgroup | Where-Object {$_.VSphereReplicationEnabled -eq $true -and $_.VSphereReplicationNfcEnabled -eq $true}) -ne $esxiHosts.Count) {
                                        For ($i=0; $i -lt $esxiHosts.Count; $i++) {
                                            if (!(Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VMHost $esxiHosts.fqdn[$i] | Where-Object {$_.vSphereReplicationEnabled -eq $true})) {
                                                New-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VMHost $esxiHosts.fqdn[$i] -VirtualSwitch $vdswitchName -PortGroup $portgroup -ErrorAction Stop | Set-VMHostNetworkAdapter -IP $ipAddresses[$i] -SubnetMask $netmask -vSphereReplicationEnabled:$true -vSphereReplicationNfcEnabled:$true -Confirm:$false -ErrorAction Stop | Out-Null
                                            }
                                        }
                                        $validateVMkernelCreated = Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VirtualSwitch $vdswitchName -PortGroup $portgroup | Where-Object {$_.VSphereReplicationEnabled -eq $true -and $_.VSphereReplicationNfcEnabled -eq $true}
                                        if ($validateVMkernelCreated.Count -eq $esxiHosts.Count) {
                                            Write-Output "Creating VMkernel Ports for vSphere Replication traffic on all ESXi hosts in Workload Domain ($domain): SUCCESSFUL"
                                        } else {
                                            Write-Error "Creating VMkernel Ports for vSphere Replication traffic on all ESXi hosts in Workload Domain ($domain): POST_VALIDATED_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Creating VMkernel Ports for vSphere Replication traffic on all ESXi hosts in Workload Domain ($domain), already created: SKIPPED"
                                    }
                                } else {
                                    Write-Error "The number of IP addresses supplied do not match the number if ESXi hosts in Workload Domain ($domain): PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to find vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($portgroup): PRE_VALIDATION_FAILED"
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-EsxiVrmsVMkernelPort

Function Undo-EsxiVrmsVMkernelPort {
    <#
        .SYNOPSIS
        Removes VMkernel ports on ESXi hosts

        .DESCRIPTION
        The Undo-EsxiVrmsVMkernelPort cmdlet removes the VMkernel port on each ESXi host for vSphere Replication traffic. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Removes a VMkernel port on each ESXi host for vSphere Replication traffic

        .EXAMPLE
        Undo-EsxiVrmsVMkernelPort -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -portgroup sfo-m01-cl01-vds01-pg-vrms
        This example removes a VMkernel from each ESXi host Management Domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$portgroup
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)}) {
                                $vdswitchName = (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)}).VDSwitch.Name
                                $esxiHosts = Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain -and $_.vcenters.fqdn -eq $vcfVcenterDetails.fqdn}).clusters.id)}
                                
                                if (!(Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VirtualSwitch $vdswitchName -PortGroup $portgroup | Where-Object {$_.VSphereReplicationEnabled -eq $true -and $_.VSphereReplicationNfcEnabled -eq $true}) -ne $esxiHosts.Count) {
                                    For ($i=0; $i -lt $esxiHosts.Count; $i++) {
                                        if (Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VMHost $esxiHosts.fqdn[$i] | Where-Object {$_.vSphereReplicationEnabled -eq $true}) {
                                            Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VMHost $esxiHosts.fqdn[$i] -PortGroup $portgroup -ErrorAction Stop | Remove-VMHostNetworkAdapter -Confirm:$false -ErrorAction Stop
                                        }
                                    }
                                    $validateVMkernel = Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VirtualSwitch $vdswitchName -PortGroup $portgroup | Where-Object {$_.VSphereReplicationEnabled -eq $true -and $_.VSphereReplicationNfcEnabled -eq $true}
                                    if ($validateVMkernel.Count -eq 0) {
                                        Write-Output "Removing VMkernel Ports for vSphere Replication traffic on all ESXi hosts in Workload Domain ($domain): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing VMkernel Ports for vSphere Replication traffic on all ESXi hosts in Workload Domain ($domain): POST_VALIDATED_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing VMkernel Ports for vSphere Replication traffic on all ESXi hosts in Workload Domain ($domain), do not exist: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($portgroup): PRE_VALIDATION_FAILED"
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-EsxiVrmsVMkernelPort

Function Add-EsxiVrmsStaticRoute {
    <#
        .SYNOPSIS
        Create a static route on ESXi hosts for vSphere Replication traffic

        .DESCRIPTION
        The Add-EsxiVrmsStaticRoute cmdlet creates a static route on each ESXi hosts for vSphere Replication traffic.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Creates static routes on ESXi hosts for vSphere Replication traffic

        .EXAMPLE
        Add-EsxiVrmsStaticRoute -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -subnet 172.27.15.0/24 -gateway 172.27.15.1 -portgroup sfo-sfo-m01-cl01-vds01-pg-vrms
        This example adds a static route to each ESXi host in the Management Domain to the recovery site vSphere Replication subnet
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$subnet,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [IPAddress]$gateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$portgroup
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $vdswitchName = (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)}).VDSwitch.Name
                            $esxiHosts = Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain -and $_.vcenters.fqdn -eq $vcfVcenterDetails.fqdn}).clusters.id)}
                            if (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)}) {
                                if ((Get-VMHostNetworkAdapter -Server $vcfVcenterDetails.fqdn -VirtualSwitch $vdswitchName -PortGroup $portgroup | Where-Object {$_.VSphereReplicationEnabled -eq $true -and $_.VSphereReplicationNfcEnabled -eq $true}).Count -eq $esxiHosts.Count) {
                                    [IPAddress]$network = $subnet.Split("/")[0]
                                    [Int32]$prefixLength = $subnet.Split("/")[1]
                                    Foreach ($esxiHost in $esxiHosts) {
                                        if (!(Get-VMHostRoute -VMHost $esxiHost.fqdn -Server $vcfVcenterDetails.fqdn | Where-Object {($_.ExtensionData.Network -eq $network) -and ($_.ExtensionData.Gateway -eq $gateway)})) {
                                            Get-VMHost -Name $esxiHost.fqdn -Server $vcfVcenterDetails.fqdn | New-VMHostRoute -Destination $network -Gateway $gateway -PrefixLength $prefixLength -Confirm:$false | Out-Null
                                            if (Get-VMHostRoute -VMHost $esxiHost.fqdn -Server $vcfVcenterDetails.fqdn | Where-Object {($_.ExtensionData.Network -eq $network) -and ($_.ExtensionData.Gateway -eq $gateway)}) {
                                                Write-Output "Adding static route for vSphere Replication traffic to ESXi Host ($($esxiHost.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Adding static route for vSphere Replication traffic to ESXi Host ($($esxiHost.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Adding static route for vSphere Replication traffic to ESXi Host ($($esxiHost.fqdn)), already exists: SKIPPED"
                                        }
                                    }
                                } else {
                                    Write-Error "Found ESXi hosts in Workload Domain ($domain) without a VMkernel port connected to ($portgroup) for vSphere Replication traffic: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to find vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($portgroup): PRE_VALIDATION_FAILED"
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-EsxiVrmsStaticRoute

Function Undo-EsxiVrmsStaticRoute {
    <#
        .SYNOPSIS
        Removes a static route from ESXi hosts for vSphere Replication traffic

        .DESCRIPTION
        The Undo-EsxiVrmsStaticRoute cmdlet removes a static route on each ESXi hosts for vSphere Replication traffic.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Removes the static routes on ESXi hosts for vSphere Replication traffic

        .EXAMPLE
        Undo-EsxiVrmsStaticRoute -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -network 172.27.15.0
        This example removes a static route to each ESXi host in the Management Domain to the recovery site vSphere Replication subnet
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [IPAddress]$network
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $esxiHosts = Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain -and $_.vcenters.fqdn -eq $vcfVcenterDetails.fqdn}).clusters.id)}
                            Foreach ($esxiHost in $esxiHosts) {
                                if (Get-VMHostRoute -VMHost $esxiHost.fqdn -Server $vcfVcenterDetails.fqdn | Where-Object {$network -contains $_.Destination.IPAddressToString}) {
                                    Remove-VMHostRoute -VMHostRoute (Get-VMHostRoute -VMHost $esxiHost.fqdn -Server $vcfVcenterDetails.fqdn | Where-Object {$network -contains $_.Destination.IPAddressToString}) -Confirm:$false
                                    if (!(Get-VMHostRoute -VMHost $esxiHost.fqdn -Server $vcfVcenterDetails.fqdn | Where-Object {$network -contains $_.Destination.IPAddressToString})) {
                                        Write-Output "Removing static route for vSphere Replication traffic to ESXi Host ($($esxiHost.fqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing static route for vSphere Replication traffic to ESXi Host ($($esxiHost.fqdn)): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing static route for vSphere Replication traffic to ESXi Host ($($esxiHost.fqdn)), already exists: SKIPPED"
                                }
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-EsxiVrmsStaticRoute

Function Add-SrmLicenseKey {
    <#
        .SYNOPSIS
        Add a license for Site Recovery Manager

        .DESCRIPTION
        The Add-SrmLicenseKey cmdlet adds a license for Site Recovery Manager in vCenter Server. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Validates that network connectivity and authentication are possible to the Site Recovery Manager instance
        - Validates whether the license key exists in vCenter Server inventory, and if not, installs them
        - Assigns the license to Site Recovery Manager

        .EXAMPLE
        Add-SrmLicenseKey -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -srmLicenseKey AAAAA-BBBBB-CCCCC-DDDDD-EEEEE
        This example adds a license key to the Site Recovery Manager instance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmLicenseKey
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ((((Get-View -server $vcfVcenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]) {
                                $srmFqdn = (((Get-View -server $vcfVcenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                if (Test-SRMConnection -server $srmFqdn) {
                                    if (Test-SRMAuthentication -server $srmFqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        $serviceInstance = Get-View -Server $vcfVcenterDetails.fqdn ServiceInstance
                                        $licenseManager = Get-View -Server $vcfVcenterDetails.fqdn $serviceInstance.Content.LicenseManager | Where-Object {$_.LicensedEdition -match $vcfVcenterDetails.fqdn}
                                        $licenseAssignmentManager = Get-View -Server $vcfVcenterDetails.fqdn $licenseManager.licenseAssignmentManager
                                        if ($licenseManager.Licenses | Where-Object {$_.LicenseKey -eq $srmLicenseKey}) {
                                            Write-Warning "Adding License key ($srmLicenseKey) for Site Recovery Manager to vCenter Server ($($vcfVcenterDetails.fqdn)), already exists: SKIPPING"
                                        } else {
                                            $licenseManager.AddLicense($srmLicenseKey,$null) | Out-Null
                                            $licenseManager.UpdateViewData()
                                            if ($licenseManager.Licenses | Where-Object {$_.LicenseKey -eq $srmLicenseKey}) {
                                                Write-Output "Adding License key ($srmLicenseKey) for Site Recovery Manager to vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Adding License key ($srmLicenseKey) for Site Recovery Manager to vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                            $srmSiteName = (($global:DefaultSrmServers | Where-Object {$_.Name -eq $srmFqdn}).ExtensionData.GetLocalSiteInfo()).SiteName
                                            $srmPartialUuid = ($licenseAssignmentManager.QueryAssignedLicenses($null) | Where-Object {$_.EntityDisplayName -eq $srmSiteName}).EntityId
                                            $scriptCommand = "/usr/lib/vmware-vmafd/bin/vmafd-cli get-ldu --server-name localhost"
                                            $output = Invoke-VMScript -VM ($vcfVcenterDetails.fqdn).Split(".")[0] -ScriptText $scriptCommand -GuestUser root -GuestPassword $vcfVcenterDetails.rootPass -Server $vcfVcenterDetails.fqdn
                                            $srmUuid = ($srmPartialUuid + "-" + $output.ScriptOutput).Trim()
                                            if (($licenseAssignmentManager.QueryAssignedLicenses($srmUuid).AssignedLicense.LicenseKey) -eq $srmLicenseKey) {
                                                Write-Warning "Assigning License Key ($srmLicenseKey) to Site Recovery Manager instance ($srmFqdn), already exists: SKIPPING"
                                            } else {
                                                $licenseAssignmentManager.UpdateAssignedLicense($srmUuid,$srmLicenseKey,$null) | Out-Null
                                                $licenseAssignmentManager.UpdateViewData() | Out-Null
                                                if (($licenseAssignmentManager.QueryAssignedLicenses($srmUuid).AssignedLicense.LicenseKey) -eq $srmLicenseKey) {
                                                    Write-Output "Assigning License Key ($srmLicenseKey) to Site Recovery Manager instance ($srmFqdn): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Assigning License Key ($srmLicenseKey) to Site Recovery Manager instance ($srmFqdn): POST_VALIDATION_FAILED"
                                                }
                                            }
                                        }
                                    }
                                    Disconnect-SrmServer -Server $srmFqdn -Force -Confirm:$false
                                }
                            } else {
                                Write-Error "No Site Recovery Manager Appliance Registered with vCenter Server ($($vcfVcenterDetails.fqdn))"
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-SrmLicenseKey

Function Undo-SrmLicenseKey {
    <#
        .SYNOPSIS
        Removes a license for Site Recovery Manager

        .DESCRIPTION
        The Undo-SrmLicenseKey cmdlet removes a license for Site Recovery Manager from vCenter Server. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to the SDDC Manager instance
        - Validates that network connectivity and authentication is possible to the vCenter Server instance
        - Validates that network connectivity and authentication are possible to the Site Recovery Manager instance
        - Validates whether the license key exists in vCenter Server inventory, and removes it

        .EXAMPLE
        Undo-SrmLicenseKey -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -srmLicenseKey 00000-11111-22222-33333-4444
        This example removes the license key from Site Recovery Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmLicenseKey
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ((((Get-View -server $vcfVcenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]) {
                                $srmFqdn = (((Get-View -server $vcfVcenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                if (Test-SRMConnection -server $srmFqdn) {
                                    if (Test-SRMAuthentication -server $srmFqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        $serviceInstance = Get-View -Server $vcfVcenterDetails.fqdn ServiceInstance 
                                        $licenseManager = Get-View -Server $vcfVcenterDetails.fqdn $serviceInstance.Content.LicenseManager | Where-Object {$_.LicensedEdition -match $vcfVcenterDetails.fqdn}
                                        $licenseAssignmentManager = Get-View -Server $vcfVcenterDetails.fqdn $licenseManager.licenseAssignmentManager
                                        $srmSiteName = (($global:DefaultSrmServers | Where-Object {$_.Name -eq $srmFqdn}).ExtensionData.GetLocalSiteInfo()).SiteName
                                        $srmPartialUuid = ($licenseAssignmentManager.QueryAssignedLicenses($null) | Where-Object {$_.EntityDisplayName -eq $srmSiteName}).EntityId
                                        $scriptCommand = "/usr/lib/vmware-vmafd/bin/vmafd-cli get-ldu --server-name localhost"
                                        $output = Invoke-VMScript -VM ($vcfVcenterDetails.fqdn).Split(".")[0] -ScriptText $scriptCommand -GuestUser root -GuestPassword $vcfVcenterDetails.RootPass -Server $vcfVcenterDetails.fqdn
                                        $srmUuid = ($srmPartialUuid + "-" + $output.ScriptOutput).Trim()
                                        if (!($licenseAssignmentManager.QueryAssignedLicenses($srmUuid).AssignedLicense.LicenseKey) -or ($licenseAssignmentManager.QueryAssignedLicenses($srmUuid).AssignedLicense.LicenseKey) -eq "00000-00000-00000-00000-00000") {
                                            Write-Warning "Removing License key ($srmLicenseKey) for Site Recovery Manager instance ($srmFqdn), already removed: SKIPPING"
                                        } else {
                                            $licenseAssignmentManager.RemoveAssignedLicense($srmUuid) | Out-Null
                                            $licenseAssignmentManager.UpdateViewData() | Out-Null
                                            if (!($licenseAssignmentManager.QueryAssignedLicenses($srmUuid).AssignedLicense.LicenseKey)) {
                                                Write-Output "Removing License key ($srmLicenseKey) from Site Recovery Manager instance ($srmFqdn): SUCCESSFUL"
                                            } else {
                                                Write-Error "Removing License key ($srmLicenseKey) from Site Recovery Manager instance ($srmFqdn): POST_VALIDATION_FAILED"
                                            }
                                            if (!($licenseManager.Licenses | Where-Object {$_.LicenseKey -eq $srmLicenseKey})) {
                                                Write-Warning "Removing License key ($srmLicenseKey) from vCenter Server ($($vcfVcenterDetails.fqdn)), already removed: SKIPPING"
                                            } else {
                                                $licenseManager.RemoveLicense($srmLicenseKey) | Out-Null
                                                $licenseManager.UpdateViewData()
                                                if (!($licenseManager.Licenses | Where-Object {$_.LicenseKey -eq $srmLicenseKey})) {
                                                    Write-Output "Removing License key ($srmLicenseKey) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Removing License key ($srmLicenseKey) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SrmLicenseKey

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region D E V E L O P E R R E A D Y I N F R A S T R U C T U R E F U N C T I O N S ###########

Function Add-NetworkSegment {
    <#
        .SYNOPSIS
        The Add-NetworkSegment cmdlet creates an NSX segment. The cmdlet connects to SDDC Manager using the -server,
        -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Create the NSX segment if not already created in NSX Manager

        .DESCRIPTION
        The Add-NetworkSegment cmdlet creates an NSX Segment

        .EXAMPLE
        Add-NetworkSegment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -segmentName sfo-w01-kub-seg01 -gatewayType Tier1 -connectedGateway sfo-w01-ec01-t1-gw01 -cidr 192.168.31.1/24 -transportZone overlay-tz-sfo-w01-nsx01.sfo.rainpole.io -segmentType Overlay
        This example creates an overlay-backed NSX segment in the workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$segmentName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$connectedGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cidr,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$transportZone,
        [Parameter (Mandatory = $true)] [ValidateSet("Tier0", "Tier1")] [String]$gatewayType,
        [Parameter (Mandatory = $true)] [ValidateSet("Overlay", "VLAN")] [String]$segmentType
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) {
                            if (!(Get-NsxtSegment -name $segmentName)) {
                                if ($gatewayType -eq "Tier0") { $tierGatewayExists = Get-NsxtTier0Gateway -name $connectedGateway }
                                if ($gatewayType -eq "Tier1") { $tierGatewayExists = Get-NsxtTier1Gateway -name $connectedGateway }
                                if ($tierGatewayExists) {
                                    $validateTransportZone = Get-NsxtTransportZone -Name $transportZone -ErrorAction SilentlyContinue
                                    if ($validateTransportZone.display_name -eq $transportZone) {
                                        if ($validateTransportZone.transport_type -ne $segmentType.ToUpper()){
                                            Write-Error "NSX Transport Zone $transportZone does not match the defined segment Type $segmentType in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED"
                                            Break
                                        }
                                    } else {
                                        Write-Error "Unable to find NSX Transport Zone ($transportZone) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED"
                                        Break
                                    }
                                    New-NsxtSegment -name $segmentName -connectedGateway $connectedGateway -cidr $cidr -transportZone $transportZone -gatewayType $gatewayType -segmentType $segmentType | Out-Null
                                    if (Get-NsxtSegment -name $segmentName) {
                                        Write-Output "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to find NSX $gatewayType Gateway $connectedGateway in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Creating $segmentType-backed NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName), already exists: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-NetworkSegment

Function Undo-NetworkSegment {
    <#
        .SYNOPSIS
        The Undo-NetworkSegment cmdlet removes an NSX segment. The cmdlet connects to SDDC Manager using the -server,
        -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Removes the NSX segment if not already removed from NSX Manager

        .DESCRIPTION
        The Undo-NetworkSegment cmdlet removes an NSX Segment from NSX Manager

        .EXAMPLE
        Undo-NetworkSegment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -segmentName sfo-w01-kub-seg01
        This example removes an NSX segment from the NSX Manager of Workload Domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$segmentName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) {
                            if (Get-NsxtSegment -name $segmentName) {
                                Remove-NsxtSegment -name $segmentName | Out-Null
                                if (!(Get-NsxtSegment -name $segmentName)) {
                                    Write-Output "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing NSX segment in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($segmentName), does not exist: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-NetworkSegment

Function Add-PrefixList {
    <#
        .SYNOPSIS
        The Add-PrefixList cmdlet creates NSX Prefix List in the NSX Management Cluster. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Create an NSX Prefix List if not already created in NSX Manager

        .DESCRIPTION
        The Add-PrefixList cmdlet creates an NSX Prefix List

        .EXAMPLE
        Add-PrefixList -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist -subnetCIDR 192.168.20.0/24 -ingressSubnetCidr "192.168.21.0/24" -egressSubnetCidr "192.168.22.0/24" -GE "28" -LE "32" -action PERMIT
        This example creates an NSX Prefix List in the workload domain NSX Management Cluster
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$subnetCidr,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ingressSubnetCidr,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$egressSubnetCidr,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$GE,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$LE,
        [Parameter (Mandatory = $true)] [ValidateSet("PERMIT", "DENY")] [String]$action
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) {
                            if (Get-NsxtTier0Gateway -name $tier0Gateway) {
                                if (!(Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue)) {
                                    Get-NsxtTier0Gateway -name $tier0Gateway | New-NsxtPrefixList -name $prefixListName -subnetCidr $subnetCidr -action $action | Out-Null
                                    if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) {
                                        Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName | Add-NsxtPrefix -subnetCidr $ingressSubnetCidr -GE $GE -LE $LE -action $action | Out-Null
                                        Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName | Add-NsxtPrefix -subnetCidr $egressSubnetCidr -GE $GE -LE $LE -action $action | Out-Null
                                        Write-Output "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Adding NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName), already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-PrefixList

Function Undo-PrefixList {
    <#
        .SYNOPSIS
        The Undo-PrefixList cmdlet removes the NSX Prefix List from NSX Manager. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Removes an NSX Prefix List if not already removed from NSX Manager

        .DESCRIPTION
        The Undo-PrefixList cmdlet removes an NSX Prefix List

        .EXAMPLE
        Undo-PrefixList -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist
        This example removes an NSX Prefix List in the Workload Domain NSX Management Cluster
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) {
                            if (Get-NsxtTier0Gateway -name $tier0Gateway) {
                                if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) {
                                    Remove-NsxtPrefixList -name $prefixListName -tier0Gateway $tier0Gateway | Out-Null
                                    if (!(Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue)) {
                                        Write-Output "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing NSX IP Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName), does not exist: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-PrefixList

Function Add-RouteMap {
    <#
        .SYNOPSIS
        The Add-RouteMap cmdlet creates NSX Prefix List in the NSX Management Cluster. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Create an NSX Route Map if not already created in NSX Manager

        .DESCRIPTION
        The Add-RouteMap cmdlet creates an NSX Route Map

        .EXAMPLE
        Add-RouteMap -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -routeMapName sfo-w01-ec01-t0-gw01-routemap -prefixListName sfo-w01-ec01-t0-gw01-mgmt-prefixlist -action PERMIT -applyPolicy:$true
        This example creates an NSX Route Map in workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$routeMapName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefixListName,
        [Parameter (Mandatory = $true)] [ValidateSet("PERMIT", "DENY")][String]$action,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Bool]$applyPolicy
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) {
                            if (Get-NsxtTier0Gateway -name $tier0Gateway) {
                                if (!(Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue)) {
                                    if (Get-NsxtTier0Gateway -name $tier0Gateway | Get-NsxtPrefixList -name $prefixListName -ErrorAction SilentlyContinue) {
                                        Get-NsxtTier0Gateway -name $tier0Gateway | New-NsxtRouteMap -name $routeMapName -prefixList $prefixListName -action $Action | Out-Null
                                        if (Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue) {
                                            if ($applyPolicy -eq $true) {
                                                Get-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway | Set-NsxtRouteRedistributionPolicy -routeMap $routeMapName | Out-Null
                                            }
                                            Write-Output "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find NSX Prefix List in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($prefixListName): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Adding NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName), already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-RouteMap

Function Undo-RouteMap {
    <#
        .SYNOPSIS
        The Undo-RouteMap cmdlet removes NSX Route Map from the NSX Management Cluster. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Removes an NSX Route Map from NSX Manager

        .DESCRIPTION
        The Undo-RouteMap cmdlet removes an NSX Route Map

        .EXAMPLE
        Undo-RouteMap -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tier0Gateway sfo-w01-ec01-t0-gw01 -routeMapName sfo-w01-ec01-t0-gw01-routemap
        This example removes an NSX Route Map in the workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$routeMapName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) {
                            if (Get-NsxtTier0Gateway -name $tier0Gateway) {
                                if (Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue) {
                                    Remove-NsxtRouteMap -name $routeMapName -tier0Gateway $tier0Gateway | Out-Null
                                    if (!(Get-NsxtRouteMap -tier0Gateway $tier0Gateway -name $routeMapName -ErrorAction SilentlyContinue)) {
                                        Write-Output "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing NSX Route Map in NSX Manager ($($vcfNsxtDetails.fqdn)) named ($routeMapName), does not exist: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find NSX Tier0 Gateway ($tier0Gateway) in NSX Manager ($($vcfNsxtDetails.fqdn)): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-RouteMap

Function Set-DatastoreTag {
    <#
        .SYNOPSIS
        The Function Set-DatastoreTag cmdlet creates and applies a vSphere Tag to the primary datastore. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Creates and applies a vSphere Tag to the primary datastore

        .DESCRIPTION
        The Set-DatastoreTag cmdlet creates and applies a vSphere Tag to the primary datastore

        .EXAMPLE
        Set-DatastoreTag -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tagName vsphere-with-tanzu-tag -tagCategoryName vsphere-with-tanzu-category
        This example creates a new tag and assigns it to the primary datastore of Workload Domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagCategoryName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName
                                if ($datastoreExist = Get-Datastore -Name $datastore -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq $datastore}) {
                                    if (!(Get-TagAssignment -Entity $datastoreExist.Name -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) {
                                        if (!(Get-TagCategory -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagCategoryName })) {
                                            New-TagCategory -Name $tagCategoryName -EntityType Datastore -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                        }
                                        if (!(Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName })) {
                                            New-Tag -Name $tagName -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                        }
                                        Get-Datastore -Name $Datastore -Server $vcfVcenterDetails.fqdn | New-TagAssignment -Tag $tagName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                        if ((Get-TagAssignment -Entity $datastoreExist.Name -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) {
                                            Write-Output "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                        } else {
                                            Write-Error "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Creating vSphere Tag ($tagName) and applying to datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED"
                                    }
                                } else {
                                    Write-Error "Unable to find datastore ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-DatastoreTag

Function Undo-DatastoreTag {
    <#
        .SYNOPSIS
        The Function Undo-DatastoreTag cmdlet removes a vSphere Category and Tag. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes the vSphere Tag

        .DESCRIPTION
        The Undo-DatastoreTag cmdlet removes the vSphere Tag

        .EXAMPLE
        Undo-DatastoreTag -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -tagName vsphere-with-tanzu-tag -tagCategoryName vsphere-with-tanzu-category
        This example removes the vSphere tag from the Workload Domain sfo-w01 vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagCategoryName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore | Where-Object { $_.Name -eq $tagName }) {
                                    Remove-Tag -Tag $tagName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                    Remove-TagCategory -Category $tagCategoryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                    if (!(Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName })) {                                            
                                        Write-Output "Removing vSphere Tag ($tagName) and vSphere Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"                                        
                                    } else {
                                        Write-Error "Removing vSphere Tag ($tagName) and vSphere Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing vSphere Tag ($tagName) and Category ($tagCategoryName) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-DatastoreTag

Function Add-StoragePolicy {
    <#
        .SYNOPSIS
        The Add-StoragePolicy cmdlet creates a vSphere Storage Policy. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Creates a VM vSphere Storage Policy

        .DESCRIPTION
        The Add-StoragePolicy cmdlet creates a VM vSphere Storage Policy

        .EXAMPLE
        Add-StoragePolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -policyName vsphere-with-tanzu-storage-policy -tagName vsphere-with-tanzu-tag
        This example creates a VM Storage Policy named vsphere-with-tanzu-policy in the Wrkload Domain vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$policyName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tagName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (!(Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) {
                                    if (Get-Tag -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $tagName }) {
                                        New-SpbmStoragePolicy -Name $policyName -AnyOfRuleSets (New-SpbmRuleSet -AllOfRules (New-SpbmRule -AnyOfTags $tagName -Server $vcfVcenterDetails.fqdn)) -Server $vcfVcenterDetails.fqdn | Out-Null
                                        if (Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) {
                                            Write-Output "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): SUCCESSFUL"
                                        } else {
                                            Write-Error "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find vSphere Tag ($tagName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Creating Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName), already exists: SKIPPED"                                    
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-StoragePolicy

Function Undo-StoragePolicy {
    <#
        .SYNOPSIS
        The Undo-StoragePolicy cmdlet removes a vSphere Storage Policy. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes a VM vSphere Storage Policy

        .DESCRIPTION
        The Undo-StoragePolicy cmdlet removes a VM vSphere Storage Policy

        .EXAMPLE
        Undo-StoragePolicy -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -policyName vsphere-with-tanzu-storage-policy
        This example removes a VM Storage Policy named vsphere-with-tanzu-storage-policy from the Wrkload Domain vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$policyName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) {
                                    Remove-SpbmStoragePolicy -StoragePolicy $policyName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                    if (!(Get-SpbmStoragePolicy -Name $policyName -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) {
                                        Write-Output "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing Storage Policy in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($policyName), does not exist: SKIPPED"                                    
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-StoragePolicy

Function Add-ContentLibrary {
    <#
        .SYNOPSIS
        Creates a content library
    
        .DESCRIPTION
        The Add-ContentLibrary cmdlet creates a subscribed or published content library. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Creates a content library
    
        .EXAMPLE
        Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 -published
        This example creates published content library named sfo-w01-lib01 on the primary datastore in workload domain sfo-w01
    
        .EXAMPLE
        Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01 -datastore sfo-w01-ds-nfs01 -published
        This example creates published content library named sfo-w01-lib01 on a specific datastore in workload domain sfo-w01
    
        .EXAMPLE
        Add-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName Kubernetes -subscriptionUrl "https://wp-content.vmware.com/v2/latest/lib.json"
        This example creates subscribed content library named Kubernetes on the primary datastore in workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibraryName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$datastore,
        [Parameter (ParameterSetName = 'Subscription', Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$subscriptionUrl,
        [Parameter (ParameterSetName = 'Local', Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$published
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (!(Get-ContentLibrary -Name $contentLibraryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue)) {
                                    if (!$PsBoundParameters.ContainsKey('datastore')) {
                                        $datastore = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).primaryDatastoreName
                                    }
                                    if (Get-Datastore -Name $datastore -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue | Where-Object {$_.Name -eq $datastore}) {
                                        if ($subscriptionUrl) {
                                            #attribution to William Lam (https://gist.github.com/lamw/988e4599c0f88d9fc25c9f2af8b72c92) for this snippet
                                            Invoke-RestMethod -Uri $subscriptionUrl -Method Get | Out-Null

                                            $endpointRequest = [System.Net.Webrequest]::Create("$subscriptionUrl")
                                            $sslThumbprint = $endpointRequest.ServicePoint.Certificate.GetCertHashString()
                                            $sslThumbprint = $sslThumbprint -replace '(..(?!$))', '$1:'

                                            $contentLibraryInput = @{
                                                Name            = $contentLibraryName
                                                Datastore       = $datastore
                                                AutomaticSync   = $true
                                                SubscriptionUrl = $subscriptionUrl
                                                SslThumbprint   = $sslThumbprint
                                            }

                                            New-ContentLibrary @contentLibraryInput -Server $vcfVcenterDetails.fqdn | Out-Null
                                        } elseif ($published) {
                                            New-ContentLibrary -Name $contentLibraryName -Published -Datastore $datastore -Server $vcfVcenterDetails.fqdn | Out-Null
                                        }
                                        if (Get-ContentLibrary -Name $contentLibraryName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) {
                                            Write-Output "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): SUCCESSFUL"
                                        } else {
                                            Write-Error "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find Datastore named ($datastore) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Creating Content Library in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName), already exists: SKIPPED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-ContentLibrary

Function Undo-ContentLibrary {
    <#
        .SYNOPSIS
        Remove Content Library

        .DESCRIPTION
        The Undo-ContentLibrary cmdlet removes a content library. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Deletes a content library

        .EXAMPLE
        Undo-ContentLibrary -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -contentLibraryName sfo-w01-lib01
        This example removes the content library from the Workload Domain vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibraryName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-ContentLibrary -Name $contentLibraryName -ErrorAction Ignore) {
                                    Remove-ContentLibrary -ContentLibrary $contentLibraryName -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                    if (!(Get-ContentLibrary -Name $contentLibraryName -ErrorAction Ignore)) {
                                        Write-Output "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing Content Library from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($contentLibraryName), does not exist: SKIPPED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-ContentLibrary

Function Enable-SupervisorCluster {
    <#
        .SYNOPSIS
        Enables Workload Management on a VCF cluster

        .DESCRIPTION
        The Enable-SupervisorCluster cmdlet enables Workload Management on a VCF cluster. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Performs validation of in puts unless skipped using a switch
        - Enables Workload Management on the vSphere cluster

        .EXAMPLE
        $wmClusterInput = @{
            server = "sfo-vcf01.sfo.rainpole.io"
            user = "administrator@vsphere.local"
            pass = 'VMw@re1!'
            domain = "sfo-w01"
            cluster = "sfo-w01-cl01"
            sizeHint = "Tiny"
            managementVirtualNetwork = "sfo-w01-kub-seg01"
            managementNetworkMode = "StaticRange"
            managementNetworkStartIpAddress = "192.168.20.10"
            managementNetworkAddressRangeSize = 5
            managementNetworkGateway = "192.168.20.1"
            managementNetworkSubnetMask = "255.255.255.0"
            masterDnsName = "sfo-w01-cl01.sfo.rainpole.io"
            masterDnsServers = @("172.16.11.4", "172.16.11.5")
            masterNtpServers = @("172.16.11.253", "172.16.12.253")
            contentLibrary = "Kubernetes"
            ephemeralStoragePolicy = "vsphere-with-tanzu-storage-policy"
            imageStoragePolicy = "vsphere-with-tanzu-storage-policy"
            masterStoragePolicy = "vsphere-with-tanzu-storage-policy"
            nsxEdgeCluster = "sfo-w01-ec01"
            distributedSwitch = "sfo-w01-cl01-vds01"
            podCIDRs = "100.100.0.0/20"
            serviceCIDR = "100.200.0.0/22"
            externalIngressCIDRs = "192.168.21.0/24"
            externalEgressCIDRs = "192.168.22.0/24"
            workerDnsServers = @("172.16.11.4", "172.16.11.5")
            masterDnsSearchDomain = "sfo.rainpole.io"
        }

        .EXAMPLE
        Enable-SupervisorCluster @wmClusterInput
        This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01

        .EXAMPLE
        Enable-SupervisorCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -sizeHint Tiny -managementVirtualNetwork sfo-w01-kub-seg01 -managementNetworkMode StaticRange -managementNetworkStartIpAddress 192.168.20.10 -managementNetworkAddressRangeSize 5 -managementNetworkGateway 192.168.20.1 -managementNetworkSubnetMask 255.255.255.0 -cluster sfo-w01-cl01 -contentLibrary Kubernetes -ephemeralStoragePolicy vsphere-with-tanzu-storage-policy -imageStoragePolicy vsphere-with-tanzu-storage-policy -masterStoragePolicy vsphere-with-tanzu-storage-policy -nsxEdgeCluster sfo-w01-ec01 -distributedSwitch sfo-w01-sfo-w01-vc01-sfo-w01-cl01-vds01 -podCIDRs "100.100.0.0/20" -serviceCIDR "100.200.0.0/22" -externalIngressCIDRs "192.168.21.0/24" -externalEgressCIDRs "192.168.22.0/24" -masterNtpServers @("172.16.11.253", "172.16.12.253") -masterDnsServers @("172.16.11.4", "172.16.11.5") -masterDnsName sfo-w01-cl01.sfo.rainpole.io -masterDnsSearchDomain sfo.rainpole.io -workerDnsServers @("172.16.11.4", "172.16.11.5")
        This example enables Workload Management on a vSphere Cluster in workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateSet("Tiny", "Small", "Medium", "Large")] [String]$sizeHint,
        [Parameter (Mandatory = $true)] [ValidateSet("DHCP", "StaticRange")][String]$managementNetworkMode,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementVirtualNetwork,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkStartIpAddress,
        [Parameter (Mandatory = $true)] [ValidateRange(5,10)][int]$managementNetworkAddressRangeSize,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementNetworkSubnetMask,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterDnsName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterNtpServers,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$masterDnsServers,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$contentLibrary,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ephemeralStoragePolicy,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$imageStoragePolicy,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$masterStoragePolicy,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxEdgeCluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$distributedSwitch,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$podCIDRs,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceCIDR,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$externalIngressCIDRs,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$externalEgressCIDRs,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$masterDnsSearchDomain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$workerDnsServers,
        [Parameter (Mandatory = $false)] [ValidateRange(300,18000)]$ConfigurationTimeoutSeconds=3600,
        [Parameter (Mandatory = $false)] [Switch]$skipValidation,
        [Parameter (Mandatory = $false)] [Switch]$validateOnly
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (!(Get-WMCluster -cluster $cluster -ErrorAction Ignore)) {
                                Request-vSphereApiToken -Fqdn $vcfVcenterDetails.fqdn -Username $vcfVcenterDetails.ssoadmin -Password $vcfVcenterDetails.ssoAdminPass | Out-Null
                                if (($vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                                    if (Test-NSXTConnection -server $vcfNsxtDetails.fqdn) {
                                        if (Test-NSXTAuthentication -server $vcfNsxtDetails.fqdn -user $vcfNsxtDetails.adminUser -pass $vcfNsxtDetails.adminPass) {
                                            [bool]$inputParameterValidation = $true
                                            #Check SkipValidation parameter
                                            if (($SkipValidation.isPreset)) {
                                                # Validate if vCenter uses 'local'
                                                if ($vcfVcenterDetails.fqdn) {
                                                    if (($vcfVcenterDetails.fqdn.split(".")[$_.count-1] -eq "local") -and ($masterDnsSearchDomain.split(".")[$_.count-1] -ne "local")) {
                                                        Write-Warning "'local' domain detected in ($(vcfVcenterDetails.fqdn)), make sure you have provided masterDnsSearchDomain ($masterDnsSearchDomain) to match"
                                                    }
                                                }
                                                # Validate management network inputs
                                                # Valid Starting IP Address is an actual IPv4 address
                                                if ($managementNetworkStartIpAddress) {
                                                    if (!(Test-IPaddressArray -IPaddressArray $managementNetworkStartIpAddress)) {
                                                        Write-Error "Invalid Management Network Start IP address ($managementNetworkStartIpAddress): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Valid Subnet Mask
                                                if ($managementNetworkSubnetMask) {
                                                    if (!(Test-IPaddressArray -IPaddressArray $managementNetworkSubnetMask)) {
                                                        Write-Error "Management Network Subnet Mask ($managementNetworkSubnetMask) validation failed: PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate Gateway IP Address is an actual IPv4 address and exists in the same subnet as the management starting address
                                                if ($managementNetworkGateway) {
                                                    Try {
                                                        if (Test-IPaddressArray $managementNetworkGateway) {
                                                            #Validate the Gateway IP address and the starting IP address are in the same subnet
                                                            $checkManagementNetworkGatewayInSubnet = $null
                                                            Try {
                                                                $checkManagementNetworkGatewayInSubnet = Test-IpAddress -IpAddress $managementNetworkGateway -Subnet "$managementNetworkStartIpAddress/$managementNetworkCidr"
                                                            } Catch {}
                                                            if ($checkManagementNetworkGatewayInSubnet.Validated -eq $false) {
                                                                Write-Error "Cannot validate the gateway IP address for the Management Network ($managementNetworkGateway) is from the same subnet as the Management Network Starting IP Address ($managementNetworkStartIpAddress/$managementNetworkCidr): PRE_VLALIDATION_FAILED"
                                                                $inputParameterValidation = $false
                                                            }
                                                        }
                                                    } Catch {
                                                        Write-Error "Invalid IP address ($managementNetworkGateway) : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate Management Virtual Network (dvPortGroup) exists
                                                if ($ManagementVirtualNetwork) {
                                                    Try {
                                                        $checkManagementVirtualNetwork = Get-VirtualNetwork -Name $ManagementVirtualNetwork -ErrorAction SilentlyContinue
                                                    } Catch {
                                                        #Do nothing
                                                    }
                                                    if (!$checkManagementVirtualNetwork -or !$managementVirtualNetwork) {
                                                        Write-Error "Invalid Management Virtual Network ($ManagementVirtualNetwork): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    } 
                                                }
                                                # Validate Ephemeral Storage Policy exists
                                                if ($ephemeralStoragePolicy){
                                                    $checkEphemeralStoragePolicy = $null
                                                    Try {
                                                        $checkEphemeralStoragePolicy = Get-SpbmStoragePolicy -Name $EphemeralStoragePolicy -ErrorAction SilentlyContinue
                                                    } Catch {
                                                        #Do nothing
                                                    }
                                                    if (!$checkEphemeralStoragePolicy -or !$ephemeralStoragePolicy) {
                                                        Write-Error "Invalid Ephemeral Storage Policy ($EphemeralStoragePolicy): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate Image Storage Policy exists
                                                if ($imageStoragePolicy) {
                                                    $checkImageStoragePolicy = $null
                                                    Try {
                                                        $checkImageStoragePolicy = Get-SpbmStoragePolicy -Name $ImageStoragePolicy -ErrorAction SilentlyContinue
                                                    } Catch {
                                                        #Do nothing
                                                    }
                                                    if (!$checkImageStoragePolicy -or !$imageStoragePolicy) {
                                                        Write-Error "Invalid Image Storage Policy ($ImageStoragePolicy): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate Master Storage Policy exists
                                                if ($masterStoragePolicy) {
                                                    $checkMasterStoragePolicy = $null
                                                    Try {
                                                        $checkMasterStoragePolicy = Get-SpbmStoragePolicy -Name $MasterStoragePolicy -ErrorAction SilentlyContinue
                                                    }Catch {
                                                        #Do nothing
                                                    }
                                                    if (!$checkMasterStoragePolicy -or !$masterStoragePolicy) {
                                                        Write-Error "Invalid Master Storage Policy ($MasterStoragePolicy): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate NSX Edge Cluster exists and lookup ID. TBD chech status of the Edge Cluster and TNs
                                                if ($nsxEdgeCluster) {
                                                    $nsxEdgeClusterId = $null
                                                    $checkNsxEdgeCluster = $null
                                                    Try {
                                                        $checkNsxEdgeCluster = Get-NsxEdgeCluster -Name $nsxEdgeCluster -ErrorAction SilentlyContinue
                                                        $nsxEdgeClusterId = $checkNsxEdgeCluster.Id
                                                    } Catch {
                                                        #Do nothing
                                                    }
                                                    if (!$nsxEdgeClusterId -or !$nsxEdgeCluster) {
                                                        Write-Error "Invalid NSX Edge Cluster ($NsxEdgeCluster): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate control plane NTP servers exist and are functional
                                                if ($masterNtpServers) {
                                                    Foreach ($masterNtpServer in $masterNtpServers) {
                                                        $checkNtpServer = $null
                                                        $checkNtpServer = Test-ntpServer $masterNtpServer
                                                        if (!($checkNtpServer)) {
                                                            Write-Error "Invalid master NTP server ($masterNtpServer) : PRE_VALIDATION_FAILED"
                                                            $inputParameterValidation = $false
                                                        }
                                                    }
                                                }
                                                # Validate control plane DNS servers exist and are functional
                                                if ($masterDnsServers) {
                                                    $checkDnsServers = $null
                                                    $checkDnsServers = Test-DnsServers $masterDnsServers
                                                    if (!($checkDnsServers)) {
                                                        Write-Error "Invalid master dns servers ($masterDnsServers) : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate worker DNS servers exist and are functional
                                                if ($workerDnsServers) {
                                                    $checkDnsServers = $null
                                                    $checkDnsServers = Test-DnsServers $workerDnsServers
                                                    if (!($checkDnsServers)) {
                                                        Write-Error "Invalid worker dns servers ($workerDnsServers) : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate ContentLibrary exists
                                                #Full validation (checking type, subscription, etc.) is TBD
                                                if ($contentLibrary) {
                                                    $checkContentLibrary = $null
                                                    Try {
                                                        $checkContentLibrary = Get-SubscribedLibrary -Name $contentLibrary -ErrorAction SilentlyContinue
                                                    } Catch {
                                                        Debug-ExceptionWriter -object $_
                                                    }
                                                    if ($checkContentLibrary.Name -ne $contentLibrary -or !$contentLibrary) {
                                                        Write-Error "Invalid Content Library ($contentLibrary): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    } 
                                                }
                                                # Validate Distributed Virtual Switch exists
                                                if ($distributedSwitch) {
                                                    $checkDistributedSwitch = $null
                                                    Try {
                                                        $checkDistributedSwitch = Get-VDSwitch -Name $distributedSwitch -ErrorAction SilentlyContinue
                                                    } Catch {
                                                        Debug-ExceptionWriter -object $_
                                                    }
                                                    if ($checkDistributedSwitch.Name -ne $distributedSwitch -or !$distributedSwitch) {
                                                        Write-Error "Invalid Virtual Distributed Switch ($distributedSwitch): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    } 
                                                } 
                                                # Validates Pod subnet inputs are formatted correctly and sized to meet minimum requirements
                                                if ($podCIDRs) {
                                                    $checkPodCidr = $null
                                                    $checkPodCidr = Test-WMSubnetInput -Subnet $podCIDRs -SubnetType "Pod"
                                                    if (!($checkPodCidr)) {
                                                        Write-Error "Invalid podCIDRs ($podCIDRs) : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validates Service subnet inputs are formatted correctly and sized to meet minimum requirements
                                                if ($serviceCIDR) {
                                                    $checkServiceCidr = $null
                                                    $checkServiceCidr = Test-WMSubnetInput -Subnet $serviceCIDR -SubnetType "Service"
                                                    if (!($checkServiceCidr)) {
                                                        Write-Error "Invalid ServiceCIDR ($serviceCIDR) : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validates Ingress subnet inputs are formatted correctly and sized to meet minimum requirements
                                                if ($externalIngressCIDRs) {
                                                    $checkIngressCidr = $null
                                                    $checkIngressCidr = Test-WMSubnetInput -Subnet $serviceCIDR -SubnetType "Ingress"
                                                    if (!($checkIngressCidr)) {
                                                        Write-Error "Invalid IngressCIDR ($externalIngressCIDRs) : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validates Egress subnet inputs are formatted correctly and sized to meet minimum requirements
                                                if ($externalEgressCIDRs) {
                                                    $checkEgressCidr = $null
                                                    $checkEgressCidr = Test-WMSubnetInput -Subnet $externalEgressCIDRs -SubnetType "Egress"
                                                    if (!($checkEgressCidr)) {
                                                        Write-Error "Invalid EgressCIDR ($externalEgressCIDRs) : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate control plane Kubernetes API endpoint is valid and in DNS
                                                # TBD as this is not mandatory parameter
                                                if ($masterDnsName) {
                                                    foreach ($dnsName in $masterDnsName) {
                                                        $checkDnsName = $null
                                                        Try {
                                                            $checkDnsName = Resolve-DnsName -Name $DnsName -Type A -QuickTimeout -ErrorAction Stop
                                                        } Catch [System.ComponentModel.Win32Exception] {
                                                            Write-Error "Invalid control plane DNS name ($DnsName): PRE_VALIDATION_FAILED"
                                                            $inputParameterValidation = $false
                                                        }
                                                        if ($checkDnsName) {
                                                            $checkMasterIpAddress = $null
                                                            Try {
                                                                $checkMasterIpAddress = Test-IpAddress -IpAddress $checkDnsName.Answers[0].Address.IPAddressToString -Subnet $externalIngressCIDRs
                                                            } Catch {
                                                                #Do nothing
                                                            }
                                                            if ($checkMasterIpAddress.Validated -eq $false) {
                                                                Write-Error -Message "Cannot validate the IP address for $DnsName ($DnsNameIpAddress) is from the external ingress CIDR ($externalIngressCIDRs). : PRE_VALIDATION_FAILED"
                                                                $inputParameterValidation = $false
                                                            }
                                                        }
                                                    }
                                                }
                                                # Validate master DNS search domain is formatted correctly and exists in DNS
                                                if ($masterDnsSearchDomain) {
                                                    $checkMasterDnsSearchDomain = $null
                                                    Try {
                                                        $checkMasterDnsSearchDomain = Resolve-DnsName -Name $masterDnsSearchDomain -Type A -QuickTimeout -ErrorAction Stop
                                                    } Catch [System.ComponentModel.Win32Exception] {
                                                        Write-Error "Invalid control plane DNS search domain ($masterDnsSearchDomain): PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # Validate vSphere license is in place
                                                Try {
                                                    $checkLicense = Get-WMLicenseStatus -server $server -domain $domain -ErrorAction SilentlyContinue
                                                    if ($checkLicense.namespaces_licensed -eq $false) {
                                                        Write-Error -Message "The vSphere license applied to cluster $cluster does not support Workload Management or is expired. Please resolve this and try again : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    } elseif ($checklicense.namespaces_supported -eq $false) {
                                                        Write-Error -Message "The cluster $cluster does not support Workload Management. Please resolve this and try again. : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                } Catch {
                                                    Debug-ExceptionWriter -object $_
                                                }
                                                # Validate the cluster is present
                                                if ($cluster) {
                                                    $checkCluster = $null
                                                    Try {
                                                        $checkCluster = Get-Cluster -Name $cluster -ErrorAction SilentlyContinue
                                                    } Catch {
                                                        #Do nothing
                                                    }
                                                    if (!$checkCluster -or ($checkCluster.Name -ne $cluster)) {
                                                        Write-Error "Invalid vSphere cluster $cluster. : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                    $checkWmCluster = $null
                                                    Try {
                                                        $checkWmCluster = Get-WMCluster -Cluster $cluster -ErrorAction SilentlyContinue
                                                    } Catch {
                                                        #Do nothing
                                                    }
                                                    if ($checkWmCluster) {
                                                        Write-Error "Cluster $cluster is already enabled for Workload management : PRE_VALIDATION_FAILED"
                                                        $inputParameterValidation = $false
                                                    }
                                                }
                                                # If any of the prevalidation failed
                                                if ($inputParameterValidation) {
                                                    Write-Output "Pre-validation : SUCESSFULL" 
                                                } else {
                                                    Write-Error "At least one input parameter validation failed : PRE_VALIDATION_FAILED"
                                                    Break
                                                }
                                            }
                                            # TBD MasterDnsServerIpAddress = $masterDnsServers
                                            if ($inputParameterValidation) {
                                                $internalWMClusterInput = @{
                                                    SizeHint                          = $SizeHint
                                                    ManagementVirtualNetwork          = (Get-VirtualNetwork -Name $managementVirtualNetwork)
                                                    ManagementNetworkMode             = $managementNetworkMode
                                                    ManagementNetworkStartIpAddress   = $managementNetworkStartIpAddress
                                                    ManagementNetworkAddressRangeSize = $managementNetworkAddressRangeSize
                                                    ManagementNetworkGateway          = $managementNetworkGateway
                                                    ManagementNetworkSubnetMask       = $managementNetworkSubnetMask
                                                    MasterDnsNames                    = $masterDnsName
                                                    MasterNtpServer                   = $masterNtpServers
                                                    Cluster                           = (Get-Cluster -Name $cluster)
                                                    ContentLibrary                    = $contentLibrary
                                                    EphemeralStoragePolicy            = (Get-SpbmStoragePolicy -Name $ephemeralStoragePolicy)
                                                    ImageStoragePolicy                = (Get-SpbmStoragePolicy -Name $imageStoragePolicy)
                                                    MasterStoragePolicy               = (Get-SpbmStoragePolicy -Name $masterStoragePolicy)
                                                    NsxEdgeClusterId                  = ((Get-NsxEdgeCluster -Name $nsxEdgeCluster).id)
                                                    DistributedSwitch                 = (Get-VDSwitch -Name $distributedSwitch)
                                                    PodCIDRs                          = $podCIDRs
                                                    ServiceCIDR                       = $serviceCIDR
                                                    ExternalIngressCIDRs              = $externalIngressCIDRs
                                                    ExternalEgressCIDRs               = $externalEgressCIDRs
                                                    WorkerDnsServer                   = $workerDnsServers
                                                    MasterDnsServerIpAddress          = $masterDnsServers
                                                    MasterDnsSearchDomain             = $masterDnsSearchDomain
                                                }
                                            }
                                            if ($ValidateOnly.isPresent) {
                                                Write-Output "Validation completed : SUCCESSFUL"
                                            } else {
                                                Enable-WMCluster @internalWMClusterInput -RunAsync -ConfigurationTimeoutSeconds $ConfigurationTimeoutSeconds | Out-Null
                                                Write-Output  "Submitted Creation of Supervisor Cluster $cluster in vCenter Server $($vcfVcenterDetails.fqdn). This may take a while to complete. Operation will timeout after ($ConfigurationTimeoutSeconds) seconds"
                                                $startSleep = 300
                                                $SleepTime = 60
                                                Start-Sleep $startSleep
                                                if (Get-WMCluster -Cluster $cluster -ErrorAction SilentlyContinue) {
                                                    Watch-WmClusterConfigStatus -wmClusterName $cluster -sleepTime $SleepTime -retriesCount (($ConfigurationTimeoutSeconds-$startSleep)/$sleepTime)
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                Write-Warning "Deploying Kubernetes Supervisor Cluster, already deployed: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Enable-SupervisorCluster

Function Undo-SupervisorCluster {
    <#
        .SYNOPSIS
        Remove Supervisor Cluster

        .DESCRIPTION
        The Undo-SupervisorCluster cmdlet removes the Supervisor Cluster from a Workload Domain. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Performs validation of in puts unless skipped using a switch
        - Disables Workload Management on the vSphere cluster

        .EXAMPLE
        Undo-SupervisorCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01
        This example disables Workload Management on a vSphere Cluster in workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$RunAsync
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        if (Get-WMCluster -cluster $cluster -ErrorAction Ignore) {
                                            if (!$PsBoundParameters.ContainsKey("RunAsync")) {
                                                Disable-WMCluster -WMCluster $cluster -RunAsync -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                            } else {
                                                Disable-WMCluster -WMCluster $cluster -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                            }
                                            if (!(Get-WMCluster -cluster $cluster -ErrorAction Ignore)) {
                                                Write-Output "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Removing Supervisor Cluster ($cluster) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED"
                                        }
                                    }
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SupervisorCluster

Function New-SupervisorClusterCSR {
    <#
        .SYNOPSIS
        Create a new certificate signing request for the defined Supervisor Cluster

        .DESCRIPTION
        The New-SupervisorClusterCSR cmdlet creates a new certificate signing request for the defined Supervisor
        Cluster. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Requests the certificate signing request file

        .EXAMPLE
        New-SupervisorClusterCSR -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -commonName sfo-m01-cl01.sfo.rainpole.io -organization Rainpole -organizationalUnit Rainpole -country US -stateOrProvince California -locality "Palo Alto" -adminEmailAddress admin@rainpole.io -keySize 2048 -filePath ".\SupervisorCluster.csr"
        This example returns a certificate signing request for the Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$commonName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organization,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organizationalUnit,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$country,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$stateOrProvince,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$locality,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmailAddress,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$keySize,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        if ($PsBoundParameters.ContainsKey("keySize")) {
                                            Request-WMClusterCSR -cluster $cluster -commonName $commonName -organization $organization -organizationalUnit $organizationalUnit -country $country -stateOrProvince $stateOrProvince -locality $locality -adminEmailAddress $adminEmailAddress -keySize $keySize -filePath $filePath | Out-Null
                                        } else {
                                            Request-WMClusterCSR -cluster $cluster -commonName $commonName -organization $organization -organizationalUnit $organizationalUnit -country $country -stateOrProvince $stateOrProvince -locality $locality -adminEmailAddress $adminEmailAddress -filePath $filePath | Out-Null
                                        }
                                        if (Test-Path -Path $filePath) {
                                            Write-Output "Creating Certificate Signing Request (.csr) file for ($commonName) to file ($filePath): SUCCESSFUL"
                                        } else {
                                            Write-Error "Creating Certificate Signing Request (.csr) file for ($commonName) to file ($filePath): POST_VALIDATION_FAILED"
                                        }
                                    }
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-SupervisorClusterCSR

Function Request-SignedCertificate {
    <#
        .SYNOPSIS
        Request a Signed Certificate from a Microsoft Enterprise Certificate Authority by providing generated
        Certificate Signing Request (CSR) file.

        .DESCRIPTION
        The Request-SignedCertificate cmdlet requests a Signed Certificate from a Microsoft Enterprise Certificate
        Authority by providing Certificate Signing Request (CSR) file. Issued certificate is written to Base64-encoded
        output file.

        .EXAMPLE
        Request-SignedCertificate -mscaComputerName dc-rpl01.rainpole.io -mscaName rainpole-DC-RPL01-CA -domainUsername "administrator@rainpole.io" -domainPassword "VMw@re1!" -certificateTemplate VMware -certificateRequestFile "c:\temp\SupervisorCluster.csr" -CertificateFile "c:\temp\SupervisorCluster.cer"
        This example requests a Signed Certificate from a Microsoft Enterprise Certificate Authority providing certificate signing request in file "c:\temp\SupervisorCluster.csr" and if the CA policy is configured to automaticaly issue certificate the certificate will be issued to Base64-encoded output file "c:\temp\SupervisorCluster.cer"
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$mscaComputerName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$mscaName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainUsername,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainPassword,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificateTemplate = "webserver",
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateRequestFile,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateFile,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$SkipValidation,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$ValidateOnly
    )

    Try {
        [Bool]$preValidation = $true
        if (!($SkipValidation.IsPresent)) {
            # Validate if CSR exists
            if (!(Test-Path -Path $certificateRequestFile -ErrorAction SilentlyContinue)) {
                Write-Error "Certificate Signning Request (CSR) file ($certificateRequestFile) not found: PRE_VALIDATION_FAILED"
                $preValidation = $false
            }
            # Validate if output file exisits
            if ((Test-Path -Path $certificateFile -ErrorAction SilentlyContinue)) {
                Write-Error "Certificate file ($certificateFile) already exists: PRE_VALIDATION_FAILED"
                $preValidation = $false
            }
            # Validate if can get Win32_ComputerSystem
            if ((Get-WmiObject Win32_ComputerSystem -ComputerName $mscaComputerName -ErrorAction SilentlyContinue).Status -ne "OK") {
                Write-Error "Getting Win32_ComputerSystem object for ($mscaComputerName): PRE_VALIDATION_FAILED"
                $preValidation = $false
            }
            # Validate if can connect on port 135
            if ((Test-NetConnection -ComputerName $mscaComputerName -Port 135 -ErrorAction SilentlyContinue).TcpTestSucceeded -ne $true) {
                Write-Error "Connecting to ($mscaComputerName) on port 135: PRE_VALIDATION_FAILED"
                $preValidation = $false
            }
        }
        if ($preValidation) {
            if (!($ValidateOnly.isPresent)) {
                $CertificateAttributes = "CertificateTemplate:$certificateTemplate"
                $commandToExecute = "certreq -submit -f -q -UserName $domainUsername -p $domainPassword -config `"$mscaComputerName`\$mscaName`" -attrib `"$CertificateAttributes`" $certificateRequestFile $certificateFile"
                $resultExecution = Invoke-Expression -Command $commandToExecute
                Start-Sleep 5
                if ($resultExecution -match "(Issued)") {
                    Write-Output "Issued certificate ($certificateFile): SUCCESSFUL"
                } else {
                    Write-Error "Certificate issuing to file ($certificateFile) failed with ($resultExecution): FAILED"
                    Break
                }
            } else {
                Write-Output "Pre-validate Only: SUCCESSFUL"
            }
        } else {
            Write-Error "At least one Pre-Validation check failed: PRE_VALIDATION_FAILED"
            Break
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Request-SignedCertificate

Function Install-SupervisorClusterCertificate {
    <#
        .SYNOPSIS
        Add a signed TLS certificate for the defined Supervisor Cluster

        .DESCRIPTION
        The Install-SupervisorClusterCertificate cmdlet adds a signed TLS certificate for the defined Supervisor
        Cluster. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Installs the Signed Certificate to the Supervisor Cluster

        .EXAMPLE
        Install-SupervisorClusterCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -Cluster sfo-w01-cl01 -FilePath ".\SupervisorCluster.cer"
        This example applies the signed TLS certificate to Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$filePath
    )

    if (!$PsBoundParameters.ContainsKey("filePath")) {
        $filePath = Get-ExternalFileName -title "Select the Supervisor Cluster Certificate File (.cer)" -fileType "cer" -location "default"
    } elseif ($PsBoundParameters.ContainsKey("filePath")) {
        if (!(Test-Path -Path $filePath)) {
            Write-Error "Certificate (cer) file for the Supervisor Cluster '$filePath' File Not Found"
            Break
        }
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                Request-vSphereApiToken -fqdn $vcfVcenterDetails.fqdn -username $vcfVcenterDetails.ssoAdmin -password $vcfVcenterDetails.ssoAdminPass | Out-Null
                                $response = Install-WMClusterCertificate -cluster $cluster -filePath $filePath
                                if ($response -match "successfully applied") {
                                    Write-Output "Installing Signed Certificate ($filePath) to Supervisor Cluster ($cluster): SUCCESSFUL"
                                } else {
                                    Write-Error "Installing Signed Certificate ($filePath) to Supervisor Cluster ($cluster): POST_VALIDATION_FAILED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-SupervisorClusterCertificate

Function Add-SupervisorClusterLicense {
    <#
        .SYNOPSIS
        Adds a Supervisor Cluster license

        .DESCRIPTION
        The Add-SupervisorClusterLicense cmdlet adds a Supervisor Cluster licence.. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Adds a new Supervisor Cluster license

        .EXAMPLE
        Add-SupervisorClusterLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -Cluster sfo-w01-cl01 -LicenseKey "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
        This example adds a license to the Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$licenseKey
    )
    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        $clusterId = ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).clusters | Where-Object {$_.id -eq (Get-VCFCluster | Where-Object {$_.name -eq $cluster}).id}).id
                        if ($clusterId){
                            if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                                if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                    Connect-vSphereMobServer -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass 
                                    $licenseExists = $null
                                    Try {
                                        $licenseExists = Get-VCFLicenseKey -key $licenseKey -ErrorAction SilentlyContinue
                                    } Catch {
                                        # Do nothing
                                    }
                                    if (!($licenseExists)) {
                                        New-VCFLicenseKey -key $licenseKey -productType WCP -description "WCP license"
                                        Start-Sleep 10
                                        if (Get-VCFLicenseKey -key $licenseKey) {
                                            Write-Output "Adding license key ($licenseKey) in SDDC manager ($sddcManager): SUCCESSFUL"
                                            $clusterId = ((Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).clusters | Where-Object {$_.id -eq (Get-VCFCluster | Where-Object {$_.name -eq $cluster}).id}).id
                                            
                                            $uri = "https://$sddcManager/v1/wcps/$clusterId/licensing"
                                            $json = '{"licenseKey": "'+ $licenseKey +'"}'
                                            $response = Invoke-RestMethod -Method POST -URI $uri -headers $headers -ContentType application/json -body $json
                                            Try {
                                                $taskStatus = $null
                                                Do {
                                                    $taskStatus = (Get-VCFTask -id $response.id).status
                                                    Start-Sleep 10
                                                } While ($taskStatus -eq "In Progress")
                                                if ($taskStatus -eq "Successful") {
                                                    Write-Output "Assign license key ($licenseKey) to Supervisior cluster ($cluster): SUCCESSFUL"
                                                } else {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key ($licenseKey) was properly added to Supervisor Cluster ($cluster): POST_VALIDATION_FAILED"),
                                                            'Add-SupervisorClusterLicense',
                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                            ""
                                                        )
                                                    )
                                                } 
                                            } Catch {
                                                Debug-ExceptionWriter -object $_
                                            }
                                        } else {
                                            $PSCmdlet.ThrowTerminatingError(
                                                [System.Management.Automation.ErrorRecord]::new(
                                                    ([System.Management.Automation.GetValueException]"Unable to validate license key ($licenseKey) was properly added to Supervisor Cluster ($cluster): POST_VALIDATION_FAILED"),
                                                    'Add-SupervisorClusterLicense',
                                                    [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                    ""
                                                )
                                            )
                                        }
                                    } else {
                                        Write-Warning "License key ($licenseKey) already exists in SDDC manager ($sddcManager) inventory: SKIPPED"
                                    }
                                    
                                }
                                Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                            }
                        } else {
                            $PSCmdlet.ThrowTerminatingError(
                                [System.Management.Automation.ErrorRecord]::new(
                                    ([System.Management.Automation.ItemNotFoundException]"Unable to find cluster named ($cluster) in the Workload Domain named ($domain) in the invenotry of SDDC Manager ($server): PRE_VALIDATION_FAILED"),
                                    'Add-SupervisorClusterLicense',
                                    [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                    ""
                                )
                            )
                        }
                    }
                } else {
                    $PSCmdlet.ThrowTerminatingError(
                        [System.Management.Automation.ErrorRecord]::new(
                            ([System.Management.Automation.ItemNotFoundException]"Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"),
                            'Add-SupervisorClusterLicense',
                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                            ""
                        )
                    )
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-SupervisorClusterLicense

Function Add-Namespace {
    <#
        .SYNOPSIS
        Creates a Namespace and applies extra configuration to it

        .DESCRIPTION
        The Add-Namespace cmdlet creates a Namespace and applies its configuration.. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Creates the Namespace

        .EXAMPLE
        Add-Namespace -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -namespace sfo-w01-ns01 -storagePolicy vsphere-with-tanzu-storage-policy
        This example creates a Namespace named sfo-w01-ns01 in the Supervisor Cluster sfo-w01-cl01 with a vSphere Storage Policy vsphere-with-tanzu-storage-policy
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$storagePolicy
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (!(Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue)) {
                                    if (Get-Cluster -Name $cluster -ErrorAction SilentlyContinue) {
                                        if (Get-SpbmStoragePolicy -Name $storagePolicy -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) {
                                            New-WMNamespace -Name $namespace -Cluster $cluster | Out-Null
                                            if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) {
                                                New-WMNamespaceStoragePolicy -Namespace $namespace -StoragePolicy $storagePolicy | Out-Null
                                                Write-Output "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Unable to find vSphere Storage Policy ($storagePolicy) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error  "Unable to find Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Creating Namespace ($namespace) in Supervisor Cluster ($cluster) in vCenter Server ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-Namespace

Function Undo-Namespace {
    <#
        .SYNOPSIS
        Remove a Namespace

        .DESCRIPTION
        The Undo-Namespace cmdlet removes a Namespace from the Supervisor Cluster.. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes a Namespace

        .EXAMPLE
        Undo-Namespace -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -namespace sfo-w01-ns02
        This example removes the Namespace named sfo-w01-ns02
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-WMNamespace -Name $namespace -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) {
                                    Remove-WMNamespace -Namespace $namespace -Server $vcfVcenterDetails.fqdn -Confirm:$false | Out-Null
                                    if (!(Get-WMNamespace -Name $namespace -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) {
                                        Write-Output "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing Namespace ($namespace) from vCenter Server ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-Namespace

Function Add-NamespacePermission {
    <#
        .SYNOPSIS
        Adds permissions to a Namespace

        .DESCRIPTION
        The Add-NamespacePermission cmdlet adds permissions to a Namespace. The cmdlet connects to SDDC Manager using
        the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Assigns permissions to a Namespace

        .EXAMPLE
        Add-NamespacePermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-w01 -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -namespace sfo-w01-ns01 -principal gg-kub-admins -role edit -type group
        This example adds the edit role to the group gg-kub-admins in the domain sfo.rainpole.io to the Namespace sfo-w01-ns01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateSet("edit", "view")] [String]$role,
        [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type
    )

    Try {
        $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue
        if ($checkAdAuthentication[1] -match "Authentication Successful") {
            $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force
            $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass)
            if (Test-VCFConnection -server $server) {
                if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                    if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) {
                        if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) {
                            if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                                if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                    if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) {
                                        if ($type -eq "group") { $adObjectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) }
                                        elseif ($type -eq "user") { $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) }
                                        if ($adObjectCheck) {
                                            if (!(Get-WMNamespacePermission -Namespace $namespace -Domain $domain -PrincipalName $principal)) {
                                                New-WMNamespacePermission -Namespace $namespace -Role $role -Domain $domain -PrincipalType $type -PrincipalName $principal | Out-Null
                                                if (Get-WMNamespacePermission -Namespace $namespace -Domain $domain -PrincipalName $principal) {
                                                    Write-Output "Assigning Role ($role) to $type ($principal) in Namespace ($namespace): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Assigning Role ($role) to $type ($principal) in Namespace ($namespace): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                Write-Warning "Assigning Role ($role) to $type ($principal) in Namespace ($namespace), already assigned: SKIPPED"
                                            }
                                        } else {
                                            Write-Error "Active Directory $type ($principal) not found in the Active Directory Domain: PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                    }
                                }
                                Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    } else {
                        Write-Error "Unable to find Workload Domain named ($sddcDomain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                    }
                }
            }
        } else {
            Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED"
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-NamespacePermission

Function Undo-NamespacePermission {
    <#
        .SYNOPSIS
        Remove permissions from a Namespace

        .DESCRIPTION
        The Undo-NamespacePermission cmdlet removes a permissions from a Namespace. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes permissions from a Namespace

        .EXAMPLE
        Undo-NamespacePermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-w01 -namespace sfo-w01-ns01 -principal gg-kub-admins
        This example removes the edit role from the Namespace sfo-w01-ns01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-WMNamespace -Name $namespace -ErrorAction SilentlyContinue) {
                                    if (Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal) {
                                        Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal | Remove-WMNamespacePermission -Confirm:$false | Out-Null
                                        if (!(Get-WMNamespacePermission -Namespace $namespace -PrincipalName $principal)) {
                                            Write-Output "Removing access for principal ($principal) from Namespace ($namespace): SUCCESSFUL"
                                        } else {
                                            Write-Error "Removing access for principal ($principal) from Namespace ($namespace): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Removing access for principal ($principal) from Namespace ($namespace), does not exist: SKIPPED"
                                    }
                                } else {
                                    Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($sddcDomain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-NamespacePermission

Function Enable-Registry {
    <#
        .SYNOPSIS
        Enable the embedded Harbor Registry on a Supervisor Cluster

        .DESCRIPTION
        The Enable-Registry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Enables the embedded Harbour Registry on the Supervisor Cluster

        .EXAMPLE
        Enable-Registry -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -storagePolicy vsphere-with-tanzu-storage-policy
        This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 with vSPhere Storage Policy vsphere-with-tanzu-policy
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$storagePolicy
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.Name -eq $domain }).clusters.id) }).Name
                                        if (!(Get-WMRegistry -cluster $cluster -ErrorAction SilentlyContinue)) {
                                            if (Get-SpbmStoragePolicy -Name $storagePolicy -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) {
                                                Enable-WMRegistry -cluster $cluster -StoragePolicy $storagePolicy | Out-Null
                                                Do {
                                                    $configStatus = Get-WMRegistry -cluster $cluster | Get-WMRegistryHealth
                                                } Until ($configStatus -eq "RUNNING")
                                                if (Get-WMRegistry -cluster $cluster -ErrorAction SilentlyContinue) {
                                                    Write-Output "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                Write-Error "Unable to find vSphere Storage Policy ($storagePolicy) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Enabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster), already performed: SKIPPED"
                                        }
                                    }
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Enable-Registry

Function Undo-Registry {
    <#
        .SYNOPSIS
        Disable the embedded Harbor Registry on a Supervisor Cluster

        .DESCRIPTION
        The Undo-Registry cmdlet disables the embedded Harbor Registry on a Supervisor Cluster. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Disables the Harbour Registry on the Supervisor Cluster

        .EXAMPLE
        Undo-Registry -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01
        This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 with vSPhere Storage Policy vsphere-with-tanzu-policy
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.Name -eq $domain }).clusters.id) }).Name
                                        if (Get-WMRegistry -cluster $cluster -ErrorAction Ignore) {
                                            Remove-WMRegistry -cluster $cluster | Out-Null
                                            Do {
                                                $configStatus = Get-WMRegistry -cluster $cluster -ErrorAction Ignore #| Get-WMRegistryHealth -ErrorAction Ignore
                                            } Until (!($configStatus))
                                            if (!(Get-WMRegistry -cluster $cluster -ErrorAction Ignore)) {
                                                Write-Output "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): SUCCESSFUL"
                                            } else {
                                                Write-Error "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Disabling Embedded Harbour Registry in vCenter Server ($($vcfVcenterDetails.fqdn)) for Cluster ($cluster), already performed: SKIPPED"
                                        }
                                    }
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-Registry

Function Add-NamespaceVmClass {
    <#
        .SYNOPSIS
        Add a Virtual Machine class to a Namespace

        .DESCRIPTION
        The Add-NamespaceVmClass cmdlet adds a Virtual Machine Class to a Namespace. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Adds a VM Class to the Namespace

        .EXAMPLE
        Add-NamespaceVmClass -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -namespace sfo-w01-tkc01 -vmClass guaranteed-small
        This example adds the VM Class guaranteed-small to Supervisor Namespace sfo-tkc-01 in Workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace,
        [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Test-vSphereApiConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-vSphereApiAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        if (Get-WMNamespace -Name $namespace -ErrorAction Ignore) {
                                            if (!(Get-VMClass -namespace $namespace | Where-Object {$_ -eq $vmClass})) {
                                                Add-VMClass -namespace $namespace -vmClass $vmClass | Out-Null
                                                if (Get-VMClass -namespace $namespace | Where-Object {$_ -eq $vmClass}) {
                                                    Write-Output "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                Write-Warning "Adding Virtual Machine Class ($vmClass) to Namespace ($namespace), already exists: SKIPPED"
                                            }                      
                                        } else {
                                            Write-Error "Unable to find Namespace ($namespace) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Write-Error $_.Exception.Response
    }
}
Export-ModuleMember -Function Add-NamespaceVmClass

Function Add-TanzuKubernetesCluster {
    <#
        .SYNOPSIS
        Create a new Tanzu Kubernetes Cluster on a Supervisor Cluster

        .DESCRIPTION
        The Add-TanzuKubernetesCluster cmdlet creates a new Tanzu Kubernetes Cluster on a Supervisor Cluster. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Creates a Tanzu Kubernetes Cluster

        .EXAMPLE
        Add-TanzuKubernetesCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -yaml .\SampleYaml\sfo-w01-tkc01-cluster.yaml
        This example creates a Tanzu Kubernetes cluster based on the YAML file .\SampleYaml\sfo-w01-tkc01-cluster.yaml as the vSphere SSO user administrator@vsphere.local on Supervisor Cluster sfo-w01-cl01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$yaml
    )

    if (!$PsBoundParameters.ContainsKey("yaml")) {
        $yaml = Get-ExternalFileName -title "Select the YAML File (.yaml)" -fileType "yaml" -location "default"
    } else {
        if (!(Test-Path -Path $yaml)) {
            Write-Error  "YAML File '$yaml' File Not Found"
            Break
        }
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                Connect-WMCluster -cluster $cluster -user $user -pass $pass | Out-Null
                                New-TanzuKubernetesCluster -YAML $yaml | Out-Null
                                Write-Output "Creating Tanzu Kubernetes Cluster in Supervisor Cluster ($cluster) using YAML ($yaml): SUCCESSFUL"
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                            Disconnect-WMCluster | Out-Null
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-TanzuKubernetesCluster

Function Undo-TanzuKubernetesCluster {
    <#
        .SYNOPSIS
        Remove a Tanzu Kubernetes Cluster

        .DESCRIPTION
        The Undo-TanzuKubernetesCluster cmdlet removes a new Tanzu Kubernetes Cluster. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes a Tanzu Kubernetes Cluster

        .EXAMPLE
        Undo-TanzuKubernetesCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -cluster sfo-w01-cl01 -namespace sfo-w01-tkc01 -tkc sfo-w01-tkc01
        This example removes a Tanzu Kubernetes Cluster from the a Supervisor Cluster
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tkc
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Get-WMCluster -cluster $cluster -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore) {
                                    Connect-WMCluster -cluster $cluster -user $user -pass $pass | Out-Null
                                    if (Get-TanzuKubernetesCluster -name $namespace -tkc $tkc -ErrorAction Ignore | Out-Null ) {
                                        Remove-TanzuKubernetesCluster -cluster $tkc -namespace $namespace | Out-Null
                                        if (!(Get-TanzuKubernetesCluster -name $namespace -tkc $tkc -ErrorAction Ignore | Out-Null )) {
                                            Write-Output "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc): SUCCESSFUL"
                                        } else {
                                            Write-Error "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Removing Tanzu Kubernetes Cluster from Supervisor Cluster ($cluster) Namespace ($namespace) called ($tkc), does not exist: SKIPPED"
                                    }
                                } else {
                                    Write-Warning "Workload Management is not enabled on Cluster ($server) in vCenter Server ($($vcfVcenterDetails.fqdn))"
                                }
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                            Disconnect-WMCluster | Out-Null
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-TanzuKubernetesCluster

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region I N T E L L I G E N T L O G G I N G & A N A L Y T I C S F U N C T I O N S ###########

Function Export-vRLIJsonSpec {
    <#
        .SYNOPSIS
        Create vRealize Log Insight Deployment JSON specification using the Planning and Preparation workbook

        .DESCRIPTION
        The Export-vRLIJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook
        to deploy vRealize Log Insight using vRealize Suite Lifecycle Manager. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values.
        - Validates that the Planning and Preparation provided is available
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the License, Certificate and Password in the Planning and Prep Preparation workbook have been
        created in vRealize Suite Lifecycle Manager Locker
        - Generates the deployment JSON specification file using the Planning and Preparation workbook and details
        from vRealize Suite Lifecycle Manager named 'vrliDeploymentSpec.json'

        .EXAMPLE
        Export-vRLIJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example creates a JSON specification file for deploying vRealize Log Insight using the Planning and Preparation Workbook data
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("workbook")) {
            $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
        } else {
            if (!(Test-Path -Path $workbook)) {
                Write-Error  "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found"
                Break
            }
        }

        $pnpWorkbook = Open-ExcelPackage -Path $workbook

        ### Obtain Configuration Information from vRealize Suite Lifecycle Manager
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S'
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if ($pnpWorkbook.Workbook.Names["vrli_license"].Value) {
                                $licenseKey = $pnpWorkbook.Workbook.Names["vrli_license"].Value
                            } else {
                                $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value
                            }
                            $vrliLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey}
                            if ($vrliLicense.key -eq $licenseKey) {
                                if ($vrliCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value}) {
                                    if ($vrliPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value) {
                                        if ($vcfVersion -eq "4.5.0") {
                                            $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.userName -match (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "@vsphere.local")}
                                        } else {
                                            $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value)
                                        }
                                        $datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value}
                                        $infrastructurePropertiesObject = @()
                                        $infrastructurePropertiesObject += [pscustomobject]@{
                                            'dataCenterVmid'        = $datacenterName.dataCenterVmid
                                            'regionName'            = "default"
                                            'zoneName'                = "default"
                                            'vCenterName'            = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0]
                                            'vCenterHost'            = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value
                                            'vcUsername'            = $vcCredentials.userName
                                            'vcPassword'            = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias))
                                            'acceptEULA'            = "true"
                                            'enableTelemetry'        = "true"
                                            'defaultPassword'        = ("locker:password:" + $($vrliPassword.vmid) + ":" + $($vrliPassword.alias))
                                            'certificate'            = ("locker:certificate:" + $($vrliCertificate.vmid) + ":" + $($vrliCertificate.alias))
                                            'cluster'                = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value)
                                            'storage'                = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                            'diskMode'                = "thin"
                                            'network'                = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value
                                            'masterVidmEnabled'        = "false"
                                            'dns'                    = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value)
                                            'domain'                = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value
                                            'gateway'                = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value
                                            'netmask'                = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value
                                            'searchpath'            = $pnpWorkbook.Workbook.Names["child_dns_zone"].Value
                                            'timeSyncMode'            = "ntp"
                                            'ntp'                    = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value
                                            'isDhcp'                = "false"
                                            'vcfProperties'            = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}'
                                        }
                                        $infrastructureObject = @()
                                        $infrastructureObject += [pscustomobject]@{
                                            'properties'    = ($infrastructurePropertiesObject | Select-Object -Skip 0)
                                        }

                                        ### Generate the Properties Details
                                        $productPropertiesObject = @()
                                        $productPropertiesObject += [pscustomobject]@{
                                            'certificate'                    = ("locker:certificate:" + $($vrliCertificate.vmid) + ":" + $($vrliCertificate.alias))
                                            'productPassword'                = ("locker:password:" + $($vrliPassword.vmid) + ":" + $($vrliPassword.alias))
                                            'adminEmail'                    = $pnpWorkbook.Workbook.Names["region_vrli_admin_email"].Value
                                            'fipsMode'                        = "false"
                                            'licenseRef'                    = ("locker:license:" + $($vrliLicense.vmid) + ":" + $($vrliLicense.alias))
                                            'nodeSize'                        = $pnpWorkbook.Workbook.Names["region_vrli_appliance_size"].Value.ToLower()
                                            'configureClusterVIP'            = "false"
                                            'affinityRule'                    = $false
                                            'isUpgradeVmCompatibility'        = $false
                                            'vrliAlwaysUseEnglish'            = $false
                                            'masterVidmEnabled'                = $false
                                            'configureAffinitySeparateAll'    = "true"
                                            'ntp'                            = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value
                                            'timeSyncMode'                    = "ntp"
                                        }

                                        #### Generate vRealize Log Insight Cluster Details
                                        $clusterVipProperties = @()
                                        $clusterVipProperties += [pscustomobject]@{
                                            'hostName'    = $pnpWorkbook.Workbook.Names["region_vrli_virtual_fqdn"].Value
                                            'ip'        = $pnpWorkbook.Workbook.Names["region_vrli_virtual_ip"].Value
                                        }
                                        $clusterVipsObject = @()
                                        $clusterVipsObject += [pscustomobject]@{
                                            'type'            = "vrli-cluster-1"
                                            'properties'    = ($clusterVipProperties | Select-Object -Skip 0)
                                        }
                                        $clusterObject = @()
                                        $clusterObject += [pscustomobject]@{
                                        'clusterVips'    = $clusterVipsObject
                                        }
                                        
                                        #### Generate vRealize Log Insight Node Details
                                        $masterProperties = @()
                                        $masterProperties += [pscustomobject]@{
                                            'vmName'        = $pnpWorkbook.Workbook.Names["region_vrli_nodea_hostname"].Value
                                            'hostName'        = $pnpWorkbook.Workbook.Names["region_vrli_nodea_fqdn"].Value
                                            'ip'            = $pnpWorkbook.Workbook.Names["region_vrli_nodea_ip"].Value
                                            'folderName'    = $pnpWorkbook.Workbook.Names["region_vrli_vm_folder"].Value
                                        }
                                        $worker1Properties = @()
                                        $worker1Properties += [pscustomobject]@{
                                            'vmName'        = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_hostname"].Value
                                            'hostName'        = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_fqdn"].Value
                                            'ip'            = $pnpWorkbook.Workbook.Names["region_vrli_nodeb_ip"].Value
                                        }
                                        $worker2Properties = @()
                                        $worker2Properties += [pscustomobject]@{
                                            'vmName'        = $pnpWorkbook.Workbook.Names["region_vrli_nodec_hostname"].Value
                                            'hostName'        = $pnpWorkbook.Workbook.Names["region_vrli_nodec_fqdn"].Value
                                            'ip'            = $pnpWorkbook.Workbook.Names["region_vrli_nodec_ip"].Value
                                        }
                                        $nodesObject = @()
                                        $nodesobject += [pscustomobject]@{
                                            'type'            = "vrli-master"
                                            'properties'    = ($masterProperties | Select-Object -Skip 0)
                                        }
                                        $nodesobject += [pscustomobject]@{
                                            'type'            = "vrli-worker"
                                            'properties'    = ($worker1Properties | Select-Object -Skip 0)
                                        }
                                        $nodesobject += [pscustomobject]@{
                                            'type'            = "vrli-worker"
                                            'properties'    = ($worker2Properties | Select-Object -Skip 0)
                                        }

                                        #### Generate the vRealize Log Insight Properties Section
                                        if ($vcfVersion -eq "4.3.0") { $vrliVersion = "8.4.0"}
                                        if ($vcfVersion -eq "4.3.1") { $vrliVersion = "8.4.1"}
                                        if ($vcfVersion -eq "4.4.0") { $vrliVersion = "8.6.2"}
                                        if ($vcfVersion -eq "4.4.1") { $vrliVersion = "8.6.2"}
                                        if ($vcfVersion -eq "4.5.0") { $vrliVersion = "8.8.2"}
                                        $productsObject = @()
                                        $productsObject += [pscustomobject]@{
                                            'id'             = "vrli"
                                            'version'        = $vrliVersion
                                            'properties'    = ($productPropertiesObject  | Select-Object -Skip 0)
                                            'clusterVIP'    = ($clusterObject  | Select-Object -Skip 0)
                                            'nodes'            = $nodesObject    
                                        }
                                        $vrliDeploymentObject = @()
                                        $vrliDeploymentObject += [pscustomobject]@{
                                            'environmentName'                   = $pnpWorkbook.Workbook.Names["vrslcm_reg_env"].Value
                                            'infrastructure'                    = ($infrastructureObject  | Select-Object -Skip 0)
                                            'products'                          = $productsObject     
                                        }
                                        $vrliDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vrliDeploymentSpec.json" 
                                        Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue
                                        Write-Output "Creation of Deployment JSON Specification file for vRealize Log Insight: SUCCESSFUL"
                                    } else {
                                        Write-Error "Unable to find Admin Password with alias ($($pnpWorkbook.Workbook.Names["region_vrli_admin_password_alias"].Value)) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to find Certificate with alias ($($pnpWorkbook.Workbook.Names["region_vrli_virtual_hostname"].Value)) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to find License key ($licenseKey) in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Export-vRLIJsonSpec

Function New-vRLIDeployment {
    <#
        .SYNOPSIS
        Deploy vRealize Log Insight Cluster via vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The New-vRLIDeployment cmdlet deploys vRealize Log Insight via vRealize Suite Lifecycle Manager. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that the Planning and Preparation provided is available
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the environment does not already exist in vRealize Suite Lifecycle Manager
        - Requests a new deployment of vRealize Log Insight via vRealize Suite Lifecycle Manager

        .EXAMPLE
        New-vRLIDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example starts a deployment of vRealize Log Inisght via vRealize Suite Lifecycle Manager using the Planning and Preparation Workbook data
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor
    )

    Try {

        if (!$PsBoundParameters.ContainsKey("workbook")) {
            $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
        } else {
            if (!(Test-Path -Path $workbook)) {
                Write-Error "Planning and Preparation Workbook (.xlsx) ($workbook), File Not Found"
                Break
            }
        }

        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            Export-vRLIJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null
                            $json = (Get-Content -Raw .\vrliDeploymentSpec.json)
                            $jsonSpec = $json | ConvertFrom-Json
                            if (!($environmentExists = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $($jsonSpec.environmentName)}))) {
                                if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.productPassword.Split(":")[3])) {
                                    if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) {
                                        if (Get-vRSLCMLockerLicense | Where-Object {$_.alias -Match $($jsonSpec.products.properties.licenseRef.Split(":")[3])}) {
                                            $newRequest = Add-vRSLCMEnvironment -json $json
                                            if ($newRequest) {
                                                if ($PsBoundParameters.ContainsKey("monitor")) {
                                                    Start-Sleep 10
                                                    Watch-vRSLCMRequest -vmid $($newRequest.requestId)
                                                } else {
                                                    Write-Output "Deployment Request for vRealize Log Insight Submitted Successfully (Request Ref: $($newRequest.requestId))"
                                                }
                                            } else {
                                                Write-Error "Request to deploy vRealize Log Insight failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "License with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Certificate with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Password with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])) does not exist in the locker: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Environment with name ($($jsonSpec.environmentName)) already exists in vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)) with a status of ($($environmentExists.environmentStatus)): SKIPPED"
                            }
                        }
                    }
                } 
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vRLIDeployment

Function Undo-vRLIDeployment {
    <#
        .SYNOPSIS
        Remove the vRealize Log Insight Environment from vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Undo-vRLIDeployment cmdlet removes vRealize Log Insight from vRealize Suite Lifecycle Manager. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the environment exist in vRealize Suite Lifecycle Manager
        - Requests a the deletion of vRealize Log Insight from vRealize Suite Lifecycle Manager

        .EXAMPLE
        Undo-vRLIDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -environmentName sfo-region-env
        This example starts a removal of vRealize Log Inisght from vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$environmentName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if ($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $environmentName}) {
                                $newRequest = Remove-vRSLCMEnvironment -environmentId (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $environmentName}).environmentId
                                if ($newRequest) {
                                    if ($PsBoundParameters.ContainsKey("monitor")) {
                                        Start-Sleep 10
                                        Watch-vRSLCMRequest -vmid $($newRequest.requestId)
                                        if (!(Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $environmentName})) {
                                            Write-Output "Removal of vRealize Log Insight from vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)): SUCCESSFUL"
                                        } else {
                                            Write-Error "Removal of vRealize Log Insight from vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Output "Removal request of vRealize Log Insight Submitted Successfully (Request Ref: $($newRequest.requestId))"
                                    }
                                } else {
                                    Write-Error "Removel request of vRealize Log Insight failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Environment with name ($environmentName) in vRealize Suite Lifecyle Manager ($($vcfVrslcmDetails.fqdn)), already removed: SKIPPED"
                            }
                        }
                    }
                } 
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRLIDeployment

Function Add-vRLISmtpConfiguration {
    <#
        .SYNOPSIS
        Configure SMTP settings in vRealize Log Insight

        .DESCRIPTION
        The Add-vRLISmtpConfiguration cmdlet configures the SMTP sever settings in vRealize Log Insight. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that network connectivity is possible to the SMTP server
        - Configures SMTP server settings in vRealize Log Insight if not already configured

        .EXAMPLE
        Add-vRLISmtpConfiguration -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -smtpServer smtp.rainpole.io -port 25 -sender administrator@rainpole.io
        This example configures the SMTP server settings on vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpUser,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$smtpPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (Test-Connection -ComputerName $smtpServer -Quiet -Count 1) {
                                if (!(Get-vRLISmtpConfiguration | Where-Object {$_.server -eq $smtpServer})) {
                                    Set-vRLISmtpConfiguration -smtpServer $smtpServer -port $port -sender $sender -username $smtpUser -password $smtpPass | Out-Null
                                    if (Get-vRLISmtpConfiguration | Where-Object {$_.server -eq $smtpServer}) {
                                        Write-Output "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer): SUCCESSFUL"
                                    } else {
                                        Write-Error "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Configuring SMTP Server in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with SMTP server ($smtpServer), already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to communicate with SMTP Server ($smtpServer), check details: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLISmtpConfiguration

Function Add-vRLIAuthenticationWSA {
    <#
        .SYNOPSIS
        Configure vRealize Log Insight Intergration with Workspace ONE Access

        .DESCRIPTION
        The Add-vRLIAuthenticationWSA cmdlet configures role assignments in NSX Manager. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that network connectivity is possible to Workspace ONE Access
        - Configures Workspace ONE Access Integration on vRealize Log Insight if not already configured

        .EXAMPLE
        Add-vRLIAuthenticationWSA -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1!
        This example enables Workspace ONE Access integration on vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (Test-Connection -ComputerName $wsaFqdn -Quiet -Count 1) {
                                if ((Get-vRLIAuthenticationWSA).enabled -eq $false) {
                                    Set-vRLIAuthenticationWSA -hostname $wsaFqdn -port 443 -redirectUrl $vcfVrliDetails.fqdn -username $wsaUser -password $wsaPass
                                    if ((Get-vRLIAuthenticationWSA).enabled -eq $true) {
                                        Write-Output "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn): SUCCESSFUL"
                                    } else {
                                        Write-Error "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Configuring Workspace ONE Access Integration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with ($wsaFqdn), already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to communicate with Workspace ONE Access Instance ($wsaFqdn), check details: POST_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        } 
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLIAuthenticationWSA

Function Install-vRLIPhotonAgent {
    <#
        .SYNOPSIS
        Install vRealize Log Insight Photon Agent in a Virtual Machine

        .DESCRIPTION
        The Install-vRLIPhotonAgent cmdlet installs and configures the vRealize Log Insight Photon Agent on a virtual
        machine. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the Virtual Machine exists in the vCenter Server inventory
        - Downloads and Installs the Photon Agent on the Virtual Machne
        - Configures the liagent.ini file to communicate with vRealize Log Insight

        .EXAMPLE
        Install-vRLIPhotonAgent -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vmName sfo-wsa01 -vmRootPass VMw@re1!
        This example installs and configures the vRealize Log Insight Agent on the virtual machine named 'sfo-wsa01'
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmRootPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                                if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) {
                                    if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        if (Get-VM -Name $vmName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) {
                                            $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn
                                            if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) {
                                                Write-Warning "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName), already exists: SKIPPED"
                                            } else {
                                                Invoke-VMScript -VM $vmName -ScriptText "rm /tmp/liagent.rpm && rm /tmp/installAgent.sh && /tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null
                                                $installAgent = @(
                                                    "curl -k -o /tmp/liagent.rpm https://$($vcfVrliDetails.fqdn)/api/v1/agent/packages/types/rpm; rpm -Uvh /tmp/liagent.rpm",
                                                    "systemctl enable liagentd",
                                                    "systemctl status liagentd"
                                                )
                                                Foreach ($line in $installAgent) {
                                                    Invoke-VMScript -VM $vmName -ScriptText "echo ""$line"">>/tmp/installAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null
                                                }
                                                $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/installAgent.sh && /tmp/installAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn
                                                if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) {
                                                    $configureAgent = @(
                                                        "sed -i 's/;hostname=LOGINSIGHT/hostname=$($vcfVrliDetails.fqdn)/' /var/lib/loginsight-agent/liagent.ini",
                                                        "sed -i 's/;proto=cfapi/proto=cfapi/' /var/lib/loginsight-agent/liagent.ini",
                                                        "sed -i 's/;port=9543/port=9000/' /var/lib/loginsight-agent/liagent.ini",
                                                        "sed -i 's/;ssl=yes/ssl=no/' /var/lib/loginsight-agent/liagent.ini",
                                                        "systemctl restart liagentd",
                                                        "systemctl status liagentd"
                                                    )
                                                    Foreach ($line in $configureAgent) {
                                                        Invoke-VMScript -VM $vmName -ScriptText "echo ""$line"">>/tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null
                                                    }
                                                    $output = Invoke-VMScript -VM $vmName -ScriptText "chmod 777 /tmp/configureAgent.sh && /tmp/configureAgent.sh" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn
                                                    if ($output.ScriptOutput.Contains("active (running)")) {
                                                        Write-Output "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName): SUCCESSFUL"
                                                    } else {
                                                        Write-Error "Installing and Configuring vRealize Log Insight Agent Installed and Configured on ($vmName): POST_VALIDATION_FAILED"
                                                    }
                                                } else {
                                                    Write-Error "Enabling vRealize Log Insight Agent Installed and Configured on ($vmName): POST_VALIDATION_FAILED"
                                                }
                                            }
                                        } else {
                                            Write-Error "Virtual Machine ($vmName), not Found in vCenter Server ($($vcfVcenterDetails.fqdn)) Inventory, check details and try again: PRE_VALIDATION_FAILED"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-vRLIPhotonAgent

Function Undo-vRLIPhotonAgent {
    <#
        .SYNOPSIS
        Removes the vRealize Log Insight Photon Agent from a Virtual Machine

        .DESCRIPTION
        The Undo-vRLIPhotonAgent cmdlet removes the vRealize Log Insight Photon Agent from a virtual
        machine. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the Virtual Machine exists in the vCenter Server inventory
        - Removes the Photon Agent from the Virtual Machne

        .EXAMPLE
        Undo-vRLIPhotonAgent -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vmName sfo-wsa01 -vmRootPass VMw@re1!
        This example removes the vRealize Log Insight Agent from the virtual machine named 'sfo-wsa01'
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmRootPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                            if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) {
                                if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                    if (Get-VM -Name $vmName -Server $vcfVcenterDetails.fqdn -ErrorAction SilentlyContinue) {
                                        $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn
                                        if ($output.ScriptOutput.Contains("/lib/systemd/system/liagentd.service; enabled")) {
                                            Invoke-VMScript -VM $vmName -ScriptText "curl -k -o /tmp/liagent.rpm https://$($vcfVrliDetails.fqdn)/api/v1/agent/packages/types/rpm; package=`$(rpm -q /tmp/liagent.rpm); rpm -e `$package; systemctl daemon-reload" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn | Out-Null
                                            $output = Invoke-VMScript -VM $vmName -ScriptText "systemctl status liagentd" -GuestUser root -GuestPassword $vmRootPass -Server $vcfVcenterDetails.fqdn
                                            if ($output.ScriptOutput.Contains("liagentd.service could not be found")) {
                                                Write-Output "Removing vRealize Log Insight Agent from ($vmName): SUCCESSFUL"
                                            } else {
                                                Write-Error "Removing vRealize Log Insight Agent from ($vmName): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Removing vRealize Log Insight Agent from ($vmName), already performed: SKIPPED"
                                        }
                                    } else {
                                        Write-Error "Virtual Machine ($vmName), not Found in vCenter Server ($($vcfVcenterDetails.fqdn)) Inventory, check details and try again: PRE_VALIDATION_FAILED"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRLIPhotonAgent

Function Add-vRLIAgentGroup {
    <#
        .SYNOPSIS
        Creates an agent group in vRealize Log Insight

        .DESCRIPTION
        The Add-vRLIAgentGroup cmdlet creates a new agent group in vRealize Log Insight. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Creates an agent group in the vRealize Log Insight if not already configured

        .EXAMPLE
        Add-vRLIAgentGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -agentGroupType wsa -agentGroupName "Workspace ONE Access - Appliance Agent Group" -criteria "xint-wsa01a.rainpole.io","xint-wsa01b.rainpole.io","xint-wsa01c.rainpole.io"
        This example creates an agent group for Workspace ONE Access in vRealize Log Insight and assigns the Cluster Virtual Machines

        .EXAMPLE
        Add-vRLIAgentGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -agentGroupType photon -agentGroupName "Photon OS - Appliance Agent Group" -criteria "sfo-vcf01.sfo.rainpole.io","xint-vrslcm01.rainpole.io","xint-wsa01a.rainpole.io","xint-wsa01b.rainpole.io","xint-wsa01c.rainpole.io"
        This example creates an agent group for Photon OS in vRealize Log Insight and assigns the SDDC Manager, vRealize Suite Lifecycle Manager and Workspace ONE Access Cluster Virtual Machines
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$agentGroupName,
        [Parameter (Mandatory = $true)] [ValidateSet("wsa","photon")] [ValidateNotNullOrEmpty()] [String]$agentGroupType,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$criteria
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (!(Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentGroupName})) {
                                New-vRLIAgentGroup -agentGroupType $agentGroupType -criteria $criteria -agentGroupName $agentGroupName | Out-Null
                                if (Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentGroupName}) {
                                    Write-Output "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName): SUCCESSFUL"
                                } else {
                                    Write-Error "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Creating Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName), already performed: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLIAgentGroup

Function Undo-vRLIAgentGroup {
    <#
        .SYNOPSIS
        Deletes an agent group in vRealize Log Insight

        .DESCRIPTION
        The Undo-vRLIAgentGroup cmdlet deletes an agent group from vRealize Log Insight. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Deletes an agent group from the vRealize Log Insight if not already configured

        .EXAMPLE
        Undo-vRLIAgentGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -agentGroupName "Workspace ONE Access (IAM) - Appliance Agent Group"
        This example deletes an agent group for Workspace ONE Access in vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$agentGroupName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentGroupName}) {
                                Remove-vRLIAgentGroup -groupName $agentGroupName | Out-Null
                                if (!(Get-vRLIAgentGroup | Select-Object name | Where-Object {$_.name -eq $agentGroupName})) {
                                    Write-Output "Deleting Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName): SUCCESSFUL"
                                } else {
                                    Write-Error "Deleting Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Deleting Agent Group in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for ($agentGroupName), does not exist: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRLIAgentGroup

Function Register-vRLIWorkloadDomain {
    <#
        .SYNOPSIS
        Connect a Workload Domain to vRealize Log Insight

        .DESCRIPTION
        The Register-vRLIWorkloadDomain cmdlet connects a Workload Domain to vRealize Log Insight. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Obtains the Workload Domain details from the SDDC Manager inventory
        - Connects the Workload Domain with vRealize Log Insight if not already configured

        .EXAMPLE
        Register-vRLIWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status ENABLED
        This example ENABLES the Workload Domain in vRealize Log Insight

        .EXAMPLE
        Register-vRLIWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status DISABLED
        This example DISABLES the Workload Domain in vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateSet("ENABLED", "DISABLED")] [String]$status
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                                if ((Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -ne $status) { 
                                    Set-VCFvRLIConnection -domainId (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id -status $status | Out-Null
                                    Do {
                                        $configStatus = (Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status
                                    } Until ($configStatus -ne "IN_PROGRESS")
                                    if ((Get-VCFvRLIConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -eq $status) { 
                                        Write-Output "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain): SUCCESSFUL"
                                    } else {
                                        Write-Error "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Workload Domain Intergration in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for Workload Domain ($domain), already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Register-vRLIWorkloadDomain

Function Set-vRLISyslogEdgeCluster {
    <#
        .SYNOPSIS
        Configure Syslog settings on NSX Edge Cluster Nodes

        .DESCRIPTION
        The Set-vRLISyslogEdgeCluster cmdlet configures Syslog settings on NSX Edge Cluster The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Gathers the NSX Edge Node details from NSX Management Cluster
        - Configures the Syslog settings on the NSX Edge Node if not already configured

        .EXAMPLE
        Set-vRLISyslogEdgeCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -exportname SFO-VRLI
        This example configures the Syslog settings for each NSX Edge node to sent logs to vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exportName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                $vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass
                if ($nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes) {
                    if (Test-NSXTConnection -server $nsxtManagerDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $nsxtManagerDetails.fqdn -user $nsxtManagerDetails.adminUser -pass $nsxtManagerDetails.AdminPass) {
                            [Array]$edgeNodeIds = (Get-NsxtEdgeCluster).members.transport_node_id
                            foreach ($nodeId in $edgeNodeIds) {
                                if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName})) {
                                    if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.server -eq $vcfVrliDetails.fqdn})) {
                                        Set-NsxtSyslogExporter -transport -id $nodeId -exporterName $exportName -logLevel INFO -port 514 -protocol TCP -server $vcfVrliDetails.fqdn | Out-Null
                                        if (Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName}) {
                                            Write-Output "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId): SUCCESSFUL"
                                        } else {
                                            Write-Error "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Configuring Syslog Server ($($vcfVrliDetails.fqdn)) on Edge Node ($nodeId), already exists: SKIPPED"
                                    }
                                } else {
                                    Write-Warning "Configuring Syslog Exporter ($exportName) on Edge Node ($nodeId), already exists: SKIPPED"
                                }
                            }
                        }
                    }
                } 
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vRLISyslogEdgeCluster

Function Undo-vRLISyslogEdgeCluster {
    <#
        .SYNOPSIS
        Removes the Syslog settings on NSX Edge Cluster Nodes

        .DESCRIPTION
        The Undo-vRLISyslogEdgeCluster cmdlet removes the Syslog settings on NSX Edge Cluster. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to NSX Management Cluster
        - Gathers the NSX Edge Node details from NSX Management Cluster
        - Removes the Syslog settings on the NSX Edge Node

        .EXAMPLE
        Undo-vRLISyslogEdgeCluster -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -exportname SFO-VRLI
        This example removes the Syslog settings for each NSX Edge node
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exportName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if ($nsxtManagerDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain -listNodes) {
                    if (Test-NSXTConnection -server $nsxtManagerDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $nsxtManagerDetails.fqdn -user $nsxtManagerDetails.adminUser -pass $nsxtManagerDetails.AdminPass) {
                            [Array]$edgeNodeIds = (Get-NsxtEdgeCluster).members.transport_node_id
                            Foreach ($nodeId in $edgeNodeIds) {
                                if (Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName}) { 
                                    Remove-NsxtSyslogExporter -transport -id $nodeId -exporterName $exportName | Out-Null
                                    if (!(Get-NsxtSyslogExporter -transport -id $nodeId | Where-Object {$_.exporter_name -eq $exportName})) {
                                        Write-Output "Removing Syslog Exporter ($exportName) on Edge Node ($nodeId): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing Syslog Exporter ($exportName) on Edge Node ($nodeId): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing Syslog Exporter ($exportName) on Edge Node ($nodeId), already removed: SKIPPED"
                                }
                            }
                        }
                    }
                } 
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRLISyslogEdgeCluster

Function Add-vRLILogArchive {
    <#
        .SYNOPSIS
        Configure log archiving in vRealize Log Insight

        .DESCRIPTION
        The Add-vRLILogArchive cmdlet configure log archiving in vRealize Log Insight. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Configure an email address to send notifications to in vRealize Log Insight
        - Configure the log retention threshold in vRealize Log Insight
        - Configure log archive location in vRealize Log Insight

        .EXAMPLE
        Add-vRLILogArchive -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -emailAddress administrator@rainpole.io -retentionNotificationDays 1 -retentionInterval weeks -retentionPeriodDays 7 -archiveLocation "nfs://172.27.11.4/sfo-m01-vrli01-400GB"
        This example configures the log archive and retention period in vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$retentionNotificationDays,
        [Parameter (Mandatory = $true)] [ValidateSet("minutes","hours","days","weeks","months")] [ValidateNotNullOrEmpty()] [String]$retentionInterval,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$retentionPeriodDays,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$archiveLocation
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            Set-vRLIEmailNotification -emailAddress $emailAddress | Out-Null
                            Set-vRLIRetentionThreshold -enable true -interval $retentionNotificationDays -intervalUnit $retentionInterval | Out-Null
                            $partitionId = (Get-vRLIIndexPartition).id
                            Set-vRLILogArchive -id $partitionId -enable true -retentionPeriod $retentionPeriodDays -archiveEnable true -archiveLocation $archiveLocation
                            Write-Output "Configuring Email Notifications, Retention Period and Archive Location in vRealize Log Insight ($($vcfVrliDetails.fqdn)): SUCCESSFUL"
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLILogArchive

Function Add-vRLIAuthenticationGroup {
    <#
        .SYNOPSIS
        Adds a group from the authentication provider in vRealize Log Insight

        .DESCRIPTION
        The Add-vRLIAuthenticationGroup cmdlet assigns access to a group based on the authentication providor. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that integration with Workspace ONE Access has been enabled
        - Validates that the group has not already been assigned access to vRealize Log Insight
        - Adds the group to the access control assigning the role provided in vRealize Log Insight

        .EXAMPLE
        Add-vRLIAuthenticationGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -group gg-vrli-admins -role 'Super Admin'
        This example adds the group gg-vrli-admins with Super Admin role in vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group,
        [ValidateSet("Super Admin","User","Dashboard User","View Only Admin")] [ValidateNotNullOrEmpty()] [String]$role
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if ($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (Get-vRLIAuthenticationWSA -eq "True") {
                                if (!(Get-vRLIGroup -authProvider vidm | Where-Object {$_.name -eq $group + "@" + $domain})) {
                                    Add-vRLIGroup -authProvider vidm -domain $domain -group $group -role $role | Out-Null
                                    if (Get-vRLIGroup -authProvider vidm | Where-Object {$_.name -eq $group + "@" + $domain}) {
                                        Write-Output "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group): SUCCESSFUL"
                                    } else {
                                        Write-Warning "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Adding Group to vRealize Log Insight ($($vcfVrliDetails.fqdn)), named ($group), already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Workspace ONE Integration on vRealize Log Insight ($($vcfVrliDetails.fqdn)), not enabled: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLIAuthenticationGroup

Function Add-vRLIAlertDatacenter {
    <#
        .SYNOPSIS
        Adds datacenter based alerts in vRealize Log Insight

        .DESCRIPTION
        The Add-vRLIAlertsDatacenter cmdlet adds datacenter based alerts to vRealize Log Insight. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Datacenter object provided is valid in the vCenter Server inventory
        - Creates the alert in vRealize Log Insight for the Datacenter object if not already configured
        - Integrates with vRealize Operations Manager if the -vropsIntegration switch is provided

        .EXAMPLE
        Add-vRLIAlertDatacenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomainName sfo-m01 -datacenterName sfo-m01-dc01 -email administrator@rainpole.io -alertTemplate ".\SampleNotifications\vrli-vcf-datacenter.json" -vropsIntegration
        This example adds the alerts provided in the JSON file
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomainName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alertTemplate,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$vropsIntegration
    )

    $adapter = "VMWARE" # Defines the vRealize Operations Manager Adapter type
    $resource = "Datacenter" # Defines the vRealize Operations Manager Resource type associated with the Adapter

    Try {
        if (Test-Path -Path $alertTemplate) {
            if (Test-VCFConnection -server $server) {
                if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                    if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                        if ($PsBoundParameters.ContainsKey("vropsIntegration")) {
                            if (!($vcfVropsDetails = Get-vROPSServerDetail -fqdn $server -username $user -password $pass)) {
                                Break
                            } else {
                                if (!(Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn)) { Break }
                                if (!(Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass)) { Break }
                            }
                        }
                        if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomainName)) {
                            if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) {
                                if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                                        if (Get-Datacenter $datacenterName -ErrorAction Ignore ) {
                                            if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { 
                                                $templateAlerts = (Get-Content -path $alertTemplate -Raw)
                                                $templateAlerts = $templateAlerts -replace '!!datacenterName!!',$datacenterName
                                                $templateAlerts = $templateAlerts -replace '!!email!!',$email
                                                [Array]$allAlerts = $templateAlerts | ConvertFrom-Json
                                                Foreach ($alert in $allAlerts) {
                                                    $json = $alert | ConvertTo-Json
                                                    if ($PsBoundParameters.ContainsKey("vropsIntegration")) {
                                                        $entityObjectId =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $datacenterName | Where-Object {$_.identifierType.name -eq "VMEntityObjectID"}).value
                                                        $entityVcid =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $datacenterName | Where-Object {$_.identifierType.name -eq "VMEntityVCID"}).value
                                                        $vcopsResourceKindKey = '"vcopsResourceKindKey": "' + 'resourceName='+$datacenterName+'&adapterKindKey='+$adapter+'&resourceKindKey='+$resource+'&identifiers=VMEntityName::'+$datacenterName+'$$$VMEntityObjectID::'+$entityObjectId+'$$$VMEntityVCID::'+$entityVcid + '"'
                                                        $json = $json -replace '"vcopsEnabled": false','"vcopsEnabled": true'
                                                        $json = $json -replace '"vcopsResourceKindKey": ""',$vcopsResourceKindKey
                                                    }
                                                    if (!((Get-vRLIAlert | Select-Object name ) | Where-Object {$_.name -eq $alert.name})) {
                                                        Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass | Out-Null
                                                        New-vRLIAlert -json $json | Out-Null
                                                    }
                                                }
                                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                                                Write-Output "Adding Datacenter Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) using template Alert JSON ($alertTemplate) for Workload Domain ($sddcDomainName): SUCCESSFUL"
                                            }
                                        } else {
                                            Write-Error "Unable to find Datacenter ($datacenterName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                        }
                                    }
                                }
                            }
                        }
                    }                       
                }
            }
        } else {
            Write-Error "Unable to find template Alert JSON ($alertTemplate): PRE_VALIDATION_FAILED"
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLIAlertDatacenter

Function Add-vRLIAlertVirtualMachine {
    <#
        .SYNOPSIS
        Adds virtual machine based alerts in vRealize Log Insight

        .DESCRIPTION
        The Add-vRLIAlertVirtualMachine cmdlet adds virtual machine based alerts to vRealize Log Insight. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Virtual Machine object provided is valid in the vCenter Server inventory
        - Creates the alert in vRealize Log Insight for the Virtual Machine object if not already configured
        - Integrates with vRealize Operations Manager if the -vropsIntegration switch is provided

        .EXAMPLE
        Add-vRLIAlertVirtualMachine -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomainName sfo-m01 -vmName xint-vrslcm01 -email administrator@rainpole.io -alertTemplate ".\SampleNotifications\vrli-vcf-vmVrslcm.json" -vropsIntegration
        This example adds the alerts provided in the JSON file for the vRealize Suite Lifecycle Manager Virtual Machine
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomainName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alertTemplate,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$vropsIntegration
    )

    $adapter = "VMWARE" # Defines the vRealize Operations Manager Adapter type
    $resource = "VirtualMachine" # Defines the vRealize Operations Manager Resource type associated with the Adapter

    Try {
        if (Test-Path -Path $alertTemplate) {
            if (Test-VCFConnection -server $server) {
                if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                    if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                        if ($PsBoundParameters.ContainsKey("vropsIntegration")) {
                            if (!($vcfVropsDetails = Get-vROPSServerDetail -fqdn $server -username $user -password $pass)) {
                                Break
                            } else {
                                if (!(Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn)) { Break }
                                if (!(Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass)) { Break }
                            }
                        }
                        if (($vcfVcenterDetails = Get-VcenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomainName)) {
                            if (Test-VsphereConnection -server $vcfVcenterDetails.fqdn) {
                                if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                                        if (Get-VM $vmName -ErrorAction Ignore ) {
                                            if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) { 
                                                $templateAlerts = (Get-Content -path $alertTemplate -Raw)
                                                $templateAlerts = $templateAlerts -replace '!!vmName!!',$vmName
                                                $templateAlerts = $templateAlerts -replace '!!email!!',$email
                                                [Array]$allAlerts = $templateAlerts | ConvertFrom-Json
                                                Foreach ($alert in $allAlerts) {
                                                    $json = $alert | ConvertTo-Json
                                                    if ($PsBoundParameters.ContainsKey("vropsIntegration")) {
                                                        $VMEntityInstanceUUID =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMEntityInstanceUUID"}).value
                                                        $VMEntityObjectID =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMEntityObjectID"}).value
                                                        $VMEntityVCID =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMEntityVCID"}).value
                                                        $VMServiceMonitoringEnabled =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "VMServiceMonitoringEnabled"}).value
                                                        $isPingEnabled =(Get-vROPSResourceDetail -adapter $adapter -resource $resource -objectname $vmName | Where-Object {$_.identifierType.name -eq "isPingEnabled"}).value
                                                        $vcopsResourceKindKey = '"vcopsResourceKindKey": "' + 'resourceName='+ $vmName +'&adapterKindKey='+ $adapter+ '&resourceKindKey='+ $resource +'&identifiers=VMEntityInstanceUUID::'+ $VMEntityInstanceUUID  +'$$$VMEntityName::'+ $vmName + '$$$VMEntityObjectID::'+ $VMEntityObjectID +'$$$VMEntityVCID::'+ $VMEntityVCID +'$$$VMServiceMonitoringEnabled::'+ $VMServiceMonitoringEnabled +'$$$isPingEnabled::'+ $isPingEnabled +'"'
                                                        $json = $json -replace '"vcopsEnabled": false','"vcopsEnabled": true'
                                                        $json = $json -replace '"vcopsResourceKindKey": ""',$vcopsResourceKindKey
                                                    }
                                                    if (!((Get-vRLIAlert | Select-Object name ) | Where-Object {$_.name -eq $alert.name})) {
                                                        Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass | Out-Null
                                                        New-vRLIAlert -json $json | Out-Null
                                                    }
                                                }
                                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                                                Write-Output "Adding Virtual Machine Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) using template Alert JSON ($alertTemplate) for Workload Domain ($sddcDomainName): SUCCESSFUL"
                                            }
                                        } else {
                                            Write-Error "Unable to find Virtual Machine ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                        }
                                    }
                                }
                            }
                        }
                    }                         
                }
            }
        } else {
            Write-Error "Unable to find template Alert JSON ($alertTemplate): PRE_VALIDATION_FAILED"
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLIAlertVirtualMachine

Function Undo-vRLIAlert {
    <#
        .SYNOPSIS
        Removes alerts from vRealize Log Insight

        .DESCRIPTION
        The Undo-vRLIAlert cmdlet removes datacenter based alerts from vRealize Log Insight. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Deletes all alerts with the name provided in the title

        .EXAMPLE
        Undo-vRLIAlert -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -name sfo-m01-dc01
        This example removes all alerts that contain the name 'sfo-m01-dc01'
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if ($allAlerts = Get-vRLIAlert | Where-Object {$_.name -match $name} | Select-Object name, id) {
                                Foreach ($alert in $allAlerts) {
                                    Remove-vRLIAlert -alertId $alert.id | Out-Null
                                }
                                Write-Output "Removing Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) with name ($name): SUCCESSFUL"
                            } else {
                                Write-Warning "Removing Alerts in vRealize Log Insight ($($vcfVrliDetails.fqdn)) for name ($name), none exist: SKIPPED"
                            }
                        }
                    }
                }                         
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRLIAlert

Function Add-vRLILogForwarder {
    <#
        .SYNOPSIS
        Adds a log forwarder destination to vRealize Log Insight

        .DESCRIPTION
        The Add-vRLILogForwarder cmdlet adds log forwarder destination to vRealize Log Insight. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Adds a log forwarder destination to vRealize Log Insight

        .EXAMPLE
        Add-vRLILogForwarder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -name "SFO to LAX" -fqdn lax-vrli01.lax.rainpole.io -protocol SYSLOG -port 514 -transport TCP -acceptCert false -sslEnabled false -testConnection false
        This example adds a log forwarder to vRealize Log Insight using syslog over TCP 514.

        .EXAMPLE
        Add-vRLILogForwarder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -name "SFO to LAX" -fqdn lax-vrli01.lax.rainpole.io -protocol CFAPI -port 9543 -acceptCert true -sslEnabled true -testConnection true
        This example adds a log forwarder destination to vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateSet("CFAPI", "SYSLOG", "RAW")] [String]$protocol,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $false)] [ValidateSet("TCP", "UDP")] [String]$transport,
        [Parameter (Mandatory = $true)] [ValidateSet('true', 'false')] [String]$acceptCert,
        [Parameter (Mandatory = $true)] [ValidateSet('true', 'false')] [String]$sslEnabled,
        [Parameter (Mandatory = $true)] [ValidateSet('true', 'false')] [String]$testConnection
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            if (! (Get-vRlILogForwarder | Where-Object {$_.host -eq $fqdn})) {
                                if ($protocol -eq 'SYSLOG' -and (-not $PsBoundParameters.ContainsKey('transport'))) {
                                    Throw 'You must enter a transport for SYSLOG.'
                                } elseif ($protocol -eq 'SYSLOG' -and ($PsBoundParameters.ContainsKey('transport'))) {
                                    Set-vRLILogForwarder -name $name -server $fqdn -protocol $protocol -port $port -transport $transport -acceptCert $acceptCert -sslEnabled $sslEnabled -testConnection $testConnection | Out-Null
                                    if (Get-vRlILogForwarder | Where-Object {$_.host -eq $fqdn}) {
                                        Write-Output "Adding log forwarder ($fqdn) to vRealize Log Insight ($($vcfVrliDetails.fqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Warning "Adding log forwarder ($fqdn) to vRealize Log Insight ($($vcfVrliDetails.fqdn)): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Set-vRLILogForwarder -name $name -server $fqdn -protocol $protocol -port $port -acceptCert $acceptCert -sslEnabled $sslEnabled -testConnection $testConnection | Out-Null
                                    if (Get-vRlILogForwarder | Where-Object {$_.host -eq $fqdn}) {
                                        Write-Output "Adding log forwarder ($fqdn) to vRealize Log Insight ($($vcfVrliDetails.fqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Warning "Adding log forwarder ($fqdn) to vRealize Log Insight ($($vcfVrliDetails.fqdn)): POST_VALIDATION_FAILED"
                                    }          
                                }
                            } else {
                                Write-Warning "Adding log forwarder ($fqdn) to vRealize Log Insight ($($vcfVrliDetails.fqdn)), already exist: SKIPPED"
                            }
                        }
                    }
                }                         
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRLILogForwarder

Function Undo-vRLILogForwarder {
    <#
        .SYNOPSIS
        Removes a log forwarder destination to vRealize Log Insight

        .DESCRIPTION
        The Undo-vRLILogForwarder cmdlet removes log forwarder destination to vRealize Log Insight. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Removes a log forwarder destination from vRealize Log Insight

        .EXAMPLE
        Undo-vRLILogForwarder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -fqdn lax-vrli01.lax.rainpole.io -protocol SYSLOG -port 514
        This example removes a log forwarder to vRealize Log Insight using syslog over TCP 514.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateSet("CFAPI", "SYSLOG", "RAW")] [String]$protocol,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $false)] [ValidateSet("TCP", "UDP")] [String]$transport
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {                   
                            if ($protocol -eq 'SYSLOG' -and (-not $PsBoundParameters.ContainsKey('transport'))) {
                                Throw 'You must enter a transport for SYSLOG.'
                            } elseif ($protocol -eq 'SYSLOG' -and ($PsBoundParameters.ContainsKey('transport'))) {
                                if ($response = Get-vRlILogForwarder | Where-Object {$_.name -eq $name -and $_.host -eq $fqdn -and $_.protocol -eq $protocol -and $_.port -eq $port -and $_.transportProtocol -eq $transport}) {
                                    Remove-vRLILogForwarder -id $response.id | Out-Null
                                    if (Get-vRlILogForwarder | Where-Object { $_.name -eq $name -and $_.host -eq $fqdn -and $_.protocol -eq $protocol -and $_.port -eq $port -and $_.transportProtocol -eq $transport}) {
                                        Write-Error "Removing log forwarder ($fqdn) from vRealize Log Insight ($($vcfVrliDetails.fqdn)): POST_VALIDATION_FAILED"
                                    } else {
                                        Write-Output "Removing log forwarder ($fqdn) from vRealize Log Insight ($($vcfVrliDetails.fqdn)): SUCCESSFUL"
                                    }
                                } else {
                                    Write-Warning "Removing log forwarder ($fqdn) from vRealize Log Insight ($($vcfVrliDetails.fqdn)), configuration does not exist."
                                }
                            } else {
                                if ($response = Get-vRlILogForwarder | Where-Object {$_.name -eq $name -and $_.host -eq $fqdn -and $_.protocol -eq $protocol -and $_.port -eq $port}) {
                                    Remove-vRLILogForwarder -id $response.id | Out-Null
                                    if (Get-vRlILogForwarder | Where-Object {$_.name -eq $name -and $_.host -eq $fqdn -and $_.protocol -eq $protocol -and $_.port -eq $port}) {
                                        Write-Error "Removing log forwarder ($fqdn) from vRealize Log Insight ($($vcfVrliDetails.fqdn)): POST_VALIDATION_FAILED"
                                    } else {
                                        Write-Output "Removing log forwarder ($fqdn) from vRealize Log Insight ($($vcfVrliDetails.fqdn)): SUCCESSFUL"
                                    }
                                } else {
                                    Write-Warning "Removing log forwarder ($fqdn) from vRealize Log Insight ($($vcfVrliDetails.fqdn)), configuration does not exist."
                                }        
                            }
                        }
                    }
                }                         
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRLILogForwarder

Function Add-NsxtNodeProfileSyslogExporter {
    <#
        .SYNOPSIS
        Sets a syslog exporter on an NSX node profile to vRealize Log Insight

        .DESCRIPTION
        The Add-NsxtNodeProfileSyslogExporter cmdlet adds a syslog exporter for vRealize Log Insight to an NSX node
        profile for configuration of syslog on the NSX components included in the node profile.
        The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Validates that vRealize Log Insight has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Adds a syslog exporter on the default (All NSX Nodes) or specified node profile for NSX-T Data Center

        .EXAMPLE
        Add-NsxtNodeProfileSyslogExporter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01
        This example adds a syslog exporter to vRealize Log Insight for the default (All NSX Nodes) node profile.

        .EXAMPLE
        Add-NsxtNodeProfileSyslogExporter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -id "********-****-****-****-************"
        This example adds a syslog exporter to vRealize Log Insight for a specific node profile with the -id parameter.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if (!($PsBoundParameters.ContainsKey("id"))) {
            $id = "00000000-0000-0000-0000-000000000001" # Default: (All NSX Nodes)
        }
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                            if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                                if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                                    if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                                        if ($profileExists = Get-NsxtNodeProfile -id $id -ErrorAction SilentlyContinue) {
                                            if (!((Get-NsxtNodeProfile -id $id).syslog.exporters | Where-Object {$_.server -eq $vcfVrliDetails.fqdn -and $_.port -eq 514 -and $_.protocol -eq "TCP" -and $_.max_log_level -eq "INFO"})) {
                                                Set-NsxtNodeProfileSyslogExporter -id $id -server $vcfVrliDetails.fqdn -port 514 -protocol "TCP" -logLevel "INFO" | Out-Null
                                                    if ((Get-NsxtNodeProfile -id $id).syslog.exporters | Where-Object {$_.server -eq $vcfVrliDetails.fqdn -and $_.port -eq 514 -and $_.protocol -eq "TCP" -and $_.max_log_level -eq "INFO"}) {
                                                        Write-Output "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($($profileExists.display_name)) on NSX Manager ($($vcfNsxDetails.fqdn)): SUCCESSFUL"
                                                    } else {
                                                        Write-Error "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($id) in NSX Manager ($($vcfNsxDetails.fqdn)): POST_VALIDATION_FAILED"
                                                    }     
                                            } else {
                                                Write-Warning "Adding the syslog exporter ($($vcfVrliDetails.fqdn)) to the NSX node profile ($($profileExists.display_name)) in NSX Manager ($($vcfNsxDetails.fqdn)), already exist: SKIPPED"
                                            }
                                        } else {
                                            Write-Error "The NSX node profile ($id) does not exist in NSX Manager ($($vcfNsxDetails.fqdn)): PRE_VALIDATION_FAILED"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } 
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-NsxtNodeProfileSyslogExporter

Function Undo-NsxtNodeProfileSyslogExporter {
    <#
        .SYNOPSIS
        Removes all syslog exporters on an NSX node profile.

        .DESCRIPTION
        The Undo-NsxtNodeProfileSyslogExporter cmdlet removes a syslog exporter for vRealize Log Insight from
        an NSX node profile for configuration of syslog on the NSX components included in the node profile.
        The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to NSX Manager
        - Removes all syslog exporters on the default (All NSX Nodes) or specified node profile for NSX-T Data Center

        .EXAMPLE
        Undo-NsxtNodeProfileSyslogExporter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01
        This example removes all syslog exporters from the default (All NSX Nodes) node profile.

        .EXAMPLE
        Undo-NsxtNodeProfileSyslogExporter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -id "********-****-****-****-************"
        This example removes all syslog exporters from a specific node profile with the -id parameter.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if (!($PsBoundParameters.ContainsKey("id"))) {
            $id = "00000000-0000-0000-0000-000000000001"
        }
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain)) {
                    if (Test-NSXTConnection -server $vcfNsxDetails.fqdn) {
                        if (Test-NSXTAuthentication -server $vcfNsxDetails.fqdn -user $vcfNsxDetails.adminUser -pass $vcfNsxDetails.adminPass) {
                            if ($profileExists = Get-NsxtNodeProfile -id $id -ErrorAction SilentlyContinue) {
                                if (!(Get-NsxtNodeProfile -id $id | Where-Object {$null -eq $_.syslog})) {
                                    Remove-NsxtNodeProfileSyslogExporter -id $id | Out-Null
                                    if (Get-NsxtNodeProfile -id $id | Where-Object {$null -eq $_.syslog}) {
                                        Write-Output "Removing all syslog exporters from the NSX node profile ($($profileExists.display_name)) on NSX Manager ($($vcfNsxDetails.fqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing all syslog exporters from the NSX node profile ($id) in NSX Manager ($($vcfNsxDetails.fqdn)): POST_VALIDATION_FAILED"
                                    }     
                                } else {
                                    Write-Warning "Removing all syslog exporters from the NSX node profile ($($profileExists.display_name)) in NSX Manager ($($vcfNsxDetails.fqdn)), already removed: SKIPPED"
                                }
                            } else {
                                Write-Error "The NSX node profile ($id) does not exist in NSX Manager ($($vcfNsxDetails.fqdn)): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-NsxtNodeProfileSyslogExporter

Function Get-vROpsLogForwardingConfig {
    <#
        .SYNOPSIS
        Gets the vRealize Operations Manager log forwarding configuration.

        .DESCRIPTION
        The Get-vROpsLogForwardingConfig cmdlet gets the vRealize Operations Manager logging forwarding configuration.
        The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Gets the vRealize Operations Manager logging forwarding configuration

        .EXAMPLE
        Get-vROpsLogForwardingConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example returns the log forwarding configuration on vRealize Operations.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($vcfVropsDetails = Get-vROpsServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop) {
                                if (Test-vROpsConnection -server $vcfVropsDetails.loadBalancerFqdn) {   
                                    if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                                        if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                                            if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                                                $response = Get-vROpsLogForwarding
                                                $response
                                                if ($response.enabled -eq $false) {
                                                    Write-Warning "vRealize Operations ($($vcfVropsDetails.loadBalancerFqdn)) logging configuration to vRealize Log Insight status: Not enabled."
                                                } elseif ($response.enabled -eq $true -and $response.host -ne $vcfVrliDetails.fqdn) {
                                                    Write-Warning "vRealize Operations ($($vcfVropsDetails.loadBalancerFqdn)) logging configuration to vRealize Log Insight status: Not configured with $($vcfVrliDetails.fqdn)."                    
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vROpsLogForwardingConfig

Function Get-vRAvRLIConfig {
    <#
        .SYNOPSIS
        Returns the vRealize Log Insight logging configuration (CFAPI) on vRealize Automation.

        .DESCRIPTION
        The Get-vRAvRLIConfig cmdlet returns the vRealize Log Insight logging configuration for vRealize Automation.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values and connects to the first
        vRealize Automation appliance using the -rootPass value.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Validates that network connectivity is possible to the first vRealize Automation appliance
        - Returns the vRealize Log Insight configuration in vRealize Automation

        .EXAMPLE
        Get-vRAvRLIConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1!
        This example returns the vRealize Log Insight logging configuration on vRealize Automation.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($vraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop) {
                                if (Test-vRAConnection -server $vRADetails.node1IpAddress) {   
                                    $vmName = $vraDetails.fqdn | Select-Object -First 1
                                    $vmName = $vmName.Split(".")[0]
                                    if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                        $scriptCommand = "vracli vrli"
                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn
                                        if (($output.ScriptOutput).Contains('No vRLI integration configured')) {
                                            Write-Output "vRealize Automation integration with vRealize Log Insight status 'Not Configured'"
                                        } elseif (($output.ScriptOutput).Contains('agentId')) {
                                            $output.ScriptOutput | ConvertFrom-JSON
                                        } else {
                                            Write-Error "Returning the vRealize Automation integration with vRealize Log Insight: POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to locate a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"                                        
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vRAvRLIConfig

Function Set-vRAvRLIConfig {
    <#
        .SYNOPSIS
        Sets the vRealize Log Insight logging configuration (CFAPI) on vRealize Automation.

        .DESCRIPTION
        The Set-vRAvRLIConfig cmdlet sets the vRealize Log Insight logging configuration for vRealize Automation.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values and connects to the first
        vRealize Automation appliance using the -rootPass value.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Validates that network connectivity and authentication is possible to vRealize Log Insight
        - Validates that network connectivity is possible to the first vRealize Automation appliance
        - Sets the vRealize Log Insight configuration on vRealize Automation

        .EXAMPLE
        Set-vRAvRLIConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1! -protocol HTTPS
        This example sets the vRealize Log Insight logging configuration on vRealize Automation.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass,
        [Parameter (Mandatory = $true)] [ValidateSet("HTTPS", "HTTP")] [String]$protocol,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Int]$port
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($vraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop) {
                                if (Test-vRAConnection -server $vRADetails.node1IpAddress) {
                                    if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                                        if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                                            if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                                                $vmName = $vraDetails.fqdn | Select-Object -First 1
                                                $vmName = $vmName.Split('.')[0]
                                                if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {

                                                    # Set the uri format and default ports
                                                    if ($protocol -eq "HTTPS") {
                                                        $uriProtocol = $protocol.ToLower()
                                                        $uriPort = 9543 # CFAPI SSL Default
                                                    } elseif ($protocol -eq "HTTP") {
                                                        $uriProtocol = $protocol.ToLower()
                                                        $uriPort = 9000 # CFAPI Non-SSL Default
                                                    }

                                                    # Set the port if provided
                                                    if ($PsBoundParameters.ContainsKey("port")) {
                                                        $uriPort = $port
                                                    }

                                                    # Set the uri to the vRealize Log Insight cluster FQDN
                                                    $uriHost = $vcfVrliDetails.fqdn

                                                    # Run commands based on the selected protocol
                                                    if ($protocol -eq "HTTPS") {
                                                        $scriptCommand = "vracli vrli set " + $uriProtocol + "://" + $uriHost + ":" + $uriPort + " --force" # Must use --force to accept certificate.
                                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn
                                                    } else {
                                                        $scriptCommand = 'vracli vrli set ' + $uriProtocol + '://' + $uriHost + ':' + $uriPort
                                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn
                                                    }

                                                    $status = Get-vRAvRLIConfig -server $server -user $user -pass $pass -rootPass $rootPass      
                                                    if (($status).Contains("`"host`": `"$uriHost`"") -and ($status).Contains("`"port`": $uriPort") -and ($status).Contains("`"scheme`": `"$uriProtocol`"")) {
                                                        Write-Output 'Setting the vRealize Automation integration with vRealize Log Insight: SUCCESSFUL'
                                                    } elseif (($status).Contains('No vRLI integration configured')) {
                                                        Write-Warning 'vRealize Automation integration with vRealize Log Insight configuration not set: SKIPPED'
                                                    } else {
                                                        Write-Error 'Setting the vRealize Automation integration with vRealize Log Insight: POST_VALIDATION_FAILED'
                                                    }
                                                } else {
                                                    Write-Error "Unable to locate a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"                                        
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vRAvRLIConfig

Function Remove-vRAvRLIConfig {
    <#
        .SYNOPSIS
        Removes the vRealize Log Insight logging configuration (CFAPI) on vRealize Automation.

        .DESCRIPTION
        The Remove-vRAvRLIConfig cmdlet removes the vRealize Log Insight logging configuration for vRealize Automation.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values and connects to the first
        vRealize Automation appliance using the -rootPass value.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Validates that network connectivity is possible to the first vRealize Automation appliance
        - Unsets the vRealize Log Insight configuration in vRealize Automation

        .EXAMPLE
        Remove-vRAvRLIConfig -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -rootPass VMw@re1!
        This example removes the vRealize Log Insight logging configuration on vRealize Automation.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                      if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if ($vraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass -ErrorAction Stop) {
                                if (Test-vRAConnection -server $vRADetails.node1IpAddress) {   
                                    $vmName = $vraDetails.fqdn | Select-Object -First 1
                                    $vmName = $vmName.Split(".")[0]
                                    if ((Get-VM -Name $vmName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue )) {
                                        $scriptCommand = "vracli vrli unset"
                                        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn
                                        if (($output.ScriptOutput).Contains('Clearing vRLI integration configuration')) {
                                            Write-Output "Clearing the vRealize Automation integration with vRealize Log Insight: SUCCESSFUL"
                                        } elseif (($output.ScriptOutput).Contains('No vRLI integration configured')) {
                                            Write-Warning "vRealize Automation integration with vRealize Log Insight not set: SKIPPED"
                                        } else {
                                            Write-Warning "Clearing the vRealize Automation integration with vRealize Log Insight: POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to locate a virtual machine named ($vmName) in vCenter Server ($($vcfVcenterDetails.fqdn)) inventory: PRE_VALIDATION_FAILED"                                        
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Remove-vRAvRLIConfig

Function Enable-vRLIContentPack {
    <#
        .SYNOPSIS
        Enables the vRealize Log Insight content pack from the marketplace.

        .DESCRIPTION
        The Enable-vRLIContentPack cmdlet installs a designated vRealize Log Insight content pack from the online
        Content Pack Marketplace hosted on GitHub.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Validates that network connectivity is possible to vRealize Log Insight
        - Installs the vRealize Log Insight content pack selected from the marketplace

        .EXAMPLE
        Enable-vRLIContentPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -contentPack VRO
        This examples installs the vRealize Orchestrator content pack from the marketplace.
        #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateSet('VSPHERE','VSAN','NSX','WSA','VRSLCM','VROPS','VRNI','VRA','VRO','SRM','LINUX','LINUX-SYSTEMD')] [String]$contentPack
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            # Define the supported content pack namespaces
                            if ($contentPack -eq 'VSPHERE') {$contentPackNamespace = 'com.vmware.vsphere'}
                            if ($contentPack -eq 'VSAN') {$contentPackNamespace = 'com.vmware.vsan'}
                            if ($contentPack -eq 'NSX') {$contentPackNamespace = 'com.vmware.nsxt'}
                            if ($contentPack -eq 'WSA') {$contentPackNamespace = 'com.vmware.vidm'}
                            if ($contentPack -eq 'VRSLCM') {$contentPackNamespace = 'com.vmware.vrslcm801'}
                            if ($contentPack -eq 'VROPS') {$contentPackNamespace = 'com.vmware.vrops67'}
                            if ($contentPack -eq 'VRNI') {$contentPackNamespace = 'om.vmware.vrni'}
                            if ($contentPack -eq 'VRA') {$contentPackNamespace = 'com.vmware.vra.83'}
                            if ($contentPack -eq 'VRO') {$contentPackNamespace = 'com.vmware.vro.83'}
                            if ($contentPack -eq 'SRM') {$contentPackNamespace = 'com.vmware.srm81'}                            
                            if ($contentPack -eq 'LINUX') {$contentPackNamespace = 'com.linux'}
                            if ($contentPack -eq 'LINUX-SYSTEMD') {$contentPackNamespace = 'com.linux.systemd'}

                            $index = Get-vRLIMarketplaceMetadata -index
                            $contentPackFile = ($index | Where-Object { $_.namespace -eq $contentPackNamespace }).filename
                            $contentPackName = ($index| Where-Object { $_.namespace -eq $contentPackNamespace }).name
                            $contentPackVersion = ($index | Where-Object { $_.namespace -eq $contentPackNamespace }).contentVersion

                            if ($response = Get-vRLIMarketplaceMetadata) {
                                $uri = ($response | Where-Object { $_.name -eq $contentPackFile }).url
                                $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $ghHeaders
                                $json = $response | ConvertTo-Json -Depth 100 -Compress
                            } else {
                                Write-Warning "Retrieving content pack ($contentPackFile) metadata from the marketplace: PRE_VALIDATION_FAILED"
                            }

                            if (Get-vRLIContentPack | Where-Object { $_.name -eq $contentPackName }) {
                                Write-Warning "Installing content pack ($contentPackName v$contentPackVersion) to vRealize Log Insight ($($vcfVrliDetails.fqdn)), already exists: SKIPPED"
                            } else {
                                if ($json) {
                                    Install-vRLIContentPack -json $json | Out-Null
                                    if ($contentPackStatus = (Get-vRLIContentPack | Where-Object { $_.name -eq $contentPackName })) {
                                        Write-Output "Installing content pack ($contentPackName v$contentPackVersion) to vRealize Log Insight ($($vcfVrliDetails.fqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Installing content pack ($contentPackName v$contentPackVersion) to vRealize Log Insight ($($vcfVrliDetails.fqdn)): POST_VALIDATION_FAILED"
                                    }   
                                } else {
                                    Write-Error "Installing content pack ($contentPackName v$contentPackVersion) to vRealize Log Insight ($($vcfVrliDetails.fqdn)): PRE_VALIDATION_FAILED"
                                }
                            }       
                        }          
                    }         
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Enable-vRLIContentPack

Function Update-vRLIContentPack {
    <#
        .SYNOPSIS
        Updates the vRealize Log Insight content pack from the marketplace.

        .DESCRIPTION
        The Update-vRLIContentPack cmdlet updates a designated vRealize Log Insight content pack from the online
        Content Pack Marketplace hosted on GitHub.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Validates that network connectivity is possible to vRealize Log Insight
        - Updates the vRealize Log Insight content pack selected from the marketplace

        .EXAMPLE
        Update-vRLIContentPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -contentPack NSX
        This example updates the vRealize Log Insight content pack for NSX to the latest version from the marketplace.
        #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateSet('VSPHERE','VSAN','NSX','WSA','VRSLCM','VROPS','VRNI','VRA','VRO','SRM','LINUX','LINUX-SYSTEMD')] [String]$contentPack
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrliDetails = Get-vRLIServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRLIConnection -server $vcfVrliDetails.fqdn) {
                        if (Test-vRLIAuthentication -server $vcfVrliDetails.fqdn -user $vcfVrliDetails.adminUser -pass $vcfVrliDetails.adminPass) {
                            # Define the supported content pack namespaces
                            if ($contentPack -eq 'VSPHERE') {$contentPackNamespace = 'com.vmware.vsphere'}
                            if ($contentPack -eq 'VSAN') {$contentPackNamespace = 'com.vmware.vsan'}
                            if ($contentPack -eq 'NSX') {$contentPackNamespace = 'com.vmware.nsxt'}
                            if ($contentPack -eq 'WSA') {$contentPackNamespace = 'com.vmware.vidm'}
                            if ($contentPack -eq 'VRSLCM') {$contentPackNamespace = 'com.vmware.vrslcm801'}
                            if ($contentPack -eq 'VROPS') {$contentPackNamespace = 'com.vmware.vrops67'}
                            if ($contentPack -eq 'VRNI') {$contentPackNamespace = 'om.vmware.vrni'}
                            if ($contentPack -eq 'VRA') {$contentPackNamespace = 'com.vmware.vra.83'}
                            if ($contentPack -eq 'VRO') {$contentPackNamespace = 'com.vmware.vro.83'}
                            if ($contentPack -eq 'SRM') {$contentPackNamespace = 'com.vmware.srm81'}                            
                            if ($contentPack -eq 'LINUX') {$contentPackNamespace = 'com.linux'}
                            if ($contentPack -eq 'LINUX-SYSTEMD') {$contentPackNamespace = 'com.linux.systemd'}

                            $index = Get-vRLIMarketplaceMetadata -index
                            $contentPackFile = ($index | Where-Object { $_.namespace -eq $contentPackNamespace }).filename
                            $contentPackName = ($index | Where-Object { $_.namespace -eq $contentPackNamespace }).name
                            $contentPackVersion = ($index | Where-Object { $_.namespace -eq $contentPackNamespace }).contentVersion

                            if ($status = Get-vRLIContentPack | Where-Object { $_.name -eq $contentPackName }) {
                                if ($response = Get-vRLIMarketplaceMetadata) {
                                    $uri = ($response | Where-Object { $_.name -eq $contentPackFile }).url
                                    $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $ghHeaders
                                    $json = $response | ConvertTo-Json -Depth 100 -Compress
                                    if ($status.contentVersion -lt $contentPackVersion) {
                                        Install-vRLIContentPack -update -json $json | Out-Null
                                        if (Get-vRLIContentPack | Where-Object {$_.name -eq $contentPackName -and $_.contentVersion -eq $contentPackVersion}) {
                                            Write-Output "Updating the content pack ($contentPackName) to version v$contentPackVersion on vRealize Log Insight ($($vcfVrliDetails.fqdn)): SUCCESSFUL"
                                        } else {
                                            Write-Error "Updating the content pack ($contentPackName) to version v$contentPackVersion on vRealize Log Insight ($($vcfVrliDetails.fqdn)): POST_VALIDATION_FAILED"
                                        }   
                                    } else {
                                        Write-Warning "Updating the content pack ($contentPackName) to version v$contentPackVersion on vRealize Log Insight ($($vcfVrliDetails.fqdn)), no update needed: SKIPPED"
                                    }
                                } else {
                                    Write-Error "Retrieving content pack ($contentPackFile) metadata from the marketplace: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Updating content pack ($contentPackName) to version v$contentPackVersion on vRealize Log Insight ($($vcfVrliDetails.fqdn)), not installed: PRE_VALIDATION_FAILED"
                            }   
                        }          
                    }         
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-vRLIContentPack

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region I N T E L L I G E N T O P E R A T I O N S M A N A G E M E N T F U N C T I O N S ###########

Function Export-vROPsJsonSpec {
    <#
        .SYNOPSIS
        Create vRealize Operations Manager Deployment JSON specification

        .DESCRIPTION
        The Export-vROPsJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook
        to deploy vRealize Operations Manager using vRealize Suite Lifecycle Manager. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values.
        - Validates that the Planning and Preparation provided is available
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the License, Certificate and Password in the Planning and Prep Preparation workbook have been
        created in vRealize Suite Lifecycle Manager Locker
        - Generates the deployment JSON specification file using the Planning and Preparation workbook and details
        from vRealize Suite Lifecycle Manager named 'vropsDeploymentSpec.json'

        .EXAMPLE
        Export-vROPsJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example creates a JSON specification file for deploying vRealize Operations Manager using the Planning and Preparation Workbook data

        .EXAMPLE
        Export-vROPsJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx -nested
        This example creates a reduce footprint JSON specification file for deploying vRealize Operations Manager using the Planning and Preparation Workbook data
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$nested
    )

    Try {

        if (!$PsBoundParameters.ContainsKey("workbook")) {
            $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
        } else {
            if (!(Test-Path -Path $workbook)) {
                Write-Error  "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found"
                Break
            }
        }

        $pnpWorkbook = Open-ExcelPackage -Path $workbook

        ### Obtain Configuration Information from vRealize Suite Lifecycle Manager
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S'
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if ($pnpWorkbook.Workbook.Names["vrops_license"].Value) {
                                $licenseKey = $pnpWorkbook.Workbook.Names["vrops_license"].Value
                            } else {
                                $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value
                            }
                            $vropsLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey}
                            if ($vropsLicense.key -eq $licenseKey) {
                                if ($vropsCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_hostname"].Value}) {
                                    if ($defaultPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value) {
                                        if ($vropsPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["xreg_vrops_root_password_alias"].Value) {
                                            if ($vcfVersion -eq "4.5.0") {
                                                $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.userName -match (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "@vsphere.local")}
                                            } else {
                                                $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value)
                                            }
                                            $datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value}
                                            if ($datacenterName) {
                                                $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S'
                                                $xintEnvironment = Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value}
                                                
                                                # $pnpWorkbook.Workbook.Names["xint-m01-fd-vrops"].Value
                                                $infrastructurePropertiesObject = @()
                                                $infrastructurePropertiesObject += [pscustomobject]@{
                                                    'dataCenterVmid'        = $datacenterName.dataCenterVmid
                                                    'regionName'            = "default"
                                                    'zoneName'                = "default"
                                                    'vCenterName'            = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0]
                                                    'vCenterHost'            = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value
                                                    'vcUsername'            = $vcCredentials.userName
                                                    'vcPassword'            = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias))
                                                    'acceptEULA'            = "true"
                                                    'enableTelemetry'        = "true"
                                                    'defaultPassword'        = ("locker:password:" + $($defaultPassword.vmid) + ":" + $($defaultPassword.alias))
                                                    'certificate'            = ("locker:certificate:" + $($vropsCertificate.vmid) + ":" + $($vropsCertificate.alias))
                                                    'cluster'                = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value)
                                                    'storage'                = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                                    'diskMode'                = "thin"
                                                    'network'                = $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value
                                                    'masterVidmEnabled'        = "false"
                                                    'dns'                    = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value)
                                                    'domain'                = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value
                                                    'gateway'                = $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value
                                                    'netmask'                = $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value
                                                    'searchpath'            = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value
                                                    'timeSyncMode'            = "ntp"
                                                    'ntp'                    = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value
                                                    'isDhcp'                = "false"
                                                    'vcfProperties'            = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}'
                                                }
                                                $infrastructureObject = @()
                                                $infrastructureObject += [pscustomobject]@{
                                                    'properties'    = ($infrastructurePropertiesObject | Select-Object -Skip 0)
                                                }

                                                ### Generate the Properties Details
                                                $productPropertiesObject = @()
                                                $productPropertiesObject += [pscustomobject]@{
                                                    'certificate'                    = ("locker:certificate:" + $($vropsCertificate.vmid) + ":" + $($vropsCertificate.alias))
                                                    'productPassword'                = ("locker:password:" + $($vropsPassword.vmid) + ":" + $($vropsPassword.alias))
                                                    'licenseRef'                    = ("locker:license:" + $($vropsLicense.vmid) + ":" + $($vropsLicense.alias))
                                                    'disableTls'                    = "TLSv1,TLSv1.1"
                                                    'fipsMode'                        = "false"
                                                    'timeSyncMode'                    = "ntp"
                                                    'masterVidmEnabled'                = $true
                                                    'ntp'                            = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value
                                                    'affinityRule'                    = $false
                                                    'configureAffinitySeparateAll'  = "true"
                                                    'deployOption'                    = $pnpWorkbook.Workbook.Names["xreg_vrops_appliance_size"].Value.ToLower()
                                                    'isCaEnabled'                   = "false"
                                                }

                                                #### Generate vRealize Operations Manager Cluster Details
                                                $clusterVipProperties = @()
                                                $clusterVipProperties += [pscustomobject]@{
                                                    'hostName'    = $pnpWorkbook.Workbook.Names["xreg_vrops_virtual_fqdn"].Value
                                                }
                                                $clusterVipsObject = @()
                                                $clusterVipsObject += [pscustomobject]@{
                                                    'type'            = "vrops-cluster"
                                                    'properties'    = ($clusterVipProperties | Select-Object -Skip 0)
                                                }
                                                $clusterObject = @()
                                                $clusterObject += [pscustomobject]@{
                                                'clusterVips'    = $clusterVipsObject
                                                }

                                                #### Generate vRealize Operations Manager Node Details
                                                $masterProperties = New-Object -TypeName psobject
                                                $masterProperties | Add-Member -notepropertyname 'vmName' -notepropertyvalue $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_hostname"].Value
                                                $masterProperties | Add-Member -notepropertyname 'hostName' -notepropertyvalue $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_fqdn"].Value
                                                $masterProperties | Add-Member -notepropertyname 'ip' -notepropertyvalue $pnpWorkbook.Workbook.Names["xreg_vrops_nodea_ip"].Value
                                                $masterProperties | Add-Member -notepropertyname 'gateway' -notepropertyvalue $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value
                                                $masterProperties | Add-Member -notepropertyname 'domain' -notepropertyvalue $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value
                                                $masterProperties | Add-Member -notepropertyname 'searchpath' -notepropertyvalue $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value
                                                if ($null -eq $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value) {
                                                    $masterProperties | Add-Member -notepropertyname 'dns' -notepropertyvalue $pnpWorkbook.Workbook.Names["region_dns1_ip"].Value
                                                } else {
                                                    $masterProperties | Add-Member -notepropertyname 'dns' -notepropertyvalue ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value)
                                                }
                                                $masterProperties | Add-Member -notepropertyname 'netmask' -notepropertyvalue $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value
                                                $masterProperties | Add-Member -notepropertyname 'timeZone' -notepropertyvalue "UTC"
                                                $masterProperties | Add-Member -notepropertyname 'vCenterHost' -notepropertyvalue $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value
                                                $masterProperties | Add-Member -notepropertyname 'cluster' -notepropertyvalue ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value)
                                                $masterProperties | Add-Member -notepropertyname 'network' -notepropertyvalue $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value
                                                $masterProperties | Add-Member -notepropertyname 'storage' -notepropertyvalue $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                                $masterProperties | Add-Member -notepropertyname 'diskMode' -notepropertyvalue "thin"
                                                $masterProperties | Add-Member -notepropertyname 'vCenterName' -notepropertyvalue ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0]
                                                $masterProperties | Add-Member -notepropertyname 'vcUsername' -notepropertyvalue $vcCredentials.userName
                                                $masterProperties | Add-Member -notepropertyname 'vcPassword' -notepropertyvalue ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias))
                                                if ($null -eq $pnpWorkbook.Workbook.Names["xregion_ntp2_server"].Value) {
                                                    $masterProperties | Add-Member -notepropertyname 'ntp' -notepropertyvalue $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value
                                                }
                                                else {
                                                    $masterProperties | Add-Member -notepropertyname 'ntp' -notepropertyvalue ($pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value + "," + $pnpWorkbook.Workbook.Names["xregion_ntp2_server"].Value)
                                                }
                                                if ($vcfVersion -eq "4.4.0") {
                                                    $masterProperties | Add-Member -notepropertyname 'extendedStorage' -notepropertyvalue $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                                }
                                                $replicaProperties = @()
                                                $replicaProperties += [pscustomobject]@{
                                                    'vmName'    = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_hostname"].Value
                                                    'hostName'    = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_fqdn"].Value
                                                    'ip'        = $pnpWorkbook.Workbook.Names["xreg_vrops_nodeb_ip"].Value
                                                }
                                                $dataProperties = @()
                                                $dataProperties += [pscustomobject]@{
                                                    'vmName'    = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_hostname"].Value
                                                    'hostName'    = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_fqdn"].Value
                                                    'ip'        = $pnpWorkbook.Workbook.Names["xreg_vrops_nodec_ip"].Value
                                                }
                                                $remoteCollector1Properties = @()
                                                $remoteCollector1Properties += [pscustomobject]@{
                                                    'vmName'        = $pnpWorkbook.Workbook.Names["region_vropsca_hostname"].Value
                                                    'hostName'        = $pnpWorkbook.Workbook.Names["region_vropsca_fqdn"].Value
                                                    'ip'            = $pnpWorkbook.Workbook.Names["region_vropsca_ip"].Value
                                                    'deployOption'  = "smallrc"
                                                    'gateway'       = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value
                                                    'domain'        = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value
                                                    'searchpath'    = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value
                                                    'dns'           = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value)
                                                    'netmask'       = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value
                                                    'timeZone'      = "UTC"
                                                    'vCenterHost'   = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value
                                                    'cluster'       = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value)
                                                    'network'       = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value
                                                    'storage'       = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                                    'diskMode'      = "thin"
                                                    'vCenterName'   = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0]
                                                    'vcUsername'    = $vcCredentials.userName
                                                    'vcPassword'    = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias))
                                                    'ntp'           = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value
                                                }
                                                $remoteCollector2Properties = @()
                                                $remoteCollector2Properties += [pscustomobject]@{
                                                    'vmName'    = $pnpWorkbook.Workbook.Names["region_vropscb_hostname"].Value
                                                    'hostName'    = $pnpWorkbook.Workbook.Names["region_vropscb_fqdn"].Value
                                                    'ip'        = $pnpWorkbook.Workbook.Names["region_vropscb_ip"].Value
                                                    'deployOption'  = "smallrc"
                                                    'gateway'       = $pnpWorkbook.Workbook.Names["reg_seg01_gateway_ip"].Value
                                                    'domain'        = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value
                                                    'searchpath'    = $pnpWorkbook.Workbook.Names["region_ad_child_fqdn"].Value
                                                    'dns'           = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value)
                                                    'netmask'       = $pnpWorkbook.Workbook.Names["reg_seg01_mask_overlay_backed"].Value
                                                    'timeZone'      = "UTC"
                                                    'vCenterHost'   = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value
                                                    'cluster'       = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value)
                                                    'network'       = $pnpWorkbook.Workbook.Names["reg_seg01_name"].Value
                                                    'storage'       = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                                    'diskMode'      = "thin"
                                                    'vCenterName'   = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0]
                                                    'vcUsername'    = $vcCredentials.userName
                                                    'vcPassword'    = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias))
                                                    'ntp'           = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value
                                                }
                                                $nodesObject = @()
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "master"
                                                    'properties'    = ($masterProperties | Select-Object -Skip 0)
                                                }
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "replica"
                                                    'properties'    = ($replicaProperties | Select-Object -Skip 0)
                                                }
                                                if (!$PsBoundParameters.ContainsKey("nested")) {
                                                    $nodesobject += [pscustomobject]@{
                                                        'type'            = "data"
                                                        'properties'    = ($dataProperties | Select-Object -Skip 0)
                                                    }
                                                }
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "remotecollector"
                                                    'properties'    = ($remoteCollector1Properties | Select-Object -Skip 0)
                                                }
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "remotecollector"
                                                    'properties'    = ($remoteCollector2Properties | Select-Object -Skip 0)
                                                }

                                                #### Generate the vRealize Operations Manager Properties Section
                                                if ($vcfVersion -eq "4.3.0") { $vropsVersion = "8.4.0"}
                                                if ($vcfVersion -eq "4.3.1") { $vropsVersion = "8.5.0"}
                                                if ($vcfVersion -eq "4.4.0") { $vropsVersion = "8.6.2"}
                                                if ($vcfVersion -eq "4.4.1") { $vropsVersion = "8.6.2"}
                                                if ($vcfVersion -eq "4.5.0") { $vropsVersion = "8.6.3"}
                                                $productsObject = @()
                                                $productsObject += [pscustomobject]@{
                                                    'id'             = "vrops"
                                                    'version'        = $vropsVersion
                                                    'properties'    = ($productPropertiesObject  | Select-Object -Skip 0)
                                                    'clusterVIP'    = ($clusterObject  | Select-Object -Skip 0)
                                                    'nodes'            = $nodesObject    
                                                }
                                                if (!($xintEnvironment)) { 
                                                    $vropsDeploymentObject = @()
                                                    $vropsDeploymentObject += [pscustomobject]@{
                                                        'environmentName'       = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value
                                                        'infrastructure'        = ($infrastructureObject  | Select-Object -Skip 0)
                                                        'products'              = $productsObject     
                                                    }
                                                } else {
                                                    $vropsDeploymentObject = @()
                                                    $vropsDeploymentObject += [pscustomobject]@{
                                                        'environmentId'         = $xintEnvironment.environmentId
                                                        'environmentName'       = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value
                                                        'infrastructure'        = ($infrastructureObject  | Select-Object -Skip 0)
                                                        'products'              = $productsObject     
                                                    }
                                                }

                                                $vropsDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vropsDeploymentSpec.json" 
                                                Write-Output "Creation of Deployment JSON Specification file for vRealize Operations Manager: SUCCESSFUL"                            
                                            } else {
                                                Write-Error "Datacenter Provided in the Planning and Preparation Workbook '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value)' does not exist: PRE_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Root Password with alias '$($pnpWorkbook.Workbook.Names["xreg_vrops_root_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Admin Password with alias '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["xreg_vrops_virtual_hostname"].Value)' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "License with alias '$licenseKey' not found in the vRealize Suite Lifecycle Manager Locker: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }    
            }
        }
        Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Export-vROPsJsonSpec

Function New-vROPSDeployment {
    <#
        .SYNOPSIS
        Deploy vRealize Operations Manager to vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The New-vROPSDeployment cmdlet deploys vRealize Operations Manager via vRealize Suite Lifecycle Manager. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Suite Lifecycle Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the environment does not already exist in vRealize Suite Lifecycle Manager
        - Requests a new deployment of vRealize Operations Manager via vRealize Suite Lifecycle Manager

        .EXAMPLE
        New-vROPSDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example starts a deployment of vRealize Operations Manager via vRealize Suite Lifecycle Manager using the Planning and Preparation Workbook data

        .EXAMPLE
        New-vROPSDeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx -nested
        This example starts a reduce footprint deployment of vRealize Operations Manager via vRealize Suite Lifecycle Manager using the Planning and Preparation Workbook data
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$nested
    )

    if (!$PsBoundParameters.ContainsKey("workbook")) {
        $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
    } else {
        if (!(Test-Path -Path $workbook)) {
            Write-Error  "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found"
            Break
        }
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (!$PsBoundParameters.ContainsKey("nested")) {
                                Export-vROPSJsonSpec -workbook $workbook -server $server -user $user -pass $pass | Out-Null
                            } else {
                                Export-vROPSJsonSpec -workbook $workbook -server $server -user $user -pass $pass -nested | Out-Null
                            }
                            $json = (Get-Content -Raw .\vropsDeploymentSpec.json)
                            $jsonSpec = $json | ConvertFrom-Json
                            if (!((Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName}).products.id -contains $jsonSpec.products.id)) {
                                if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.productPassword.Split(":")[3])) {
                                    if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) {
                                        if (Get-vRSLCMLockerLicense | Where-Object {$_.alias -Match $($jsonSpec.products.properties.licenseRef.Split(":")[3])}) {
                                            if ($jsonSpec.environmentId) {
                                                $newRequest = Add-vRSLCMEnvironment -json $json -environmentId $jsonSpec.environmentId -addProduct -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
                                            } else {
                                                $newRequest = Add-vRSLCMEnvironment -json $json -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
                                            }
                                            if ($newRequest) {
                                                if ($PsBoundParameters.ContainsKey("monitor")) {
                                                    Start-Sleep 10
                                                    Watch-vRSLCMRequest -vmid $($newRequest.requestId)
                                                } else {
                                                    Write-Output "Deployment Rquest for vRealize Operations Manager Submitted Successfully (Request Ref: $($newRequest.requestId))"
                                                }
                                            } else {
                                                Write-Error "Request to deploy vRealize Operations Manager failed, check the vRealize Suite Lifecycle Manager UI: POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "License in vRealize Suite Lifecycle Manager ($($vrvcfVrslcmDetailsslcm.fqdn)) Locker with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])), does not exist: PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])), does not exist: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "vRealize Operations Manager in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)), already exists: SKIPPED"
                            }
                        }
                    }
                } 
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vROPSDeployment

Function Import-vROPSUserAccount {
    <#
        .SYNOPSIS
        Import a user from Workspace ONE Access and assign access in vRealize Operations Manager

        .DESCRIPTION
        The Import-vROPSUserAccount cmdlet imports a user from Workspace ONE Access and assigns access in vRealize
        Operations Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that Workspace ONE Access has been configured as an authentication source
        - Validates the user account provided can be found in vRealize Operations Manager
        - Validated the role exists within vRealize Operations Manager
        - Imports the user and assigns the vRealize Operations Manager role

        .EXAMPLE
        Import-vROPSUserAccount -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -userName nigel.mccloud -role Administrator
        This example imports a user into vRealize Operations Manager and assigns the role
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (!(Get-vROPSUserAccount -username $userName)) {
                                if (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}) {
                                    if ($userAccount = Search-vROPSUserAccount -sourceId (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}).id -domain $domain -userName ($userName + '@' + $domain)) {
                                        if (Get-vROPSAuthRole -name $role -ErrorAction SilentlyContinue) {
                                            Add-vROPSUserAccount -sourceId (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}).id -userName $userAccount.name -lastName $userAccount.lastName -firstName $userAccount.firstName -distinguishedName $domain -role $role | Out-Null
                                            if (Get-vROPSUserAccount -username $userName) {
                                                Write-Output "Importing user account into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($userName + '@' + $domain)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Importing user account into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($userName + '@' + $domain)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Unable to locate role in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($role): PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to locate user account in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($userName): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to locate Authentication Source in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) type (vIDMAuthSource): PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Importing user account into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($userName + '@' + $domain)), already performed: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Import-vROPSUserAccount

Function Import-vROPSUserGroup {
    <#
        .SYNOPSIS
        Import a Group from Workspace ONE Access and assign access in vRealize Operations Manager

        .DESCRIPTION
        The Import-vROPSUserGroup cmdlet imports a Group from Workspace ONE Access and assigns access in vRealize
        Operations Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that Workspace ONE Access has been configured as an authentication source
        - Validates the user group provided can be found in vRealize Operations Manager
        - Validated the role exists within vRealize Operations Manager
        - Imports the group and assigns the vRealize Operations Manager role

        .EXAMPLE
        Import-vROPSUserGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -groupName gg-vrops-admins -role Administrator
        This example imports a group into vRealize Operations Manager and assigns the role
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (!(Get-vROPSUserGroup -name ($groupName + '@' + $domain))) {
                                if (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}) {
                                    if (Search-vROPSUserGroup -sourceId (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}).id -domain $domain -groupName ($groupName + '@' + $domain)) {
                                        if (Get-vROPSAuthRole -name $role -ErrorAction SilentlyContinue) {
                                            Add-vROPSUserGroup -sourceId (Get-vROPSAuthSource | Where-Object {$_.name -eq "vIDMAuthSource"}).id -userGroup ($groupName + '@' + $domain) -role $role | Out-Null
                                            if (Get-vROPSUserGroup -name ($groupName + '@' + $domain)) {
                                                Write-Output "Importing User Group into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($groupName + '@' + $domain)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Importing User Group into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($groupName + '@' + $domain)): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Unable to locate Role in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($role): PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to locate User Group in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($groupName): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to locate Authentication Source in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) type (vIDMAuthSource): PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Importing User Group into vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($groupName + '@' + $domain)), already performed: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Import-vROPSUserGroup

Function Register-vROPSWorkloadDomain {
    <#
        .SYNOPSIS
        Connect a Workload Domain to vRealize Operations Manager

        .DESCRIPTION
        The Register-vROPSWorkloadDomain cmdlet connects a Workload Domain to vRealize Operations Manager. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates if the Workload Domain is already connected to vRealize Operations Manager
        - Enables/Disables connecting the Workload Domain to vRealize Operations Manager

        .EXAMPLE
        Register-vROPSWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status ENABLED
        This example ENABLES the Workload Domain in vRealize Opertations Manager

        .EXAMPLE
        Register-vROPSWorkloadDomain -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -status DISABLED
        This example DISABLES the Workload Domain in vRealize Opertations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateSet("ENABLED", "DISABLED")] [String]$status
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                        if ((Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -ne $status) { 
                            Set-VCFvROPSConnection -domainId (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id -status $status | Out-Null
                            Start-Sleep 10
                            Do {
                                $configStatus = (Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status
                            } Until ($configStatus -ne "IN_PROGRESS")
                            if ((Get-VCFvROPSConnection | Where-Object {$_.domainId -eq (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}).id}).status -eq $status) { 
                                Write-Output "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vcfVropsDetails.loadBalancerFqdn)) for domain ($domain): SUCCESSFUL"
                            } else {
                                Write-Error "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vcfVropsDetails.loadBalancerFqdn)) for domain ($domain): POST_VALIDATION_FAILED"
                            }
                        } else {
                            Write-Warning "Enabling Workload Domain Intergation with vRealize Opertations Manager ($($vcfVropsDetails.loadBalancerFqdn)) for domain ($domain), already enabled: SKIPPED"
                        }
                    } else {
                        Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Register-vROPSWorkloadDomain

Function Add-vROPSGroupRemoteCollectors {
    <#
        .SYNOPSIS
        Creates a Remote Collectors Group and assigns nodes in vRealize Operations Manager

        .DESCRIPTION
        The Add-vROPSGroupRemoteCollectors cmdlet creates a Remote Collector Group in vRealize Operations Manager and
        assigns the remote collector nodes. The cmdlet connects to SDDC Manager using the -server, -user, and -password
        values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Gathers the Remote Collector node details
        - Creates a new Remote Collector Group in vRealize Operations Manager
        - Assigns the deployed Remote Collector nodes to the Remote Collector Group in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSGroupRemoteCollectors -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors"
        This example creats a Remote Collector Group called 'sfo-remote-collectors' and assigns the Remove Collector Nodes in vRealize Opertations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (!(Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName})) {
                                $collectors = (Get-vROPSCollector | Where-Object {$_.type -eq "REMOTE"} | Select-Object id).id
                                $collectorIds = $collectors -join ","
                                Add-vROPSCollectorGroup -name $collectorGroupName -collectorIds $collectorIds
                                if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) {
                                    Write-Output "Creating Remote Collector Group in ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName): SUCCESSFUL"
                                } else {
                                    Write-Error "Creating Remote Collector Group in ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Creating Remote Collector Group in ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), already exists: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSGroupRemoteCollectors

Function Update-vROPSAdapterVcenter {
    <#
        .SYNOPSIS
        Updates the assigned Remote Collector Group for vCenter Adapter

        .DESCRIPTION
        The Update-vROPSAdapterVcenter cmdlet updates the assigned Remote Collector Group for all vCenter Adapters in
        vRealize Operations Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Remote Collector Group exits in vRealize Operations Manager
        - Gathers the unique ID of the Remote Collector Group
        - Gathers the vCenter Adapter details from vRelize Operations Manager
        - Updates the assigned Remote Collector Group for the vCenter Adapter in vRelize Operations Manager

        .EXAMPLE
        Update-vROPSAdapterVcenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors"
        This example updates all vCenter Adapters to use the Remote Collector Group named 'sfo-remote-collectors'
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if ($collectorGroupId = (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id) {
                                $adapters = Get-vROPSAdapter | Where-Object {$_.resourceKey.adapterKindKey -eq "VMWARE"}
                                Foreach ($adapter in $adapters) {
                                    $vcurl = ((Get-vROPSAdapter -id $adapter.id).resourceKey.resourceIdentifiers | Where-Object {$_.identifierType.name -eq "VCURL"}).value
                                    $json = '{
                                    "resourceKey" : {
                                    "name" : "'
+ $($adapter.resourceKey.name) +'",
                                    "adapterKindKey" : "VMWARE",
                                    "resourceKindKey" : "VMwareAdapter Instance",
                                    "resourceIdentifiers" : [ {
                                        "identifierType" : {
                                        "name" : "AUTODISCOVERY",
                                        "dataType" : "STRING",
                                        "isPartOfUniqueness" : true
                                        },
                                        "value" : "true"
                                    }, {
                                        "identifierType" : {
                                        "name" : "PROCESSCHANGEEVENTS",
                                        "dataType" : "STRING",
                                        "isPartOfUniqueness" : true
                                        },
                                        "value" : "true"
                                    }, {
                                        "identifierType" : {
                                        "name" : "VCURL",
                                        "dataType" : "STRING",
                                        "isPartOfUniqueness" : true
                                        },
                                        "value" : "'
+ $vcurl +'"
                                    } ]
                                    },
                                    "description" : "'
+ $($adapter.description) +'",
                                    "id" : "'
+ $($adapter.id) +'",
                                    "collectorGroupId": "'
+ $($collectorGroupId) +'"
                                    }'


                                    $json | Out-File .\updateAdapter.json
                                    if (!($($adapter.collectorGroupId) -eq $collectorGroupId)) {
                                        Set-vROPSAdapter -json .\updateAdapter.json | Out-Null
                                        Write-Output "Assiging vCenter Adapter ($($adapter.resourceKey.name)) to Remote Collector Group ($collectorGroupName): SUCCESSFUL"
                                    } else {
                                        Write-Warning "Assiging vCenter Adapter ($($adapter.resourceKey.name)) to Remote Collector Group ($collectorGroupName), already assigned: SKIPPED"
                                    }
                                    Remove-Item .\updateAdapter.json -Force -Confirm:$false
                                }
                            } else {
                                Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-vROPSAdapterVcenter

Function Update-vROPSAdapterCollecterGroup {
    <#
        .SYNOPSIS
        Updates the assigned Collector Group for the specified Adapter type

        .DESCRIPTION
        The Update-vROPSAdapterCollecterGroup cmdlet updates the assigned Remote Collector Group for all Adapters in
        vRealize Operations Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates the Collector Group exits in vRealize Operations Manager
        - Gathers the unique ID of the Remote Collector Group
        - Gathers the given Adapter details from vRelize Operations Manager
        - Updates the assigned Remote Collector Group for the Adapter in vRelize Operations Manager
        
        .EXAMPLE
        Update-vROPSAdapterCollecterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors" -adaptertype "LogInsightAdapter"
        This example updates vRLI Adapter to use the Remote Collector Group named 'sfo-remote-collectors'
        
        .EXAMPLE
        Update-vROPSAdapterCollecterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors" -adaptertype "VMWARE"
        This example updates all vCenter Adapters to use the Remote Collector Group named 'sfo-remote-collectors'
        
        .EXAMPLE
        Update-vROPSAdapterCollecterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -collectorGroupName "sfo-remote-collectors" -adaptertype "IdentityManagerAdapter" -adaptername "sfo-wsa01"
        This example updates Identity Manager Adapter with name "sfo-wsa01" to use the Remote Collector Group named 'sfo-remote-collectors'

        .EXAMPLE
        Update-vROPSAdapterCollecterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -adaptertype "IdentityManagerAdapter" -adaptername "vRSLCM_VCF_Workspace ONE Access Adapter"
        This example updates Identity Manager Adapter with name "vRSLCM_VCF_Workspace ONE Access Adapter" to use the default Remote Collector Group named "Default collector group"
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group",
        [Parameter (Mandatory = $true)] [ValidateSet("VMWARE","LogInsightAdapter","IdentityManagerAdapter","NSXTAdapter","PingAdapter","CASAdapter")] [String]$adapterType,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$adapterName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if ($collectorGroupId = (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id) {
                                $adapters = Get-vROPSAdapter | Where-Object {$_.resourceKey.adapterKindKey -eq $adapterType}
                                if ($adapterName) {
                                    if ($adapters | Where-Object {$_.resourceKey.name -eq $adapterName}) {
                                        $adapters = $adapters | Where-Object {$_.resourceKey.name -eq $adapterName}
                                    } else {
                                        Write-Error "Adapter with name $adapterName not found"
                                        Break
                                    }
                                }
                                Foreach ($adapter in $adapters) {
                                    $json =  $adapter
                                    if (!($($json.collectorGroupId) -eq $collectorGroupId)) {
                                                $json.collectorGroupId=$collectorGroupId
                                                #Remove collectorId as the request body can accept a collectorId or a collectorGroupId, but not both.
                                                $json.PSObject.Properties.Remove('collectorId')
                                                $json  | ConvertTo-Json -Depth 4 | Out-File .\updateAdapter.json                                                
                                                Set-vROPSAdapter -json .\updateAdapter.json | Out-Null
                                                Write-Output "Assiging Collector Group ($collectorGroupName) to instance - ($($adapter.resourceKey.name)) : SUCCESSFUL"
                                                Remove-Item .\updateAdapter.json -Force -Confirm:$false
                                            } else {
                                                Write-Warning "Assiging Collector Group ($collectorGroupName) to instance - ($($adapter.resourceKey.name)) : already assigned: SKIPPED"
                                            }
                                }
                            } else {
                                Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-vROPSAdapterCollecterGroup

Function Add-vROPSCurrency {
    <#
        .SYNOPSIS
        Configures the currency in vRealize Operations Manager

        .DESCRIPTION
        The Add-vROPSCurrency cmdlet configures the currency in vRealize Operations Manager. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates if a currency value has been configured
        - Configures the currency value based on the value provided

        .EXAMPLE
        Add-vROPSCurrency -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -currency USD
        This example configures the currency to USD in vRealize Opertations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$currency
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (-not (($currentCurrency = Get-vROPSCurrency | Select-Object code)).code) {
                                Set-vROPSCurrency -currency $currency | Out-Null
                                if (((Get-vROPSCurrency | Select-Object code)).code -eq $currency) {
                                    Write-Output "Configuring currency in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) to ($currency): SUCCESSFUL"
                                } else {
                                    Write-Error "Configuring currency in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) to ($currency): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Configuring currency in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) to ($currency), ($($currentCurrency.code)) already set: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSCurrency

Function Enable-vROPSManagementPack {
    <#
        .SYNOPSIS
        Install a Management Pack in vRealize Operations Manager

        .DESCRIPTION
        The Enable-vROPSManagementPack cmdlet uploads and installs a management pack in vRealize Operations Manager.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates the path to the Management Pack (.pak) file
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates the Management Pack does not exist in vRealize Operations Manager
        - Uploads the Management Pack file to vRealize Operations Manager
        - Installs the Management Pack to vRealize Operations Manager

        .EXAMPLE
        Enable-vROPSManagementPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -packType "SDDC Health" -pakfile .\management.pak
        This example installs the SDDC Health Management Pack in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateSet("SDDC Health","SrmAdapter","VrAdapter")] [ValidateNotNullOrEmpty()] [String]$packType,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pakFile
    )

    if (!$pakFile) {
        $pakFile = Get-ExternalFileName -title "Select the Management Pack file (.pak)" -fileType "pak" -location "default"
    } else {
        if (!(Test-Path -Path $pakFile)) {
            Write-Error "Management Pack file (pak) '$pakFile' File Not Found"
            Break
        }
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (!(Get-vROPSSolution | Where-Object {$_.id -eq $packType})) {
                                $uploadPak = Import-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pak $pakFile
                                if ($uploadPak) {
                                    $pakId = ($uploadPak | ConvertFrom-JSon).pak_id
                                    $installPak = Install-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId $pakId
                                    Do {
                                        $status = Get-vROPSManagementPackStatus -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId $pakId
                                    } Until ( $status.cluster_pak_install_status -ne "CANDIDATE" )
                                    if ($status.cluster_pak_install_status -eq "COMPLETED") {
                                        Write-Output "Installing '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Installing '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Uploading '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Installing '$pakFile' Management Pack to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already exists: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Enable-vROPSManagementPack

Function Register-vROPSManagementPack {
    <#
        .SYNOPSIS
        Enable / Disable a Management Pack

        .DESCRIPTION
        The Register-vROPSManagementPack cmdlet activates or deactivates a management pack in vRealize Operations
        Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates if the Management Pack is activated or deactivated in vRealize Operations Manager
        - Activates or deactivates the Management Pack

        .EXAMPLE
        Register-vROPSManagementPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -state enable -packType Ping
        This example activates the Ping management pack in vRealize Operations Manager

        .EXAMPLE
        Register-vROPSManagementPack -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -state disable -packType Ping
        This example deactivates the Ping management pack in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateSet("enable","disable")] [ValidateNotNullOrEmpty()] [String]$state,
        [Parameter (Mandatory = $true)] [ValidateSet("Ping","PCI","ISO","FISMA","HIPAA","CIS","DISA")] [ValidateNotNullOrEmpty()] [String]$packType
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            # Connect to vRealize Operations Manager and extract the Management Pack Details
                            $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $($vcfVropsDetails.adminUser), $($vcfVropsDetails.adminPass)))) # Create Basic Authentication Encoded Credentials
                            $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
                            $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo")
                            $vropsBasicHeaders.Add("Content-Type", "application/json")
                            $uri = ((Get-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass | Where-Object {$_.links -match $packType}).links | Where-Object {$_.rel -eq "pak_information"}).href
                            $adapterDetails = Invoke-RestMethod -Method GET -Uri $uri -Headers $vropsBasicHeaders
                            $uri = ((Get-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass | Where-Object {$_.links -match $packType}).links | Where-Object {$_.rel -eq "pak_cluster_status"}).href
                            if ($state -eq "enable") {
                                if (!(Get-vROPSSolution | Where-Object {$_.id -match $packType})) {
                                    Set-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId ((($adapterDetails.pak_id) -Split ("-"))[0]) -version $adapterDetails.version -status enable | Out-Null
                                    Do {
                                        $status = Invoke-RestMethod -Method GET -Uri $uri -Headers $vropsBasicHeaders
                                    } Until ( $status.cluster_pak_install_status -ne "CANDIDATE" )
                                    if ($status.cluster_pak_install_status -eq "COMPLETED") {
                                        Write-Output "Activating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Activating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Activating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already exists: SKIPPED"
                                }
                            } elseif ($state -eq "disable") {
                                if (Get-vROPSSolution | Where-Object {$_.id -match $packType}) {
                                    Set-vROPSManagementPack -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass -pakId ((($adapterDetails.pak_id) -Split ("-"))[0]) -version $adapterDetails.version -status disable | Out-Null
                                    Do {
                                        $status = Get-vROPSManagementPackActivity -server $vcfVropsDetails.loadBalancerFqdn -username $vcfVropsDetails.adminUser -password $vcfVropsDetails.adminPass
                                    } Until ( $($status.current_pak_activity.pak_id) -ne $adapterDetails.pak_id )
                                    if (!(Get-vROPSSolution | Where-Object {$_.id -match $packType})) {
                                        Write-Output "Deactivating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Deactivating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Deactivating ($packType) Management Pack on vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already exists: SKIPPED"
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Register-vROPSManagementPack

Function Add-vROPSAdapterNsxt {
    <#
        .SYNOPSIS
        Adds an NSX Adapter to vRealize Operations Manager

        .DESCRIPTION
        The Add-vROPSAdapterNsxt cmdlet adds an NSX Adapter for a Workload Domains NSX Management Cluster to vRealize
        Operations Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Workload Domain is valid and then obtains the NSX Management Cluster details
        - Validates that the Remote Collector Group exits in vRealize Operations Manager
        - Validates that the NSX Adapter and Credentials do not already exist in vRealize Operations Manager
        - Validates that the credentials do not already exist in vRealize Operations Manager
        - Creates a new NSX Adapter for the Workload Domain using credentials from SDDC Manager inventory in vRealize Operations Manager
        - Starts the collection of the NSX Adapter in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAdapterNsxt -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -collectorGroupName "sfo-remote-collectors"
        This example creates an NSX Adapter for the Management Workload Domain named in vRealize Opertations Manager and assigns to the remote collector group defined

        .EXAMPLE
        Add-vROPSAdapterNsxt -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -collectorGroupName "sfo-remote-collectors"
        This example creates an NSX Adapter for the VI Workload Domain named in vRealize Opertations Manager and assigns to the remote collector group defined

        .EXAMPLE
        Add-vROPSAdapterNsxt -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01
        This example creates an NSX Adapter for the Management Workload Domain named in vRealize Opertations Manager and assigns to the "Default collector group"
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                $vcfNsxDetails = Get-NsxtServerDetail -fqdn $server -user $user -pass $pass -domain $domain
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-VCFWorkloadDomain | Where-Object {$_.name -eq $domain}) {
                                if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) {
                                    if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn})) {
                                        if (!(Get-vROPSCredential | Where-Object {$_.name -eq $vcfNsxDetails.fqdn})) {
                                            $credentialJson = '{
                                                "name": "'
+ $vcfNsxDetails.fqdn +'",
                                                "adapterKindKey": "NSXTAdapter",
                                                "credentialKindKey": "NSXTCREDENTIAL",
                                                "fields": [
                                                    { "name": "USERNAME", "value": "'
+ $vcfNsxDetails.adminUser +'" },
                                                    { "name": "PASSWORD", "value": "'
+ $vcfNsxDetails.adminPass +'" }
                                            ]}'

                                            $credentialJson | Out-File .\addCredential.json
                                            Add-vROPSCredential -json .\addCredential.json | Out-Null
                                            Remove-Item .\addCredential.json -Force -Confirm:$false
                                        }
                                        $adapterJson = '{
                                            "name": "'
+ $vcfNsxDetails.fqdn +'",
                                            "description": "NSX-T Adapter - '
+ $vcfNsxDetails.fqdn +'",
                                            "adapterKindKey": "NSXTAdapter",
                                            "monitoringInterval": 5,
                                            "collectorGroupId": "'
+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'",
                                            "resourceIdentifiers": [
                                                { "name": "NSXTHOST", "value": "'
+ $vcfNsxDetails.fqdn +'" }
                                            ],
                                            "credential": {
                                                "id": "'
+ (Get-vROPSCredential | Where-Object {$_.name -eq $vcfNsxDetails.fqdn}).id +'"
                                                }
                                        }'

                                        $adapterJson | Out-File .\addAdapter.json
                                        Add-vROPSAdapter -json .\addAdapter.json | Out-Null
                                        $testAdapter = Test-vROPSAdapterConnection -json .\addAdapter.json
                                        $testAdapter | ConvertTo-Json -Depth 10 | Out-File .\createdAdapter.json
                                        Test-vROPSAdapterConnection -json .\createdAdapter.json -patch
                                        $adapterDetail = Get-Content -Path .\createdAdapter.json -Raw | ConvertFrom-Json
                                        $adapterDetail.PSObject.Properties.Remove('links')
                                        $adapterDetail | Add-Member -NotePropertyName description -NotePropertyValue "NSX-T Adapter - $($vcfNsxDetails.fqdn)"
                                        $adapterDetail.'adapter-certificates' = $adapterDetail.'adapter-certificates' | Select-Object * -ExcludeProperty certificateDetails
                                        $adapterDetail.id = (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}).id
                                        $adapterDetail | ConvertTo-Json -Depth 100 | Out-File .\patchAdapter.json  -Force
                                        Set-vROPSAdapter -json .\patchAdapter.json -patch | Out-Null
                                        if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}) {
                                            Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vcfNsxDetails.fqdn}).id | Out-Null
                                            Write-Output "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)): POST_VALIDATION_FAILED"
                                        }
                                        Remove-Item .\addAdapter.json -Force -Confirm:$false
                                        Remove-Item .\createdAdapter.json -Force -Confirm:$false
                                        Remove-Item .\patchAdapter.json -Force -Confirm:$false 
                                    } else {
                                        Write-Warning "Adding NSX Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vcfNsxDetails.fqdn)), already exists: SKIPPED"
                                    }      
                                } else {
                                    Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                            }   
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSAdapterNsxt

Function Add-vROPSAdapterPing {
    <#
        .SYNOPSIS
        Adds a Ping Adapter to vRealize Operations Manager

        .DESCRIPTION
        The Add-vROPSAdapterPing cmdlet adds a Ping adapter to vRealize Operations Manager. The cmdlet connects to SDDC
        Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Remote Collector Group exits in vRealize Operations Manager
        - Validates that the Ping Adapter does not already exist in vRealize Operations Manager
        - Creates a new Ping adapter in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAdapterPing -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -addressList "192.168.11.30,192.168.11.31,192.168.11.32,192.168.11.33" -adapterName xint-vrops01 -collectorGroupName "sfo-remote-collectors"
        This example creates a new Ping adapter called 'xint-vrops01', assigns the IP Addresses provided and assigned the remote collector group called 'sfo-remote-collectors'

        .EXAMPLE
        Add-vROPSAdapterPing -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -addressList "192.168.11.50,192.168.11.51,192.168.11.52,192.168.11.53" -adapterName xint-vra01
        This example creates a new Ping adapter called 'xint-vra01', assigns the IP Addresses provided and assigns to the 'Default collector group'
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$addressList,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) {
                                if (Get-vROPSSolution | Where-Object {$_.id -match "Ping"}) {
                                    if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName})) {
                                        $json = '{
                                            "name": "'
+ $adapterName +'",
                                            "description": "Ping Adapter - '
+ $adapterName +'",
                                            "adapterKindKey": "PingAdapter",
                                            "monitoringInterval": 5,
                                            "collectorGroupId": "'
+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'",
                                                "resourceIdentifiers": [
                                                    {
                                                        "name": "unique_name",
                                                        "value": "'
+ $adapterName +'"
                                                    },
                                                    {
                                                        "name": "address_list",
                                                        "value": "'
+ $addressList +'"
                                                    },
                                                    {
                                                        "name": "batch_circle_interval",
                                                        "value": "0"
                                                    },
                                                    {
                                                        "name": "count",
                                                        "value": "20"
                                                    },
                                                    {
                                                        "name": "dns_resolving_interval",
                                                        "value": "30"
                                                    },
                                                    {
                                                        "name": "dont_fragment",
                                                        "value": "false"
                                                    },
                                                    {
                                                        "name": "generate_fqdn_children",
                                                        "value": "false"
                                                    },
                                                    {
                                                        "name": "packet_size",
                                                        "value": "56"
                                                    },
                                                    {
                                                        "name": "period",
                                                        "value": "2000"
                                                    }
                                                ]
                                        }'

                                        $json | Out-File .\addAdapter.json
                                        Add-vROPSAdapter -json .\addAdapter.json | Out-Null
                                        if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}) {
                                            Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}).id | Out-Null
                                            Write-Output "Adding Ping Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding Ping Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName)): POST_VALDATION_FAILED"
                                        }
                                        Remove-Item .\addAdapter.json -Force -Confirm:$false
                                    } else {
                                        Write-Warning "Adding Ping Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName), already exists: SKIPPED"
                                    }
                                } else {
                                    Write-Error "The Ping Management Pack in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), not activated: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED"
                            }   
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSAdapterPing

Function Update-vROPSAdapterSddcHealth {
    <#
        .SYNOPSIS
        Updates the SDDC Health Adapters names in vRealize Operations Manager

        .DESCRIPTION
        The Update-vROPSAdapterSddcHealth cmdlet updates the names of the SDDC Health Adapters in vRealize Operations
        Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that SDDC Health Adapters exits in vRealize Operations Manager
        - Gathers the unique ID of the Remote Collectors
        - Gathers the details of the SDDC Health Adapters
        - Updates the name of the SDDC Health Adapters

        .EXAMPLE
        Update-vROPSAdapterSddcHealth -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example updates all the name of all SDDC Health Adapters
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if ($adapters = Get-vROPSAdapter | Where-Object {$_.resourceKey.adapterKindKey -eq "SDDCHealthAdapter"}) {
                                Foreach ($adapter in $adapters) {
                                    $collectorDetails = Get-vROPSCollector | Where-Object {$_.id -eq $adapter.collectorId}
                                    $adapterName = (($adapter.resourceKey.name).Split("-"))[0] + "-" + ($collectorDetails.name -Split ("vRealize Operations Manager Collector-"))
                                    if ($vropsVersion -lt "8.6.2") {
                                        $json = '{
                                            "resourceKey": {
                                                                "name": "'
+ $adapterName +'",
                                                                "adapterKindKey": "SDDCHealthAdapter",
                                                                "resourceKindKey": "SDDCHealth Instance"
                                                            },
                                            "description": "SDDC Health Adapter for'
+ ($collectorDetails.name -Split ("vRealize Operations Manager Collector-")) +'",
                                            "collectorId": '
+ $($collectorDetails.id) +',
                                            "monitoringInterval": 5,
                                            "id": "'
+ $($adapter.id) +'"
                                        }'

                                    } else {
                                        $json = '{
                                            "name": "'
+ $adapterName +'",
                                            "adapterKindKey": "SDDCHealthAdapter",
                                            "description": "SDDC Health Adapter for'
+ ($collectorDetails.name -Split ("vRealize Operations Manager Collector-")) +'",
                                            "collectorId": '
+ $($collectorDetails.id) +',
                                            "monitoringInterval": 5,
                                            "id": "'
+ $($adapter.id) +'"
                                        }'

                                    }
                                    $json | Out-File .\updateAdapter.json
                                    if (!($adapter.resourceKey.name -eq $adapterName)) {
                                        Set-vROPSAdapter -json .\updateAdapter.json | Out-Null
                                        Write-Output "Renaming Adapter ($($adapter.resourceKey.name)) to ($adapterName): SUCCESSFUL"
                                        Remove-Item .\updateAdapter.json -Force -Confirm:$false
                                    } else {
                                        Write-Warning "Renaming Adapter ($($adapter.resourceKey.name)) to ($adapterName), already performed: SKIPPED"
                                    }
                                }
                            } else {
                                Write-Error "Unable to locate Adapters of type (SDDCHealthAdapter) in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-vROPSAdapterSddcHealth

Function Add-vROPSAdapterSddcHealth {
    <#
        .SYNOPSIS
        Adds an SDDC Health Adapters for Remote Collectors

        .DESCRIPTION
        The Add-vROPSAdapterSddcHealth cmdlet adds SDDC Health Adapters for the Remove Collectors in vRealize
        Operations Manager. The cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that SDDC Health Adapters do not exist in vRealize Operations Manager
        - Gathers the Remote Collector details from vRealize Operations Manager
        - Creates a new SDDC Health Adapter for each Remote Collector in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAdapterSddcHealth -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
        This example creates an SDDC Health Adapter for each Remote Collector Node found in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            $vropsVersion = ((Get-vROPSVersion).releaseName -split '\s+' -match '\S')[-1] 
                            if ($remoteCollectors = (Get-vROPSCollector | Where-Object {$_.type -eq "REMOTE"})) {
                                Foreach ($collector in $remoteCollectors) {
                                    $adapterName = "SDDC Health Adapter Instance -" + ($collector.name -Split ("vRealize Operations Manager Collector-"))
                                    if ($vropsVersion -lt "8.5.0") {
                                        $json = '{
                                            "resourceKey": {
                                                                "name": "'
+ $adapterName +'",
                                                                "adapterKindKey": "SDDCHealthAdapter",
                                                                "resourceKindKey": "SDDCHealth Instance"
                                                            },
                                            "description": "SDDC Health Adapter for'
+ ($collector.name -Split ("vRealize Operations Manager Collector-")) +'",
                                            "collectorId": '
+ $($collector.id) +',
                                            "monitoringInterval": 5
                                        }'

                                    } else {
                                        $json = '{
                                            "name": "'
+ $adapterName +'",
                                            "adapterKindKey": "SDDCHealthAdapter",
                                            "description": "SDDC Health Adapter for'
+ ($collector.name -Split ("vRealize Operations Manager Collector-")) +'",
                                            "collectorId": '
+ $($collector.id) +',
                                            "monitoringInterval": 5
                                        }'

                                    }
                                    $json | Out-File .\addAdapter.json
                                    if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName})) {                   
                                        Add-vROPSAdapter -json .\addAdapter.json | Out-Null
                                        if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}) {
                                            Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}).id | Out-Null
                                            Write-Output "Adding Adapter ($adapterName) to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding Adapter ($adapterName) to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Adding Adapter ($adapterName) to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already performed: SKIPPED"
                                    }
                                    Remove-Item .\addAdapter.json -Force -Confirm:$false
                                }
                            } else {
                                Write-Error "Unable to locate Remote Collectors in vealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED"
                            } 
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSAdapterSddcHealth

Function Add-vROPSAdapterIdentityManager {
    <#
        .SYNOPSIS
        Adds an Identity Manager adapter to vRealize Operations Manager

        .DESCRIPTION
        The Add-vROPSAdapterIdentityManager cmdlet adds a Identity Manager adapter to vRealize Operations Manager. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Collector Group exits in vRealize Operations Manager
        - Validates that the Identity Manager adapter does not already exist in vRealize Operations Manager
        - Creates a new Identity Manager adapter in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAdapterIdentityManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1! -collectorGroupName "sfo-remote-collectors"
        This example creates a new Identity Manager adapter and assigns it to the remote collector group

        .EXAMPLE
        Add-vROPSAdapterIdentityManager -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -wsaFqdn sfo-wsa01.sfo.rainpole.io -wsaUser admin -wsaPass VMw@re1!
        This example creates a new Identity Manager adapter and assigns it to the 'Default collector group'
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) {
                                if (Get-vROPSSolution | Where-Object {$_.adapterKindKeys -eq "IdentityManagerAdapter"}) {
                                    $adapterName = $wsaFqdn
                                    if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq "IdentityManagerAdapter"})) {
                                        if (!(Get-vROPSCredential | Where-Object {$_.name -eq $wsaFqdn})) {
                                            $credentialJson = '{
                                                "name": "'
+ $adapterName +'",
                                                "adapterKindKey": "IdentityManagerAdapter",
                                                "credentialKindKey": "IDENTITYMANAGERCREDENTIAL",
                                                "fields": [
                                                    { "name": "USERNAME", "value": "'
+ $wsaUser +'" },
                                                    { "name": "PASSWORD", "value": "'
+ $wsaPass +'" }
                                            ]}'

                                            $credentialJson | Out-File .\addCredential.json
                                            Add-vROPSCredential -json .\addCredential.json | Out-Null
                                            Remove-Item .\addCredential.json -Force -Confirm:$false
                                        }
                                        $adapterJson = '{
                                            "name": "'
+ $adapterName +'",
                                            "description": "Workspace ONE Access Adapter - '
+ $adapterName +'",
                                            "adapterKindKey": "IdentityManagerAdapter",
                                            "monitoringInterval": 5,
                                            "collectorGroupId": "'
+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'",
                                                "resourceIdentifiers": [
                                                    {
                                                        "name": "vIDMHost",
                                                        "value": "'
+ $adapterName +'"
                                                    }
                                                ],
                                            "credential": {
                                                "id": "'
+ (Get-vROPSCredential | Where-Object {$_.name -eq $adapterName}).id +'"
                                                }
                                        }'

                                        $adapterJson | Out-File .\addAdapter.json
                                        Add-vROPSAdapter -json .\addAdapter.json | Out-Null
                                        $testAdapter = Test-vROPSAdapterConnection -json .\addAdapter.json
                                        $adapterDetail = $testAdapter
                                        $adapterDetail | Add-Member -NotePropertyName description -NotePropertyValue "Workspace ONE Access Adapter - $adapterName"
                                        $adapterDetail.PSObject.Properties.Remove('links')
                                        $adapterDetail.'adapter-certificates' = $adapterDetail.'adapter-certificates' | Select-Object * -ExcludeProperty certificateDetails
                                        $certificates = New-Object System.Collections.ArrayList
                                        $certificates = $adapterDetail.'adapter-certificates'
                                        $adapterDetail.PSObject.Properties.Remove('adapter-certificates')
                                        $adapterDetail | Add-Member -NotePropertyName adapter-certificates -NotePropertyValue ([Array]$certificates)
                                        $adapterDetail.id = (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq "IdentityManagerAdapter"}).id
                                        $adapterDetail | ConvertTo-Json -Depth 100 | Out-File .\patchAdapter.json  -Force
                                        Set-vROPSAdapter -json .\patchAdapter.json -patch | Out-Null
                                        if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq "IdentityManagerAdapter"}) {
                                            Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName}).id | Out-Null
                                            Write-Output "Adding Identity Manager Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding Identity Manager Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName)): POST_VALDATION_FAILED"
                                        }
                                        Remove-Item .\addAdapter.json -Force -Confirm:$false
                                        Remove-Item .\patchAdapter.json -Force -Confirm:$false
                                    } else {
                                        Write-Warning "Adding Identity Manager Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName), already exists: SKIPPED"
                                    }
                                } else {
                                    Write-Error "The Identity Manager Management Pack in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), not activated: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED"
                            }   
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSAdapterIdentityManager

Function Add-vROPSAdapterSrm {
    <#
        .SYNOPSIS
        Adds a Site Recovery Manager Adapter to vRealize Operations Manager

        .DESCRIPTION
        The Add-vROPSAdapterSrm cmdlet adds an Site Recovery Manager Adapter to vRealize Operations Manager. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Workload Domain is valid and then obtains the NSX Management Cluster details
        - Validates that the Remote Collector Group exits in vRealize Operations Manager
        - Validates that the Adapter and Credentials do not already exist in vRealize Operations Manager
        - Creates a new Site Recovery Manager Adapter in vRealize Operations Manager
        - Starts the collection of the Site Recovery Manager Adapter in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAdapterSrm -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -srmFqdn sfo-m01-srm01.sfo.rainpole.io -srmUser vrops-srm -srmPass VMw@re1!VMw@re1! -collectorGroupName "sfo-remote-collectors"
        This example creates a Site Recovery Manager Adapter in vRealize Opertations Manager and assigns to the remote collector group defined
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) {
                                if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $srmFqdn})) {
                                    if (!(Get-vROPSCredential | Where-Object {$_.name -eq $srmFqdn})) {
                                        $credentialJson = '{
                                            "name": "'
+ $srmFqdn +'",
                                            "adapterKindKey": "SrmAdapter",
                                            "credentialKindKey": "SRM Credentials",
                                            "fields": [
                                                { "name": "username", "value": "'
+ $srmUser +'" },
                                                { "name": "password", "value": "'
+ $srmPass +'" }
                                        ]}'

                                        $credentialJson | Out-File .\addCredential.json
                                        Add-vROPSCredential -json .\addCredential.json | Out-Null
                                        Remove-Item .\addCredential.json -Force -Confirm:$false
                                    }
                                    $adapterJson = '{
                                        "name": "'
+ $srmFqdn +'",
                                        "description": "SRM Adapter - '
+ $srmFqdn +'",
                                        "adapterKindKey": "SrmAdapter",
                                        "monitoringInterval": 5,
                                        "collectorGroupId": "'
+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'",
                                        "resourceIdentifiers": [
                                            { "name": "host", "value": "'
+ $srmFqdn +'" },
                                            { "name": "port", "value": "443" }
                                        ],
                                        "credential": {
                                            "id": "'
+ (Get-vROPSCredential | Where-Object {$_.name -eq $srmFqdn}).id +'"
                                            }
                                    }'

                                    $adapterJson | Out-File .\addAdapter.json
                                    Add-vROPSAdapter -json .\addAdapter.json | Out-Null
                                    $testAdapter = Test-vROPSAdapterConnection -json .\addAdapter.json
                                    $adapterDetail = $testAdapter
                                    $adapterDetail | Add-Member -NotePropertyName description -NotePropertyValue "SRM Adapter - $($srmFqdn)"
                                    $adapterDetail.PSObject.Properties.Remove('links')
                                    $adapterDetail.'adapter-certificates' = $adapterDetail.'adapter-certificates' | Select-Object * -ExcludeProperty certificateDetails
                                    $certificates = New-Object System.Collections.ArrayList
                                    $certificates = $adapterDetail.'adapter-certificates'
                                    $adapterDetail.PSObject.Properties.Remove('adapter-certificates')
                                    $adapterDetail | Add-Member -NotePropertyName adapter-certificates -NotePropertyValue ([Array]$certificates)
                                    $adapterDetail.id = (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $srmFqdn}).id
                                    $adapterDetail | ConvertTo-Json -Depth 100 | Out-File .\patchAdapter.json  -Force
                                    Set-vROPSAdapter -json .\patchAdapter.json -patch | Out-Null
                                    if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $srmFqdn}) {
                                        Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $srmFqdn}).id | Out-Null
                                        Write-Output "Adding Site Recovery Manager Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($srmFqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding Site Recovery Manager Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($srmFqdn)): POST_VALIDATION_FAILED"
                                    }
                                    Remove-Item .\addAdapter.json -Force -Confirm:$false
                                    Remove-Item .\patchAdapter.json -Force -Confirm:$false 
                                } else {
                                    Write-Warning "Adding Site Recovery Manager Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($srmFqdn)), already exists: SKIPPED"
                                }      
                            } else {
                                Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED"
                            }  
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSAdapterSrm

Function Add-vROPSAdapterVr {
    <#
        .SYNOPSIS
        Adds a vSphere Replication Adapter to vRealize Operations Manager

        .DESCRIPTION
        The Add-vROPSAdapterVr cmdlet adds an vSphere Replication Adapter to vRealize Operations Manager. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Workload Domain is valid and then obtains the NSX Management Cluster details
        - Validates that the Remote Collector Group exits in vRealize Operations Manager
        - Validates that the Adapter and Credentials do not already exist in vRealize Operations Manager
        - Creates a new vSphere Replication Adapter in vRealize Operations Manager
        - Starts the collection of the vSphere Replication Adapter in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAdapterVr -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vrFqdn sfo-m01-vrms01.sfo.rainpole.io -vrUser vrops-vr@vsphere.local -vrPass VMw@re1!VMw@re1! -collectorGroupName "sfo-remote-collectors"
        This example creates a vSphere Replication Adapter in vRealize Opertations Manager and assigns to the remote collector group defined
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorGroupName="Default collector group"
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}) {
                                if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vrFqdn})) {
                                    if (!(Get-vROPSCredential | Where-Object {$_.name -eq $vrFqdn})) {
                                        $credentialJson = '{
                                            "name": "'
+ $vrFqdn +'",
                                            "adapterKindKey": "VrAdapter",
                                            "credentialKindKey": "VR Credentials",
                                            "fields": [
                                                { "name": "username", "value": "'
+ $vrUser +'" },
                                                { "name": "password", "value": "'
+ $vrPass +'" }
                                        ]}'

                                        $credentialJson | Out-File .\addCredential.json
                                        Add-vROPSCredential -json .\addCredential.json | Out-Null
                                        Remove-Item .\addCredential.json -Force -Confirm:$false
                                    }
                                    $adapterJson = '{
                                        "name": "'
+ $vrFqdn +'",
                                        "description": "vSphere Replication Adapter - '
+ $vrFqdn +'",
                                        "adapterKindKey": "VrAdapter",
                                        "monitoringInterval": 5,
                                        "collectorGroupId": "'
+ (Get-vROPSCollectorGroup | Where-Object {$_.name -eq $collectorGroupName}).id +'",
                                        "resourceIdentifiers": [
                                            { "name": "vchost", "value": "'
+ (Get-VCFWorkloadDomain | Where-Object {$_.name -eq "sfo-m01"}).vcenters.fqdn +'" }
                                        ],
                                        "credential": {
                                            "id": "'
+ (Get-vROPSCredential | Where-Object {$_.name -eq $vrFqdn}).id +'"
                                            }
                                    }'

                                    $adapterJson | Out-File .\addAdapter.json
                                    Add-vROPSAdapter -json .\addAdapter.json | Out-Null
                                    $testAdapter = Test-vROPSAdapterConnection -json .\addAdapter.json
                                    $adapterDetail = $testAdapter
                                    $adapterDetail | Add-Member -NotePropertyName description -NotePropertyValue "vSphere Replication Adapter - $($vrFqdn)"
                                    $adapterDetail.PSObject.Properties.Remove('links')
                                    $adapterDetail.'adapter-certificates' = $adapterDetail.'adapter-certificates' | Select-Object * -ExcludeProperty certificateDetails
                                    $certificates = New-Object System.Collections.ArrayList
                                    $certificates = $adapterDetail.'adapter-certificates'
                                    $adapterDetail.PSObject.Properties.Remove('adapter-certificates')
                                    $adapterDetail | Add-Member -NotePropertyName adapter-certificates -NotePropertyValue ([Array]$certificates)
                                    $adapterDetail.id = (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vrFqdn}).id
                                    $adapterDetail | ConvertTo-Json -Depth 100 | Out-File .\patchAdapter.json  -Force
                                    Set-vROPSAdapter -json .\patchAdapter.json -patch | Out-Null
                                    if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vrFqdn}) {
                                        Start-vROPSAdapter -adapterId (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $vrFqdn}).id | Out-Null
                                        Write-Output "Adding vSphere Replication Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vrFqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding vSphere Replication Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vrFqdn)): POST_VALIDATION_FAILED"
                                    }
                                    Remove-Item .\addAdapter.json -Force -Confirm:$false
                                    Remove-Item .\patchAdapter.json -Force -Confirm:$false 
                                } else {
                                    Write-Warning "Adding vSphere Replication Adapter in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($($vrFqdn)), already exists: SKIPPED"
                                }      
                            } else {
                                Write-Error "Remote Collector Group in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($collectorGroupName), does not exist: PRE_VALIDATION_FAILED"
                            }  
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSAdapterVr

Function Undo-vROPSAdapter {
    <#
        .SYNOPSIS
        Removes an adapter from vRealize Operations Manager

        .DESCRIPTION
        The Undo-vROPSAdapter cmdlet adds a Identity Manager adapter to vRealize Operations Manager. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Adapter is present
        - Deletes the adapter from vRealize Operations Manager

        .EXAMPLE
        Undo-vROPSAdapter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -adapterName sfo-wsa01.sfo.rainpole.io -adapterType IdentityManagerAdapter
        This example deletes the adapter type IdentityManagerAdapter, with a name of sfo-wsa01.sfo.rainpole.io
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterName,
        [Parameter (Mandatory = $true)] [ValidateSet("PingAdapter","IdentityManagerAdapter","NSXTAdapter","SDDCHealthAdapter","SrmAdapter","VrAdapter")] [String]$adapterType
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq $adapterType}) {
                                Remove-vROPSAdapter -id (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq $adapterType}).id | Out-Null
                                Do {
                                    Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq $adapterType} | Out-Null
                                    Start-Sleep 2
                                } While (Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq $adapterType})
                                if (!(Get-vROPSAdapter | Where-Object {$_.resourceKey.name -eq $adapterName -and $_.resourceKey.adapterKindKey -eq $adapterType})) {
                                    Write-Output "Removing adapter of type ($adapterType) from vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing adapter of type ($adapterType) from vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing adapter of type ($adapterType) from vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($adapterName), does not exist: SKIPPED"
                            }   
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vROPSAdapter

Function Undo-vROPSCredential {
    <#
        .SYNOPSIS
        Removes a credential from vRealize Operations Manager

        .DESCRIPTION
        The Undo-vROPSCredential cmdlet removes a credential from vRealize Operations Manager. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Credential is present
        - Deletes the credential from vRealize Operations Manager

        .EXAMPLE
        Undo-vROPSCredential -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -credentialName sfo-wsa01.sfo.rainpole.io -credentialType IdentityManagerAdapter
        This example deletes the credential type IdentityManagerAdapter, with a name of sfo-wsa01.sfo.rainpole.io
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$credentialName,
        [Parameter (Mandatory = $true)] [ValidateSet("IdentityManagerAdapter","NSXTAdapter","CASAdapter","SrmAdapter","VrAdapter")] [String]$credentialType
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-vROPSCredential | Where-Object {$_.name -eq $credentialName -and $_.adapterKindKey -eq $credentialType}) {
                                if (!(Get-vROPSCredential -credentialId (Get-vROPSCredential -adapter | Where-Object {$_.name -eq $credentialName -and $_.adapterKindKey -eq $credentialType}).id -adapter)) {
                                    Remove-vROPSCredential -credentialId (Get-vROPSCredential | Where-Object {$_.name -eq $credentialName -and $_.adapterKindKey -eq $credentialType}).Id | Out-Null
                                    if (!(Get-vROPSCredential | Where-Object {$_.name -eq $credentialName -and $_.adapterKindKey -eq $credentialType})) {
                                        Write-Output "Removing credential of type ($credentialType) from vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($credentialName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing credential of type ($credentialType) from vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($credentialName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Credential of type ($credentialType) named ($credentialName) still assigned to an adapter: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing credential of type ($credentialType) from vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($credentialName), does not exist: SKIPPED"
                            }   
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vROPSCredential

Function Add-vROPSAlertPluginEmail {
    <#
        .SYNOPSIS
        Adds an Email based Alert Plugin

        .DESCRIPTION
        The Add-vROPSAlertPluginEmail cmdlet adds an Email based Alert Plugin in vRealize Operations Manager. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the Email Alert Plugin does not exist in vRealize Operations Manager
        - Creates a new Email Alert Plugin and enables it in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAlertPluginEmail -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -pluginName "Email-Alert-Plugin" -smtpServer smtp.rainpole.io -smtpPort 25 -senderAddress "vrops-alerts@rainpole.io" -secureConnection true -protocol TLS -authentication false
        This example creates and enables an Email Alert Plugin in vRealize Operations Manager without authentication

        .EXAMPLE
        Add-vROPSAlertPluginEmail -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -pluginName "Email-Alert-Plugin" -smtpServer smtp.rainpole.io -smtpPort 25 -senderAddress "vrops-alerts@rainpole.io" -secureConnection true -protocol TLS -authentication true -authUser administrator -authPass VMw@re1!
        This example creates and enables an Email Alert Plugin in vRealize Operations Manager with authentication
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pluginName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpPort,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$senderAddress,
        [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$secureConnection,
        [Parameter (Mandatory = $false)] [ValidateSet("SSL","TLS")] [ValidateNotNullOrEmpty()] [String]$protocol,
        [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$authentication,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$authUser,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$authPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (!(Get-vROPSAlertPlugin | Where-Object {$_.name -eq $pluginName})) {
                                if ($authentication -eq "true") {
                                    $json = '{
                                    "pluginTypeId" : "StandardEmailPlugin",
                                    "name" : "'
+ $pluginName +'",
                                    "description" : "",
                                    "configValues" : [ {
                                        "name" : "IS_SECURE_CONNECTION",
                                        "value" : "'
+ $secureConnection +'"
                                    }, {
                                        "name" : "SECURE_CONNECTION_TYPE",
                                        "value" : "'
+ $protocol +'"
                                    }, {
                                        "name" : "IS_REQUIRES_AUTHETICATION",
                                        "value" : "'
+ $authentication +'"
                                    }, {
                                        "name" : "USERNAME",
                                        "value" : "'
+ $authUser +'"
                                    }, {
                                        "name" : "PASSWORD",
                                        "value" : "'
+ $authPass +'"
                                    },{
                                        "name" : "SMTP_HOST",
                                        "value" : "'
+ $smtpServer +'"
                                    }, {
                                        "name" : "SMTP_PORT",
                                        "value" : "'
+ $smtpPort +'"
                                    }, {
                                        "name" : "senderEmailAddress",
                                        "value" : "'
+ $senderAddress +'"
                                    }, {
                                        "name" : "senderName",
                                        "value" : "'
+ ($senderAddress -split("@"))[0] +'"
                                    } ]
                                    }'

                                } else {
                                    $json = '{
                                        "pluginTypeId" : "StandardEmailPlugin",
                                        "name" : "'
+ $pluginName +'",
                                        "description" : "",
                                        "configValues" : [ {
                                            "name" : "IS_SECURE_CONNECTION",
                                            "value" : "'
+ $secureConnection +'"
                                        }, {
                                            "name" : "SECURE_CONNECTION_TYPE",
                                            "value" : "'
+ $protocol +'"
                                        }, {
                                            "name" : "SMTP_HOST",
                                            "value" : "'
+ $smtpServer +'"
                                        }, {
                                            "name" : "SMTP_PORT",
                                            "value" : "'
+ $smtpPort +'"
                                        }, {
                                            "name" : "senderEmailAddress",
                                            "value" : "'
+ $senderAddress +'"
                                        }, {
                                            "name" : "senderName",
                                            "value" : "'
+ ($senderAddress -split("@"))[0] +'"
                                        } ]
                                        }'

                                }
                                $json | Out-File .\addAlertPlugin.json
                                Add-vROPSAlertPlugin -json .\addAlertPlugin.json | Out-Null
                                if (Get-vROPSAlertPlugin | Where-Object {$_.name -eq $pluginName}) {
                                    Set-vROPSAlertPluginStatus -pluginId (Get-vROPSAlertPlugin | Where-Object {$_.name -eq $pluginName}).pluginId -status true
                                    Write-Output "Adding Alert Plugin to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($pluginName): SUCCESSFUL"
                                } else {
                                    Write-Error "Adding Alert Plugin to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($pluginName): POST_VALIDATION_FAILED"
                                }
                                Remove-Item .\addAlertPlugin.json -Force -Confirm:$false
                            } else {
                                Write-Warning "Adding Alert Plugin to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) named ($pluginName), already exists: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROPSAlertPluginEmail

Function Import-vROPSNotification {
    <#
        .SYNOPSIS
        Adds notifications

        .DESCRIPTION
        The Import-vROPSNotification cmdlet adds notifications in vRealize Operations Manager. The cmdlet connects to
        SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that the .csv provided exists
        - Adds notifications based on a .csv file into vRealize Operations Manager

        .EXAMPLE
        Import-vROPSNotification -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -csvPath .\SampleNotifications\vrops-vcf-notifications.csv
        This example adds notifications based on the comma seperated value file provided
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$csvPath
    )

    if (!$PsBoundParameters.ContainsKey("csvPath")) {
        $csvPath = Get-ExternalFileName -title "Select the Comma Seperated Value (.csv) File" -fileType "csv" -location "default"
    }
    if (!(Test-Path -Path $csvPath)) {
        Write-Error  "Comma Seperated Value (.csv) File ($csvPath) File Not Found"
        Break
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            New-vROPSNotification $csvPath | Out-Null
                            Write-Output "Adding Notifications to vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)) using Comma Seperated Value File ($csvPath): SUCCESSFUL"
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Import-vROPSNotification

Function Test-vROPsAdapterStatusByType {
    <#
        .SYNOPSIS
        Validates the integration status of vRealize Operations Adapters.

        .DESCRIPTION
        The Test-vROPsAdapterStatusByType cmdlet tests the integration status between vRealize Operations Manager and configured adapter.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates the integration status between vRealize Operations Manager and configured adapter

        .EXAMPLE
        Test-vROPsAdapterStatusByType -server sfo-vcf01.sfo.rainpole.io "administrator@vsphere.local" -pass "VMw@re1!" -adapterKind NSXTAdapter
        This example validates the integration status between vRealize Operations Manager and NSXT adapter.

        .EXAMPLE
        Test-vROPsAdapterStatusByType -server sfo-vcf01.sfo.rainpole.io "administrator@vsphere.local" -pass "VMw@re1!" -adapterKind CASAdapter
        This example validates the integration status between vRealize Operations Manager and vRealize Automation adapter.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateSet("Container", "EP Ops Adapter", "Http Post", "LogInsight", "MicrosoftAzureAdapter", "AmazonAWSAdapter", "NSXTAdapter", "PingAdapter", "SDDCHealthAdapter", "APPLICATIONDISCOVERY", "VMWARE", "VmcAdapter", "IdentityManagerAdapter", "APPOSUCP", "VOAAdapter", "CASAdapter", "LogInsightAdapter", "NETWORK_INSIGHT", "vCenter Operations Adapter", "vRealizeOpsMgrAPI", "VirtualAndPhysicalSANAdapter")] [ValidateNotNullOrEmpty()] [String]$adapterKind
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {   
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (Get-vROPSSolution | Where-Object { $_.adapterKindKeys -eq $adapterKind }) {  
                                if ((Get-vROPSAdapter | Where-Object { $_.resourceKey.adapterKindKey -eq $adapterKind })) {  
                                    $adapterJson = Get-vROPSAdapter | Where-Object { $_.resourceKey.adapterKindKey -eq $adapterKind } 
                                    $adapterJson | ForEach-Object {
                                        Test-vROPSAdapterStatus -resourceId $_.id
                                    }
                                } else {
                                    Write-Error "'$($adapterKind)' Adapter is not configured" 
                                }
                            } else { 
                                Write-Error "Unable to find '$($adapterKind)' Adapter" 
                            }
                        }                                          
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Test-vROPsAdapterStatusByType

Function Update-vROPSvRAAdapterCredential {
    <#
        .SYNOPSIS
        Update the credential of vRealize Automation adapter in vRealize Operations Manager

        .DESCRIPTION
        The Update-vROPSvRAAdapterCredential cmdlet update the credential of vRealize Automation adapter in vRealize Operations Manager. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values.
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Operations Manager has been deployed in VMware Cloud Foundation aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrieves its details
        - Validates that network connectivity is possible to vRealize Automation
        - Validates that the vRealize Automation adapter exists and configured in vRealize Operations Manager
        - Validates that the credential name of vRealize Automation adapter does not already exist in vRealize Operations Manager
        - Validates that the given credential is valid and updates vRealize Automation adapter in vRealize Operations Manager
        - Verifies the vRealize Automation adapter status in vRealize Operations Manager after updating the credential

        .EXAMPLE
        Update-vROPSvRAAdapterCredential -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -credential_displayname "vRealize Automation Credentials" -credential_username svc-vrops-vra@sfo.rainpole.io -credential_password VMw@re1! -adapterKind CASAdapter
        This example update the credential of vRealize Automation adapter with name "vRealize Automation Credentials" in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$credential_displayname,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$credential_username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$credential_password,
        [Parameter (Mandatory = $true)] [ValidateSet("CASAdapter")] [ValidateNotNullOrEmpty()] [String]$adapterKind
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {   
                        if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                            if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                                if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {  
                                    if (Get-vROPSSolution | Where-Object { $_.adapterKindKeys -eq $adapterKind }) {
                                        if ((Get-vROPSAdapter | Where-Object { $_.resourceKey.adapterKindKey -eq $adapterKind })) {
                                            if (!(Get-vROPSCredential | Where-Object { $_.name -eq $credential_displayname })) {
                                                $credentialJson = ' {
                                                                        "name" : "'
+ $credential_displayname + '",
                                                                        "adapterKindKey" : "'
+ $adapterKind + '",
                                                                        "credentialKindKey" : "CMPCREDENTIALS",
                                                                            "fields" : [ {
                                                                                "name" : "USERNAME",
                                                                                "value" : "'
+ $credential_username + '"
                                                                                }, {
                                                                                "name" : "PASSWORD",
                                                                                "value" : "'
+ $credential_password + '"
                                                                            } ]
                                                                        }'

                                                $credentialJson | Out-File .\addCredential.json
                                                Add-vROPSCredential -json .\addCredential.json | Out-Null
                                                Remove-Item .\addCredential.json -Force -Confirm:$false
                                                if ((Get-vROPSCredential | Where-Object { $_.name -eq $credential_displayname })) { 
                                                    Write-Output "Adding vRealize Automation credential named ($credential_displayname) in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"
                                                    $vraAdapterObj = Get-vROPSAdapter | Where-Object { $_.resourceKey.adapterKindKey -eq $adapterKind } 
                                                    $vraAdapterId = $vraAdapterObj.id
                                                    $adapterName = $vraAdapterObj.resourceKey.name
                                                    $credid = (Get-vROPSCredential | Where-Object { $_.name -eq $credential_displayname }).id
                                                    $vraAdapterObj.credentialInstanceId = $credid
                                                    $vraAdapterObj.PSObject.Properties.Remove('links')
                                                    $vraAdapterObj.PSObject.Properties.Remove('lastHeartbeat')
                                                    $vraAdapterObj.PSObject.Properties.Remove('messageFromAdapterInstance')
                                                    $vraAdapterObj.PSObject.Properties.Remove('lastCollected')
                                                    $vraAdapterObj.PSObject.Properties.Remove('numberOfMetricsCollected')
                                                    $vraAdapterObj.PSObject.Properties.Remove('numberOfResourcesCollected')
                                                    $certificates = New-Object System.Collections.ArrayList
                                                    $vraAdapterObj | Add-Member -NotePropertyName adapter-certificates -NotePropertyValue ([Array]$certificates)
                                                    $vraAdapterObj | ConvertTo-Json -Depth 4 | Out-File .\vraadapter.json
                                                    $testresponse = Test-vROPSAdapterConnection -json .\vraadapter.json -patch
                                                    if ($testresponse.Count) { 
                                                        Write-Output "Validating vRealize Automation credential named ($credential_displayname) in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"
                                                        Set-vROPSAdapter -json .\vraadapter.json | Out-Null
                                                        Write-Output "Updating vRealize Automation adapter named ($adapterName) in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"
                                                        Start-vROPSAdapter -adapterId $vraAdapterId | Out-Null
                                                        Start-Sleep 5
                                                        Write-Output "Verifying vRealize Automation adapter status... $(Test-vROPsAdapterStatus -resourceId $vraAdapterId)"
                                                    } else {
                                                        Write-Error "Validating vRealize Automation credential named ($credential_displayname) in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALDATION_FAILED"
                                                        Remove-vROPSCredential -credentialId $credid
                                                        Write-Output "Removing vRealize Automation credential named ($credential_displayname) in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): SUCCESSFUL"    
                                                    }
                                                    Remove-Item .\vraadapter.json -Force -Confirm:$false 
                                                } else {
                                                    Write-Error "Adding vRealize Automation credential named ($credential_displayname) in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)): POST_VALDATION_FAILED"
                                                    Break
                                                }
                                            } else {
                                                Write-Error "Adding vRealize Automation credential named ($credential_displayname) in vRealize Operations Manager ($($vcfVropsDetails.loadBalancerFqdn)), already exists: SKIPPED"
                                                Break
                                            }
                                        } else {
                                            Write-Error "'$($adapterKind)' Adapter is not configured: PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find '$($adapterKind)' Adapter: PRE_VALIDATION_FAILED"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-vROPSvRAAdapterCredential

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region P R I V A T E C L O U D A U T O M A T I O N F U N C T I O N S ###########

Function Export-vRAJsonSpec {
    <#
        .SYNOPSIS
        Create vRealize Automation Deployment JSON specification

        .DESCRIPTION
        The Export-vRAJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook
        to deploy vRealize Automation using vRealize Suite Lifecycle Manager:
        - Validates that the Planning and Preparation is available
        - Validates that network connectivity is available to vRealize Suite Lifecycle Manager
        - Makes a connection to the vRealize Suite Lifecycle Manager instance and validates that authentication possible
        - Generates the JSON specification file using the Planning and Preparation workbook and details from vRealize Suite Lifecycle Manager

        .EXAMPLE
        Export-vRAJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example creates a JSON deployment specification of vRealize Automation using the Planning and Preparation Workbook
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook
    )

    Try {

        if (!$PsBoundParameters.ContainsKey("workbook")) {
            $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
        } else {
            if (!(Test-Path -Path $workbook)) {
                Write-Error  "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found"
                Break
            }
        }

        $pnpWorkbook = Open-ExcelPackage -Path $workbook

        ### Obtain Configuration Information from vRealize Suite Lifecycle Manager
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S'
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if ($pnpWorkbook.Workbook.Names["vra_license"].Value) {
                                $licenseKey = $pnpWorkbook.Workbook.Names["vra_license"].Value
                            } else {
                                $licenseKey = $pnpWorkbook.Workbook.Names["vrs_license"].Value
                            }
                            $vraLicense = Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $licenseKey}
                            if ($vraLicense.key -eq $licenseKey) { 
                                $vraCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_vra_virtual_hostname"].Value}
                                if ($vraCertificate.alias) {
                                    $defaultPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value
                                    if ($defaultPassword.alias) {
                                        $vraPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["xreg_vra_root_password_alias"].Value
                                        if ($vraPassword.alias) {
                                            if ($vcfVersion -eq "4.5.0") {
                                                $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.userName -match (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "@vsphere.local")}
                                            } else {
                                                $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value)
                                            }
                                            $datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value}
                                            if ($datacenterName) {
                                                $xintEnvironment = Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value}

                                                $infrastructurePropertiesObject = @()
                                                $infrastructurePropertiesObject += [pscustomobject]@{
                                                    'acceptEULA'            = "true"
                                                    'enableTelemetry'        = "true"
                                                    'regionName'            = "default"
                                                    'zoneName'                = "default"
                                                    'dataCenterVmid'        = $datacenterName.dataCenterVmid
                                                    'vCenterName'            = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0]
                                                    'vCenterHost'            = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value
                                                    'vcUsername'            = $vcCredentials.userName
                                                    'vcPassword'            = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias))
                                                    'defaultPassword'        = ("locker:password:" + $($defaultPassword.vmid) + ":" + $($defaultPassword.alias))
                                                    'certificate'            = ("locker:certificate:" + $($vraCertificate.vmid) + ":" + $($vraCertificate.alias))
                                                    'cluster'                = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value)
                                                    'storage'                = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                                    'diskMode'                = "thin"
                                                    'network'                = $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value
                                                    'masterVidmEnabled'        = "false"
                                                    'dns'                    = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value)
                                                    'domain'                = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value
                                                    'gateway'                = $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value
                                                    'netmask'                = $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value
                                                    'searchpath'            = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value
                                                    'timeSyncMode'            = "ntp"
                                                    'ntp'                    = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value
                                                    'vcfProperties'            = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}'
                                                }

                                                $infrastructureObject = @()
                                                $infrastructureObject += [pscustomobject]@{
                                                    'properties'    = ($infrastructurePropertiesObject | Select-Object -Skip 0)
                                                }

                                                ### Generate the Properties Details
                                                $productPropertiesObject = @()
                                                $productPropertiesObject += [pscustomobject]@{
                                                    'certificate'                    = ("locker:certificate:" + $($vraCertificate.vmid) + ":" + $($vraCertificate.alias))
                                                    'productPassword'                = ("locker:password:" + $($vraPassword.vmid) + ":" + $($vraPassword.alias))
                                                    'licenseRef'                    = ("locker:license:" + $($vraLicense.vmid) + ":" + $($vraLicense.alias))
                                                    'fipsMode'                        = "false"
                                                    'timeSyncMode'                    = "ntp"
                                                    'ntp'                            = $pnpWorkbook.Workbook.Names["region_ntp1_server"].Value
                                                    'affinityRule'                    = $false
                                                    'configureAffinitySeparateAll'  = "true"
                                                    'nodeSize'                        = $pnpWorkbook.Workbook.Names["xreg_vra_appliance_size"].Value.ToLower()
                                                    'vraK8ServiceCidr'              = $pnpWorkbook.Workbook.Names["xreg_vra_k8s_cluster_cidr"].Value
                                                    'vraK8ClusterCidr'              = $pnpWorkbook.Workbook.Names["xreg_vra_k8s_service_cidr"].Value
                                                    'clusterFqdn'                   = $pnpWorkbook.Workbook.Names["xreg_vra_virtual_fqdn"].Value
                                                }

                                                #### Generate vRealize Automation Cluster Details
                                                $clusterVipProperties = @()
                                                $clusterVipProperties += [pscustomobject]@{
                                                    'hostName'                = $pnpWorkbook.Workbook.Names["xreg_vra_virtual_fqdn"].Value
                                                }
                                                $clusterVipsObject = @()
                                                $clusterVipsObject += [pscustomobject]@{
                                                    'type'            = "vra-va"
                                                    'properties'    = ($clusterVipProperties | Select-Object -Skip 0)
                                                }
                                                $clusterObject = @()
                                                $clusterObject += [pscustomobject]@{
                                                'clusterVips'    = $clusterVipsObject
                                                }

                                                #### Generate vRealize Automation Node Details
                                                $vraPrimaryProperties = @()
                                                $vraPrimaryProperties += [pscustomobject]@{
                                                    'hostName'          = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_fqdn"].Value
                                                    'vmName'            = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_hostname"].Value
                                                    'ip'                = $pnpWorkbook.Workbook.Names["xreg_vra_nodea_ip"].Value
                                                }
                                                $vraSecondary1Properties = @()
                                                $vraSecondary1Properties += [pscustomobject]@{
                                                    'hostName'          = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_fqdn"].Value
                                                    'vmName'            = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_hostname"].Value
                                                    'ip'                = $pnpWorkbook.Workbook.Names["xreg_vra_nodeb_ip"].Value
                                                }
                                                $vraSecondary2Properties = @()
                                                $vraSecondary2Properties += [pscustomobject]@{
                                                    'hostName'          = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_fqdn"].Value
                                                    'vmName'            = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_hostname"].Value
                                                    'ip'                = $pnpWorkbook.Workbook.Names["xreg_vra_nodec_ip"].Value
                                                }
                                                $nodesObject = @()
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "vrava-primary"
                                                    'properties'    = ($vraPrimaryProperties | Select-Object -Skip 0)
                                                }
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "vrava-secondary"
                                                    'properties'    = ($vraSecondary1Properties | Select-Object -Skip 0)
                                                }
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "vrava-secondary"
                                                    'properties'    = ($vraSecondary2Properties | Select-Object -Skip 0)
                                                }

                                                #### Generate the vRealize Automation Properties Section
                                                if ($vcfVersion -eq "4.3.0") { $vraVersion = "8.4.1"}
                                                if ($vcfVersion -eq "4.3.1") { $vraVersion = "8.5.0"}
                                                if ($vcfVersion -eq "4.4.0") { $vraVersion = "8.6.2"}
                                                if ($vcfVersion -eq "4.4.1") { $vraVersion = "8.6.2"}
                                                if ($vcfVersion -eq "4.5.0") { $vraVersion = "8.8.2"}
                                                $productsObject = @()
                                                $productsObject += [pscustomobject]@{
                                                    'id'             = "vra"
                                                    'version'        = $vraVersion
                                                    'properties'    = ($productPropertiesObject  | Select-Object -Skip 0)
                                                    'clusterVIP'    = ($clusterObject  | Select-Object -Skip 0)
                                                    'nodes'            = $nodesObject    
                                                }
                                                if (!($xintEnvironment)) { 
                                                    $vraDeploymentObject = @()
                                                    $vraDeploymentObject += [pscustomobject]@{
                                                        'environmentName'       = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value
                                                        'infrastructure'        = ($infrastructureObject  | Select-Object -Skip 0)
                                                        'products'              = $productsObject     
                                                    }
                                                } else {
                                                    $vraDeploymentObject = @()
                                                    $vraDeploymentObject += [pscustomobject]@{
                                                        'environmentId'         = $xintEnvironment.environmentId
                                                        'environmentName'       = $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value
                                                        'infrastructure'        = ($infrastructureObject  | Select-Object -Skip 0)
                                                        'products'              = $productsObject     
                                                    }
                                                }
                                                $vraDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "vraDeploymentSpec.json" 
                                                
                                                Write-Output "Creation of Deployment JSON Specification file for vRealize Automation: SUCCESSFUL"
                                            } else {
                                                Write-Error "Datacenter Provided in the Planning and Preparation Workbook '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value)' does not exist, create and retry"
                                            }
                                        } else {
                                            Write-Error "Root Password with alias '$($pnpWorkbook.Workbook.Names["xreg_vra_root_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                                        }
                                    } else {
                                        Write-Error "Admin Password with alias '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_env_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                                    }
                                } else {
                                    Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["xreg_vra_virtual_hostname"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                                }
                            } else {
                                Write-Error "License with alias '$licenseKey' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                            }
                        }
                    }
                }
            }
        }
        Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Export-vRAJsonSpec

Function New-vRADeployment {
    <#
        .SYNOPSIS
        Deploy vRealize Automation to vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The New-vRADeployment cmdlet deploys vRealize Automation via vRealize Suite Lifecycle Manager. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has not been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Requests a new deployment of vRealize Automation

        .EXAMPLE
        New-vRADeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example starts a deployment of vRealize Automation using the Planning and Preparation Workbook
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor
    )

    if (!$PsBoundParameters.ContainsKey("workbook")) {
        $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
    } else {
        if (!(Test-Path -Path $workbook)) {
            Write-Error  "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found"
            Break
        }
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            Export-vRAJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null
                            $json = (Get-Content -Raw .\vraDeploymentSpec.json)
                            $jsonSpec = $json | ConvertFrom-Json
                            if (!((Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName}).products.id -contains $jsonSpec.products.id)) {
                                if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.productPassword.Split(":")[3])) {
                                    if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) {
                                        if (Get-vRSLCMLockerLicense | Where-Object {$_.alias -Match $($jsonSpec.products.properties.licenseRef.Split(":")[3])}) {
                                            if ($jsonSpec.environmentId) {
                                                $newRequest = Add-vRSLCMEnvironment -json $json -environmentId $jsonSpec.environmentId -addProduct
                                            } else {
                                                $newRequest = Add-vRSLCMEnvironment -json $json
                                            }
                                            if ($newRequest) {
                                                if ($PsBoundParameters.ContainsKey("monitor")) {
                                                    Start-Sleep 10
                                                    Watch-vRSLCMRequest -vmid $($newRequest.requestId)
                                                } else {
                                                    Write-Output "Deployment Rquest for vRealize Automation Submitted Successfully (Request Ref: $($newRequest.requestId))"
                                                }
                                            } else {
                                                Write-Error "Request to deploy vRealize Automation failed, check the vRealize Suite Lifecycle Manager UI"
                                            }
                                        } else {
                                            Write-Error "License in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.licenseRef.Split(":")[3])), does not exist: FAILED"
                                        }
                                    } else {
                                        Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: FAILED"
                                    }
                                } else {
                                    Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.productPassword.Split(":")[3])), does not exist: FAILED"
                                }
                            } else {
                                Write-Warning "vRealize Automation in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)), already exists: SKIPPED"
                            }
                        }
                    }
                } 
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vRADeployment

Function Update-vRAOrganizationDisplayName {
    <#
        .SYNOPSIS
        Configures the organization name

        .DESCRIPTION
        The Update-vRAOrganizationDisplayName cmdlet configures the organization display name in vRealize Automation. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Verifies if the organization name is already configured based on the input
        - Configures the organization name

        .EXAMPLE
        Update-vRAOrganizationDisplayName -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -displayName "Rainpole" -vraUser configadmin -vraPass VMw@re1!
        This example configures the organization display name as 'Rainpole'
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$displayName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1]
                            if (!((Get-vRAOrganizationDisplayName -orgId $orgId).displayname -eq $displayName)) {
                                Set-vRAOrganizationDisplayName -orgId $orgId -displayName $displayName | Out-Null
                                if ((Get-vRAOrganizationDisplayName -orgId $orgId).displayname -eq $displayName) {
                                    Write-Output "Updating Organization Display Name in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): SUCCESSFUL"
                                } else {
                                    Write-Error "Updating Organization Display Name in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): FAILED"
                                }
                            } else {
                                Write-Warning "Updating Organization Display Name in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)), already defined: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-vRAOrganizationDisplayName

Function New-vRACloudAccount {
    <#
        .SYNOPSIS
        Creates vSphere and NSX-T Cloud Accounts

        .DESCRIPTION
        The New-vRACloudAccount cmdlet creates the vSphere and NSX-T Cloud Accounts for a Workload Domain in vRealize
        Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Retrives details from SDDC Manager for the vCenter Server and NSX Management Cluster
        - Adds a Cloud Account for vCenter Server and NSX Management Cluster

        .EXAMPLE
        New-vRACloudAccount -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! -capabilityTab private
        This example creates vSphere and NSX-T Cloud Accounts in vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$capabilityTab
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                                $vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain
                                $vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain
                                if (!(Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)})) {
                                    Connect-VIServer -Server $vcfVcenterDetails.fqdn -User $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass | Out-Null
                                    if ($DefaultVIServer.Name -eq $($vcfVcenterDetails.fqdn)) {
                                        $dataCenterMoref = (Get-View -Server $($vcfVcenterDetails.fqdn) -viewtype Datacenter).MoRef
                                        $vcenterCloudAccount = '{
                                            "hostName": "'
 + $($vcfVcenterDetails.fqdn) + '",
                                            "acceptSelfSignedCertificate": true,
                                            "username": "'
 + $($vcfVcenterDetails.ssoAdmin) + '",
                                            "password": "'
 + $($vcfVcenterDetails.ssoAdminPass) + '",
                                            "dcId": "onprem",
                                            "createDefaultZones": true,
                                            "name": "'
 + $($vcfVcenterDetails.vmName) + '",
                                            "regionIds": [ "'
 + $($dataCenterMoref.type) + ":" + $($dataCenterMoref.value) +'" ],
                                            "tags": [ { "key": "'
 + $capabilityTag + '", "value": "" } ]
                                        }'

                                        Add-vRACloudAccount -type vsphere -json $vcenterCloudAccount | Out-Null
                                        if (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}) {
                                            Write-Output "Creating vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                        } else {
                                            Write-Error "Creating vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to connect to vCenter Server ($($vcfVcenterDetails.fqdn)): PRE_VALIDATION_FAILED"
                                    }
                                    Disconnect-VIServer $($vcfVcenterDetails.fqdn) -Confirm:$false -WarningAction SilentlyContinue
                                } else {
                                    Write-Warning "Creating vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)), already exists: SKIPPED"
                                }
                                if (!(Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]})) {
                                    $nsxtCloudAccount = '{
                                        "hostName": "'
 + $($vcfNsxtDetails.fqdn) + '",
                                        "acceptSelfSignedCertificate": true,
                                        "password": "'
 + $($vcfNsxtDetails.adminPass) + '",
                                        "name": "'
 + ($vcfNsxtDetails.fqdn).Split(".")[0] + '",
                                        "username": "'
 + $($vcfNsxtDetails.adminUser) + '",
                                        "associatedCloudAccountIds": [ "'
 + (Get-vRACloudAccount -type vsphere | Where-Object {$_.name -eq $vcfVcenterDetails.vmName}).id + '" ],
                                        "tags": [ { "key": "'
 + $capabilityTag + '", "value": "" } ]
                                    }'

                                    Add-vRACloudAccount -type nsx-t -json $nsxtCloudAccount | Out-Null
                                    if (Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]}) {
                                        Write-Output "Creating NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): SUCCESSFUL"
                                    } else {
                                        Write-Error "Creating NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): POST_VALIDATED_FAILED"
                                    }
                                } else {
                                    Write-Warning "Creating NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])), already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vRACloudAccount

Function Undo-vRACloudAccount {
    <#
        .SYNOPSIS
        Removes the vSphere and NSX-T Cloud Accounts

        .DESCRIPTION
        The Undo-vRACloudAccount cmdlet removes the vSphere and NSX-T Cloud Accounts for a Workload Domain in vRealize
        Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Retrives details from SDDC Manager for the vCenter Server and NSX Management Cluster
        - Removes the Cloud Accounts for vCenter Server and NSX Management Cluster

        .EXAMPLE
        Undo-vRACloudAccount -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1!
        This example creates vSphere and NSX-T Cloud Accounts in vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vraPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                                $vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain
                                $vcfNsxtDetails = Get-NsxtServerDetail -fqdn $server -username $user -password $pass -domain $domain
                                if (Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]}) {
                                    Remove-vRACloudAccount -id (Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]}).id | Out-Null
                                    if (!(Get-vRACloudAccount -type nsx-t | Where-object {$_.name -eq ($vcfNsxtDetails.fqdn).Split(".")[0]})) {
                                        Write-Output "Removing NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])): POST_VALIDATED_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing NSX-T Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($(($vcfNsxtDetails.fqdn).Split(".")[0])), does not exist: SKIPPED"
                                }
                                if (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}) {
                                    Remove-vRACloudAccount -id (Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)}).id | Out-Null
                                    if (!(Get-vRACloudAccount -type vsphere | Where-object {$_.name -eq $($vcfVcenterDetails.vmName)})) {
                                        Write-Output "Removing vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)): POST_VALIDATION_FAILED"
                                    } 
                                } else {
                                    Write-Warning "Removing vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($vcfVcenterDetails.fqdn)), does not exist: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRACloudAccount

Function Update-vRACloudAccountZone {
    <#
        .SYNOPSIS
        Update Cloud Zone Configuration

        .DESCRIPTION
        The Update-vRACloudAccountZone cmdlet updated the Cloud Zone with folder and tags on the resource pool for a
        Workload Domain in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates the Workload Domain is available in the SDDC Manager Inventory
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Validates that a Cloud Account exists for the Workload Domain in vRealize Automation instance
        - Validates that the Resource Pool is availble in vRealize Automation as a Compute Resource
        - Adds the tag to the Resource Pool Compute Resource
        - Adds the folder to the Cloud Account Zone as a target
        - Adds a dynamic filter to use the defined tags
        - Updates the placement policy

        .EXAMPLE
        Update-vRACloudAccountZone -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! -tagKey enabled -tagValue true -folder "sfo-w01-fd-workload" -resourcePool "sfo-w01-cl01-rp-workload"
        This example updates the Cloud Zone for the Workload Domain with a default folder and adds tags to the resource pool for dynamic provisioning in vRealize Automation
        
        .EXAMPLE
        Update-vRACloudAccountZone -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! -placementPolicy ADVANCED
        This example updates the placement policy for the Cloud Zone to ADVANCED in vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagKey,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagValue,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$folder,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$resourcePool,
        [Parameter (Mandatory = $false)] [ValidateSet("ADVANCED", "DEFAULT", "SPREAD", "BINPACK")][ValidateNotNullOrEmpty()] [String]$placementPolicy
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            $vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain
                            if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                                if (Get-vRACloudAccount -type vsphere | Where-Object { $_.name -eq $($vcfVcenterDetails.vmName) }) {
                                    if ($PsBoundParameters.ContainsKey("resourcePool")) { 
                                        $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                        if (Get-vRAResourceCompute | Where-Object { $_.name -eq ($cluster + " / " + $resourcePool) }) {
                                            $cloudZoneDetails = Get-vRACloudZone | Where-Object { $_.cloudAccountId -eq (Get-vRACloudAccount -type vsphere | Where-Object { $_.name -eq $($vcfVcenterDetails.vmName) }).id }
                                            Add-vRAResourceComputeTag -id (Get-vRAResourceCompute | Where-Object { $_.name -eq ($cluster + " / " + $resourcePool) }).id -tagKey $tagKey -tagValue $tagValue | Out-Null
                                            Update-VRACloudZone -id $cloudZoneDetails.id -folder $folder | Out-Null
                                            Update-VRACloudZone -id $cloudZoneDetails.id -tagKey $tagKey -tagValue $tagValue | Out-Null
                                            Write-Output "Updating Cloud Zone Configuration in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($($cluster + " / " + $resourcePool)): SUCCESSFUL"
                                        } else {
                                            Write-Error "Unable to find Resource Pool in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn) named ($resourcePool): PRE_VALIDATION_FAILED"
                                        } 
                                    } 
                                    if ($PsBoundParameters.ContainsKey("placementPolicy")) { 
                                        $cloudZoneDetails = Get-vRACloudZone | Where-Object { $_.cloudAccountId -eq (Get-vRACloudAccount -type vsphere | Where-Object { $_.name -eq $($vcfVcenterDetails.vmName) }).id }
                                        Update-VRACloudZone -id $cloudZoneDetails.id -placementPolicy $placementPolicy | Out-Null
                                        Write-Output "Updating placement policy to $placementPolicy in Cloud Zone Configuration in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): SUCCESSFUL"
                                    }
                                } else {
                                    Write-Error "Unable to find vSphere Cloud Account in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn) named ($($vcfVcenterDetails.vmName)): PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                            }   
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-vRACloudAccountZone

Function Add-vROvCenterServer {
    <#
        .SYNOPSIS
        Adds a vCenter Server instance to an embedded vRealize Orchestrator.

        .DESCRIPTION
        The Add-vROvCenterServer cmdlet invokes the workflow in vRealize Orchestrator to add a vCenter Server.
        The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values
        to return the workload domain vCenter Server details from its inventory and then:
        - Makes a connection to the embedded vRealize Orchestrator using the -vraUser and -vraPass values.
        - Verifies the workflow exists.
        - Verifies that the vCenter Server instance exists in the vRealize Orchestrator catalog.
        - Adds the vCenter Server instance using the -vcUser and -vcPass values.

        .EXAMPLE
        Add-vROvCenterServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1! -vcUser administrator@vsphere.local -vcPass VMw@re1!
        This example adds the vCenter Server instance from the "sfo-w01" workload domain from the embedded vRealize Orchestrator catalog.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcPass
    )

    $workflowName = "Add a vCenter Server instance"

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                                $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain                    
                                $checkExists = (Invoke-RestMethod -Method 'GET' -URI "https://$($vcfVraDetails.loadBalancerFqdn)/vco/api/catalog/VC" -headers $vraHeaders)
                                if ((($checkExists.relations.link.attributes | Where-Object { $_.name -eq "id" }).value) -ne "$($vcenter.fqdn)") {
                                    if ($workflow = Get-vROWorkflow -name $workflowName) {
                                        $parameters =  
                                        @"
{"parameters":
    [
        {
            "value": {
                "boolean": {
                    "value": true
                }
            },
            "type": "boolean",
            "name": "enabled",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "$($vcenter.fqdn)"
                }
            },
            "type": "string",
            "name": "host",
            "scope": "local"
        },
        {
            "value": {
                "number": {
                    "value": 443
                }
            },
            "type": "number",
            "name": "port",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "/sdk"
                }
            },
            "type": "string",
            "name": "path",
            "scope": "local"
        },
        {
            "value": {
                "boolean": {
                    "value": false
                }
            },
            "type": "boolean",
            "name": "sessionPerUser",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "$vcUser"
                }
            },
            "type": "string",
            "name": "userName",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "$vcPass"
                }
            },
            "type": "string",
            "name": "password",
            "scope": "local"
        },
        {
            "value": {
                "boolean": {
                    "value": true
                }
            },
            "type": "boolean",
            "name": "ignoreCertificateWarnings",
            "scope": "local"
        },
        {
            "value": {
                "number": {
                    "value": 443
                }
            },
            "type": "number",
            "name": "httpPort",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "https://$($vcenter.fqdn):443/pbm"
                }
            },
            "type": "string",
            "name": "pbmUrl",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "https://$($vcenter.fqdn):443/sms/sdk"
                }
            },
            "type": "string",
            "name": "smsUrl",
            "scope": "local"
        }
    ]
}
"@

                                        $response = Invoke-vROWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters 
                                        if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -ne "failed"}) { 
                                            Do {
                                                $workflowStatus = (Get-vROWorkflowExecutionState -executionStateRef $response.Execution).Execution
                                            }  Until ($workflowStatus -ne "running")
                                            if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -eq "completed"}) { 
                                                Write-Output "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): SUCCESSFUL"
                                            } else {
                                                Write-Error "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain), check credentials: POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find the workflow named ($workflowName) to embedded vRealize Orcherator ($($vcfVraDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Adding vCenter Server ($($vcenter.fqdn)) to embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain), already exists: SKIPPED"
                                }                                
                            } else {
                                Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROvCenterServer

Function Remove-vROvCenterServer {
    <#
        .SYNOPSIS
        Removes a vCenter Server instance from an embedded vRealize Orchestrator.

        .DESCRIPTION
        The Remove-vROvCenterServer cmdlet invokes the workflow in vRealize Orchestrator to remove a vCenter Server.
        The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values
        to return the workload domain vCenter Server details from its inventory and then:
        - Makes a connection to the embedded vRealize Orchestrator using the -vraUser and -vraPass values.
        - Verifies the workflow exists.
        - Verifies that the vCenter Server instance exists in the vRealize Orchestrator catalog.
        - Removes the vCenter Server instance.

        .EXAMPLE
        Remove-vROvCenterServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -vraUser configadmin -vraPass VMw@re1!
        This example removes the vCenter Server instance from the "sfo-w01" workload domain from the embedded vRealize Orchestrator catalog.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass
    )

    $workflowName = "Remove a vCenter Server instance"

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                                $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain                    
                                $checkExists = (Invoke-RestMethod -Method 'GET' -URI "https://$($vcfVraDetails.loadBalancerFqdn)/vco/api/catalog/VC" -headers $vraHeaders)
                                if ((($checkExists.relations.link.attributes | Where-Object { $_.name -eq "id" }).value) -eq "$($vcenter.fqdn)") {
                                    if ($workflow = Get-vROWorkflow -name $workflowName) {
                                        $parameters =  
                                        @"
{"parameters":
    [
        {
            "value": {
                "string": {
                    "value": "https://$($vcenter.fqdn):443/sdk"
                }
            },
            "type": "string",
            "name": "host",
            "scope": "local"
        }
    ]
}
"@

                                        $response = Invoke-vROWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters 
                                        if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -ne "failed"}) { 
                                            Do {
                                                $workflowStatus = (Get-vROWorkflowExecutionState -executionStateRef $response.Execution).Execution
                                            } Until ($workflowStatus -ne "running")
                                            if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object {$_.Execution -eq "completed"}) { 
                                                Write-Output "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): SUCCESSFUL"
                                            } else {
                                                Write-Error "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain): FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find the workflow named ($workflowName) in embedded vRealize Orcherator ($($vcfVraDetails.loadBalancerFqdn)): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing vCenter Server ($($vcenter.fqdn)) from embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)) for Workload Domain ($domain), does not exist: SKIPPED"
                                }                                
                            } else {
                                Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Remove-vROvCenterServer

Function Add-vROTrustedCertificate {
    <#
        .SYNOPSIS
        Adds a trusted certificate to an embedded vRealize Orchestrator.

        .DESCRIPTION
        The Add-vROTrustedCertificate cmdlet invokes a workflow in vRealize Orchestrator to add trusted certificate.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then:
        - Makes a connection to the embedded vRealize Orchestrator using the -vraUser and -vraPass values.
        - Verifies the workflow exists.
        - Adds the trusted certificate using the -certFile value.

        .EXAMPLE
        Add-vROTrustedCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -certFile "C:\Root64.pem"
        This example adds a trusted certificate in PEM-encoded format to the embedded vRealize Orchestrator.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certFile
    )

    $workflowName = "Import a trusted certificate from a file"

    if (!$PsBoundParameters.ContainsKey("certFile")) {
        $certFile = Get-ExternalFileName -title "Select the trusted certificate file (.cer)" -fileType "cer" -location "default"
    } elseif ($PsBoundParameters.ContainsKey("certFile")) {
        if (!(Test-Path -Path $certFile)) {
            Write-Error  "Selecting the trusted certificate file ($certFile), file not found: PRE_VALIDATION_FAILED"
            Break
        }
    }

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {         
                            if ($workflow = Get-vROWorkflow -name $workflowName) {
                                $certName = Split-Path -Path "$certFile" -Leaf
                                $certContent = [Convert]::ToBase64String([IO.File]::ReadAllBytes("$certFile"))
                                $parameters =  
                                @"
{"parameters":
    [
        {"value": {
            "mime-attachment": {
                "name":"$certName",
                "content": "$certContent",
                "mime-type": "application/x-x509-ca-cert"}
            },
            "type": "MimeAttachment",
            "name": "cer",
            "scope": "local"
        }
    ]
}
"@

                                $response = Invoke-vROWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters 
                                if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object { $_.Execution -ne "failed" }) {
                                    Do {
                                        $workflowStatus = (Get-vROWorkflowExecutionState -executionStateRef $response.Execution).Execution
                                    }  Until ($workflowStatus -ne "running")
                                    if (Get-vROWorkflowExecutionState -executionStateRef $response.Execution | Where-Object { $_.Execution -eq "completed" }) { 
                                        Write-Output "Adding trusted certificate ($certFile) to the embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding trusted certificate ($certFile) to the embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)), check certificate format: POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Adding trusted certificate ($certFile) to the embedded vRealize Orchestrator ($($vcfVraDetails.loadBalancerFqdn)): FAILED"
                                }
                            }                             
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vROTrustedCertificate

Function Add-vRANotification {
    <#
        .SYNOPSIS
        Adds notification settings in vRealize Automation.

        .DESCRIPTION
        The Add-vRANotification cmdlet adds notification settings to vRealize Automation. The cmdlet connects to SDDC
        Manager using the -server, -user, -password, and -domain values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - MValidates that network connectivity and authentication is possible to vRealize Automation
        - Adds notifications settings to vRealize Automation

        .EXAMPLE
        Add-vRANotification -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -smtpServer smtp.raipole.io -emailAddress vra-no-reply@rainpole.io -sender "Rainpole Cloud" -connection NONE
        This example adds notifications settings for vRealize Automation.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender,
        [Parameter (Mandatory = $true)] [ValidateSet("SSL","STARTTLS","NONE")] [ValidateNotNullOrEmpty()] [String]$connection
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            New-vRANotification -name $smtpServer -serverName $smtpServer -emailAddress $emailAddress -sender $sender -trustCert true -connection $connection -authentication false | Out-Null
                            if (Get-vRANotification | Where-Object {$_.name -eq $smtpServer}) {
                                Write-Output "Configuring Notification settings in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($smtpServer): SUCCESSFUL"
                            } else {
                                Write-Output "Configuring Notification settings in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) named ($smtpServer): POST_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRANotification

Function Add-vRAUser {
    <#
        .SYNOPSIS
        Adds user access in an organization.

        .DESCRIPTION
        The Add-vRAUser cmdlet adds user access in vRealize Automation. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Adds the user to both an organization role and a service role

        .EXAMPLE
        Add-vRAUser -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -email jdoe@rainpole.io -orgRole org_member -serviceRole automationservice:cloud_admin
        This example adds user access in vRealize Automation by userId and orgId along with the required orgRole and serviceRole.

        Note: This cmdlet currently only supports a single serviceRole.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole,
        [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin', 'automationservice:user', 'automationservice:viewer', 'catalog:admin', 'catalog:user', 'catalog:viewer', 'CodeStream:administrator', 'CodeStream:developer', 'CodeStream:executor', 'CodeStream:user', 'CodeStream:viewer', 'migration:admin', 'migration:viewer', 'orchestration:admin', 'orchestration:designer', 'orchestration:viewer', 'saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1]
                            if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email }) {
                                $userId = (Get-vRAUser -orgId $orgId -email $email).user.userId
                                $services = (Get-vRAServices -orgId $orgId)
                                $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1]
                                if (!(Get-vRAUserRoles -userId $userId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoles.name -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId})) {
                                    New-vRAUser -userId $userId -orgId $orgId -orgRole $orgRole -serviceRole $serviceRole -serviceDefinitionId $serviceDefinitionId | Out-Null
                                    if (Get-vRAUserRoles -userId $userId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoles.name -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId}) {
                                        Write-Output "Assigning user email ($email) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: SUCCESSFUL"
                                    } else {
                                        Write-Error "Assigning user email ($email) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Assigning user email ($email) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation, already exists: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find user email ($email) in Workspace ONE Access for vRealize Automation, check user synchronization or email: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRAUser

Function Undo-vRAUser {
    <#
        .SYNOPSIS
        Removes user access from an organization.

        .DESCRIPTION
        The Undo-vRAUser cmdlet removes user access in vRealize Automation. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Removes the user from an organization role and all service roles

        .EXAMPLE
        Undo-vRAUser -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -email jdoe@rainpole.io
        This example removes user access from vRealize Automation by email.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1]
                            if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email -and $_.organizationRoles.name -ne $null -and $_.serviceRoles.serviceDefinitionId -ne $null}) {
                                if ($objectCheck = Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email }) {
                                    if ($orgRole = ($objectCheck.organizationRoles.name)) {
                                        Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole $orgRole
                                    }
                                    if ($serviceRoles = ($objectCheck.serviceRoles.serviceRoles.name)) {
                                        $services = (Get-vRAServices -orgId $orgId)
                                        Foreach ($serviceRole in $serviceRoles) {
                                            $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1]
                                            Remove-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole
                                        }
                                    }
                                    if ($orgRole -eq $null) {
                                        $orgRole = "none"
                                    }
                                    if ($serviceRoles -eq $null) {
                                        $serviceRole = "none"
                                    } else {
                                        $serviceRole = $serviceRoles -join ', '
                                    }
                                    if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.organizationRoles.name -eq $null -and $_.serviceRoles.serviceRoles.name -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null}) {
                                        Write-Output "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: SUCCESSFUL"
                                    } else {
                                        Write-Warning "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to find user email ($email) in Workspace ONE Access for vRealize Automation, check email variable: PRE_VALIDATION_FAILED"
                                }
                            } elseif (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email -and $_.organizationRoles.name -ne $null -or $_.serviceRoles.serviceDefinitionId -ne $null}) {
                                if ($objectCheck = Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.user.email -eq $email }) {
                                    if ($orgRole = ($objectCheck.organizationRoles.name)) {
                                        Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole $orgRole
                                    }
                                    if ($serviceRoles = ($objectCheck.serviceRoles.serviceRoles.name)) {
                                        $services = (Get-vRAServices -orgId $orgId)
                                        Foreach ($serviceRole in $serviceRoles) {
                                            $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1]
                                            Remove-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole
                                        }
                                    }
                                    if ($orgRole -eq $null) {
                                        $orgRole = "none"
                                    }
                                    if ($serviceRoles -eq $null) {
                                        $serviceRole = "none"
                                    } else {
                                        $serviceRole = $serviceRoles -join ', '
                                    }
                                    if (Get-vRAUser -orgId $orgId -email $email | Where-Object { $_.organizationRoles.name -eq $null -and $_.serviceRoles.serviceRoles.name -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null}) {
                                        Write-Output "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: SUCCESSFUL"
                                    } else {
                                        Write-Warning "Removing user email ($email) from organization role ($orgRole) and service roles(s) ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to find user email ($email) in Workspace ONE Access for vRealize Automation, check email variable: PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing user email ($email) from organization role and service roles(s) in vRealize Automation, no roles assigned: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRAUser

Function Add-vRAGroup {
    <#
        .SYNOPSIS
        Adds a group in an organization.

        .DESCRIPTION
        The Add-vRAGroup cmdlet adds a group in vRealize Automation. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Adds the group to an organization role and a service role

        .EXAMPLE
        Add-vRAGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -displayName gg-vra-org-owners@rainpole.io -orgRole org_owner
        This example adds a group to vRealize Automation by groupId and orgId along with the required orgRole.

        .EXAMPLE
        Add-vRAGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -displayName gg-vra-cloud-assembly-admins@rainpole.io -orgRole org_member -serviceRole automationservice:cloud_admin
        This example adds a group to vRealize Automation by groupId and orgId along with the required orgRole and serviceRole.

        Note: This cmdlet currently only supports a single serviceRole.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole,
        [Parameter (Mandatory = $false)] [ValidateSet('automationservice:cloud_admin', 'automationservice:user', 'automationservice:viewer', 'catalog:admin', 'catalog:user', 'catalog:viewer', 'CodeStream:administrator', 'CodeStream:developer', 'CodeStream:executor', 'CodeStream:user', 'CodeStream:viewer', 'migration:admin', 'migration:viewer', 'orchestration:admin', 'orchestration:designer', 'orchestration:viewer', 'saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1]
                            if (Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.displayName -eq $displayName }) {
                                $groupId = (Get-vRAGroup -orgId $orgId -displayName $displayName).id 
                                if ($PsBoundParameters.ContainsKey("orgRole") -and ($PsBoundParameters.ContainsKey("serviceRole"))) {
                                    $services = (Get-vRAServices -orgId $orgId)
                                    $serviceDefinitionId = (($services.serviceRoles | Where-Object {$_.name -eq $serviceRole -and $_.displayName -ne $serviceRole}).serviceDefinitionLink -Split("external/"))[-1]
                                    if (!(Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId})) {
                                        New-vRAGroup -groupId $groupId -orgId $orgId -orgRole $orgRole -serviceRole $serviceRole -serviceDefinitionId $serviceDefinitionId | Out-Null
                                        if (Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $serviceRole -and $_.serviceRoles.serviceDefinitionId -eq $serviceDefinitionId}) {
                                            Write-Output "Assigning group ($displayName) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: SUCCESSFUL"
                                        }
                                        else {
                                            Write-Error "Assigning group ($displayName) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation: POST_VALIDATION_FAILED"
                                        }
                                    }
                                    else {
                                        Write-Warning "Assigning group ($displayName) the organization role ($orgRole) and service role ($serviceRole) in vRealize Automation, already exists: SKIPPED"
                                    }
                                }
                                elseif (!$PsBoundParameters.ContainsKey("serviceRole")) {
                                    if (!(Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null})) {
                                        New-vRAGroup -groupId $groupId -orgId $orgId -orgRole $orgRole | Out-Null
                                        if (Get-vRAGroupRoles -groupId $groupId -orgId $orgId | Where-Object { $_.organizationRoles.name -eq $orgRole -and $_.serviceRoles.serviceRoleNames -eq $null -and $_.serviceRoles.serviceDefinitionId -eq $null}) {
                                            Write-Output "Assigning group ($displayName) the organization role ($orgRole) in vRealize Automation: SUCCESSFUL"
                                        }
                                        else {
                                            Write-Error "Assigning group ($displayName) the organization role ($orgRole) in vRealize Automation: POST_VALIDATION_FAILED"
                                        }
                                    }
                                    else {
                                        Write-Warning "Assigning group ($displayName) the organization role ($orgRole) in vRealize Automation, already exists: SKIPPED"
                                    }
                                }
                            }
                            else {
                                Write-Error "Unable to find group ($displayName) in Workspace ONE Access for vRealize Automation, check group synchronization or displayName: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vRAGroup

Function Undo-vRAGroup {
    <#
        .SYNOPSIS
        Removes a group in an organization.

        .DESCRIPTION
        The Undo-vRAGroup cmdlet removes a group in vRealize Automation. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Removes the group from an organization role and all service roles

        .EXAMPLE
        Undo-vRAGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vraUser configadmin -vraPass VMw@re1! -displayName gg-vra-cloud-assembly-admins@rainpole.io
        This example removes a group from vRealize Automation by displayName.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            $orgId = (Get-vRAOrganizationId).Split("orgs/")[-1]
                            if (Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.displayName -eq $displayName }) {
                                $groupId = (Get-vRAGroup -orgId $orgId -displayName $displayName).id 
                                if (Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.organizationRoles.name -ne $null -or $_.serviceRoles.serviceDefinitionId -ne $null}) {
                                    Remove-vRAGroupRoles -groupId $groupId -orgId $orgId | Out-Null
                                    if (!(Get-vRAGroup -orgId $orgId -displayName $displayName | Where-Object { $_.organizationRoles.name -ne $null -and $_.serviceRoles.serviceRoleNames -ne $null -and $_.serviceRoles.serviceDefinitionId -ne $null})) {
                                        Write-Output "Removing group ($displayName) from vRealize Automation: SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing group ($displayName) from vRealize Automation:: POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing group ($displayName) from vRealize Automation:, does not exist: SKIPPED"
                                }
                            } else {
                                Write-Error "Unable to find group ($displayName) in Workspace ONE Access for vRealize Automation, check group synchronization or displayName: PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRAGroup

Function New-vRAvROPSIntegrationItem {
    <#
        .SYNOPSIS
        Creates new vRealize Operations Manager integration in vRealize Automation

        .DESCRIPTION
        The New-vRAvROPSIntegrationItem cmdlet creates an integration in vRealize Automation. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Creates vRealize Operations Manager integration in vRealize Automation

        .EXAMPLE
        New-vRAvROPSIntegrationItem -server "sfo-vcf01.sfo.rainpole.io" -user "administrator@vsphere.local" -pass "VMw@re1!" -vraUser "configadmin@rainpole.io" -vraPass "VMw@re1!" -vropsIntegrationUser "svc-vrops-vra@sfo.rainpole.io@vIDMAuthSource" -vropsIntegrationPass "VMw@re1!" -vropsIntegrationName "vRealize Operations Manager"
        This example creates vRealize Operations Manager integration with name "vRealize Operations Manager" in vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vropsIntegrationUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vropsIntegrationPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vropsIntegrationName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                                if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                                    if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                                        $response = Add-vRAIntegrationItem -integrationType "vrops" -integrationName $vropsIntegrationName -integrationUser $vropsIntegrationUser -integrationPassword $vropsIntegrationPass #| Out-Null
                                        if ($response.status -eq "FINISHED") {
                                            if (Get-vRAIntegrationDetail -integrationType "vrops"  -integrationName $vropsIntegrationName -getIntegrationID) {
                                                Write-Output "Creating vRealize Operations Manager integration with name '$vropsIntegrationName' in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): SUCCESSFUL"
                                            } else {
                                                Write-Error "Creating vRealize Operations Manager integration with name '$vropsIntegrationName' in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): POST_VALIDATION_FAILED" 
                                            }
                                        } else {
                                            Write-Error "Creating vRealize Operations Manager integration with name '$vropsIntegrationName' in vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)) failed with '$($response.message)': FAILED"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vRAvROPSIntegrationItem

Function Undo-vRAvROPsIntegrationItem {
    <#
        .SYNOPSIS
        Deletes vRealize Operations Manager from vRealize Automation

        .DESCRIPTION
        The Undo-vRAvROPsIntegrationItem cmdlet deletes vRealize Operations Manager integration from vRealize Automation.The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that vRealize Automation has been deployed in VMware Cloud Foundation aware mode and retrives its details
        - Validates that network connectivity and authentication is possible to vRealize Automation
        - Validates that vRealize Operations Manager has been deployed in VCF-aware mode and retrieves its details
        - Validates that network connectivity and authentication is possible to vRealize Operations Manager
        - Deletes vRealize Operations Manager integration from vRealize Automation

        .EXAMPLE
        Undo-vRAvROPsIntegrationItem -server "sfo-vcf01.sfo.rainpole.io" -user "administrator@vsphere.local" -pass "VMw@re1!" -vraUser "svc-vra-vrops@sfo.rainpole.io@vIDMAuthSource" -vraPass "VMw@re1!" -vropsIntegrationName "vRealize Operations Manager"
        This example deletes vRealize Operations Manager in vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass, 
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vraPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vropsIntegrationName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVraDetails = Get-vRAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRAConnection -server $vcfVraDetails.loadBalancerFqdn) {
                        if (Test-vRAAuthentication -server $vcfVraDetails.loadBalancerFqdn -user $vraUser -pass $vraPass) {
                            if (($vcfVropsDetails = Get-vROPsServerDetail -fqdn $server -username $user -password $pass)) {
                                if (Test-vROPSConnection -server $vcfVropsDetails.loadBalancerFqdn) {
                                    if (Test-vROPSAuthentication -server $vcfVropsDetails.loadBalancerFqdn -user $vcfVropsDetails.adminUser -pass $vcfVropsDetails.adminPass) {
                                        if ($null -eq (Get-vRAIntegrationDetail -integrationType "vrops"  -integrationName $vropsIntegrationName -getIntegrationID ) ) {
                                            Write-Warning "vRealize Operations Manager Integration with name '$vropsIntegrationName' not found...: SKIPPED" 
                                            break
                                        }
                                        Remove-vRAIntegrationItem -integrationType vrops -integrationId (Get-vRAIntegrationDetail -integrationType vrops -integrationName $vropsIntegrationName -getIntegrationID) | Out-Null
                                    }
                                    if ($null -eq (Get-vRAIntegrationDetail -integrationType "vrops"  -integrationName $vropsIntegrationName -getIntegrationID) ) {
                                        Write-Output "Removing vRealize Operations Manager Integration with name '$vropsIntegrationName' from vRealize Automation ($($vcfVraDetails.loadBalancerFqdn)): SUCCESSFUL"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vRAvROPsIntegrationItem

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region S H A R E D P O W E R V A L I D A T E D S O L U T I O N S F U N C T I O N S ###########

Function Add-vCenterGlobalPermission {
    <#
        .SYNOPSIS
        Adds a Global Permission to a user or group
        
        .DESCRIPTION
        The Add-vCenterGlobalPermission cmdlets assigns the vCenter Server Global Permission to the user or group provided.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the bind credentials are valid
        - Validates that the domain is present in vCenter Server as an Identity Provider
        - Validates the user or group exists in Active Directory
        - Assigns the user or group to the vCenter Global Permission

        If -localDomain is selected, then AD authentication check is skipped and user/group is checked for in the local directory

        .EXAMPLE
        Add-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-vc-admins -role Admin -propagate true -type group
        This example adds the group gg-vc-admins from domain sfo.rainpole.io the Administrator Global Permission

        .EXAMPLE
        Add-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -domainBindUser administrator -domainBindPass VMw@re1! -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -role "NSX-T Data Center to vSphere Integration" -propagate true -type user -localdomain
        This example adds the "NSX-T Data Center to vSphere Integration" Global Permission to the user svc-sfo-m01-nsx01-sfo-m01-vc01 from domain vsphere.local
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role,
        [Parameter (Mandatory = $true)] [ValidateSet("true", "false")] [String]$propagate,
        [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type,
        [Parameter (Mandatory = $false)] [Switch]$localDomain = $false
    )

    Try {
        if (!$localDomain){
            $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue
            if (!($checkAdAuthentication[1] -match "Authentication Successful")) {
                Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDTION_FAILED"
                Return
            }
        }

        $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force
        $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass)
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            Connect-vSphereMobServer -server $vcfVcenterDetails.fqdn -username $vcfVcenterDetails.ssoAdmin -password $vcfVcenterDetails.ssoAdminPass | Out-Null
                            $roleAssigned = (Get-GlobalPermission | Where-Object {$_.Principal -match $principal})
                            if (!($roleAssigned | Where-Object {$_.Role -eq $role})) {
                                if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        if (!(Get-IdentitySource | Where-Object { $_.Name -eq $domain })) {
                                            Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain)"
                                        } else {
                                            if ($type -eq "group") {
                                                if (!$localDomain) {
                                                    $objectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal })
                                                } else {
                                                    $principal = $domain.ToUpper() + "\" + $principal
                                                    $objectCheck = (Get-VIAccount -Group -Domain $domain -server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $principal })
                                                }
                                            } elseif ($type -eq "user") {
                                                if (!$localDomain){
                                                    $objectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal })
                                                    $principal = $domain.ToUpper() + "\" + $principal
                                                } else {
                                                    $principal = $domain.ToUpper() + "\" + $principal
                                                    $objectCheck = (Get-VIAccount -User -Domain $domain -server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $principal })
                                                }
                                            }
                                            if ($objectCheck) {
                                                $roleId = (Get-VIRole -Name $role -Server $vcfVcenterDetails.fqdn | Select-Object -ExpandProperty Id)
                                                Add-GlobalPermission -principal $principal -roleId $roleId -propagate $propagate -type $type | Out-Null
                                                $roleAssigned = (Get-GlobalPermission | Where-Object {$_.Principal -match $principal.Split("\")[-1]})
                                                if ($roleAssigned | Where-Object {$_.Role -eq $role}) {
                                                    Write-Output "Adding Global Permission with Role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Adding Global Permission with Role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                if ($localDomain) {
                                                    Write-Error "Unable to find $type ($principal) in Local Domain, create and retry: PRE_VALIDATION_FAILED"
                                                } else {
                                                    Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED"
                                                }
                                            }
                                        }
                                    }
                                    Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue
                                }
                            } else {
                                Write-Warning "Adding Global Permission with Role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal), already applied: SKIPPED"
                            }
                            Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -Force -WarningAction SilentlyContinue
                            Disconnect-vSphereMobServer
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vCenterGlobalPermission

Function Undo-vCenterGlobalPermission {
    <#
        .SYNOPSIS
        Removes a Global Permission to a user or group
        
        .DESCRIPTION
        The Undo-vCenterGlobalPermission cmdlets removes the vCenter Server Global Permission for the user or group provided.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Removes the user or group from the vCenter Global Permission

        If -localDomain is selected, then AD authentication check is skipped and user/group is checked for in the local directory

        .EXAMPLE
        Undo-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -principal gg-vc-admins -type group
        This example remove the group gg-vc-admins from the vCenter Global Permission

        .EXAMPLE
        Undo-vCenterGlobalPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -principal testUser -type user -localdomain
        This example remove the group testUser from the vCenter Global Permission
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type,
        [Parameter (Mandatory = $false)] [Switch]$localDomain = $false
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            Connect-vSphereMobServer -server $vcfVcenterDetails.fqdn -username $vcfVcenterDetails.ssoAdmin -password $vcfVcenterDetails.ssoAdminPass | Out-Null
                            if (Get-GlobalPermission | Where-Object {$_.Principal -match $principal}) {
                                if ($PsBoundParameters.ContainsKey("localDomain")) {
                                    Remove-GlobalPermission -principal ($domain.ToUpper()+"\"+$principal) -type $type | Out-Null
                                } else {
                                    Remove-GlobalPermission -principal $principal -type $type | Out-Null
                                }
                                if (!(Get-GlobalPermission | Where-Object {$_.Principal -match $principal})) {
                                    Write-Output "Removing Global Permission in vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing Global Permission in vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing Global Permission in vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal), already removed: SKIPPED"
                            }
                            Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -Force -WarningAction SilentlyContinue
                            Disconnect-vSphereMobServer
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vCenterGlobalPermission

Function Set-vCenterPermission {
    <#
        .SYNOPSIS
        Sets Permission for user or group in the vCenter Server. This overrides any existing Global Permissions for the user or group in the vCenter Server.

        .DESCRIPTION
        The Set-vCenterPermission cmdlet assigns the Permission/Role to existing user or group in the vCenter Server.
        The user/group must exist in the domain prior to running this cmdlet.

        .EXAMPLE
        Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain vsphere.local -workloadDomain sfo-m01 -principal svc-sfo-w01-nsx01-sfo-w01-vc01 -role "NoAccess"
        This example assigns NoAccess role to the user svc-sfo-w01-nsx01-sfo-w01-vc01 from domain vsphere.local.

        .EXAMPLE
        Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo -workloadDomain sfo-m01 -principal gg-vc-admins -role "Admin"
        This example assigns the Admin role to the group gg-vc-admins from domain SFO.

        .EXAMPLE
        Set-vCenterPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo -workloadDomain sfo-m01 -principal sfo-vra-vsphere -role "NoAccess" -folderName "local" -folderType "Datastore"
        This example assigns the NoAccess role to the user svc-vra-vsphere from domain SFO on the datastore folder named "local".
        Note: The functionality is limited to non-nested folders in the default datacenter.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$workloadDomain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role,
        [Parameter (ParameterSetName = 'Folders', Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$folderName,
        [Parameter (ParameterSetName = 'Folders', Mandatory = $false)] [ValidateSet("Datacenter", "Datastore", "HostAndCluster", "Network", "VM")] [String]$folderType
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $workloadDomain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $workloadDomain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        if (Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail) {
                                            $principal = $domain.ToUpper() + "\" + $principal
                                            if ($PsBoundParameters.ContainsKey("folderName") -and ($PsBoundParameters.ContainsKey("folderType"))) {
                                                if (($objectCheck = Get-Folder -Name $folderName -Type $folderType -ErrorAction Ignore | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}).Name) {
                                                    if ($objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder -Name $folderName -Type $folderType | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"})) {
                                                        if (!($objectCheck.Role -eq $role)) {
                                                            New-VIPermission -Server $vcfVcenterDetails.fqdn -Role $role -Principal $principal -Entity (Get-Folder -Name $folderName -Type $folderType | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) | Out-Null
                                                            $objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder -Name $folderName -Type $folderType | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"})
                                                            if ($objectCheck.Role -eq $role) {
                                                                Write-Output "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName): SUCCESSFUL"
                                                            } else {
                                                                Write-Error "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName): POST_VALIDATION_FAILED"
                                                            }
                                                        } else {
                                                            Write-Warning "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName), already assigned: SKIPPED"
                                                        }
                                                    } else {
                                                        Write-Error "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal) on $($folderType.ToLower()) folder ($folderName), check folderName and folderType: PRE_VALIDATION_FAILED"
                                                    }
                                                } else {
                                                    Write-Error "Unable to find $($folderType.ToLower()) folder ($folderName) in vCenter Server ($($vcfVcenterDetails.vmName)): PRE_VAILIDATION_FAILED"
                                                }
                                            } else {
                                                if ($folderName -or $folderType) {
                                                Write-Error "Only one of -folderName or -folderType parameters provided: PRE_VALIDATATION_FAILED"
                                                } else {
                                                    if ($objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}))  {
                                                        if (!($objectCheck.Role -eq $role)) {
                                                            New-VIPermission -Server $vcfVcenterDetails.fqdn -Role $role -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"}) | Out-Null
                                                            $objectCheck = Get-VIPermission -Server $vcfVcenterDetails.fqdn -Principal $principal -Entity (Get-Folder "Datacenters" -Type Datacenter | Where-Object {$_.Uid -like "*"+$vcfVcenterDetails.fqdn+"*"})
                                                            if ($objectCheck.Role -eq $role) {
                                                                Write-Output "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal): SUCCESSFUL"
                                                            } else {
                                                                Write-Error "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal): POST_VALIDATION_FAILED"
                                                            }
                                                        } else {
                                                            Write-Warning "Assigning role ($role) in vCenter Server ($($vcfVcenterDetails.vmName)) to ($principal), already assigned: SKIPPED"
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            Write-Error "Unable to find ($principal) in vCenter Server ($($vcfVcenterDetails.vmName)): PRE_VAILIDATION_FAILED"
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vCenterPermission

Function Add-SsoPermission {
    <#
        .SYNOPSIS
        Assign vCenter Single Sign-On Group to user/group

        .DESCRIPTION
        The Add-SsoPermission cmdlet assigns the vCenter Single Sign-On Role to the user or group provided. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the bind credetials are valid
        - Validates that the domain is present in vCenter Server as an Identity Provider
        - Validates the user or group exists in Active Directory
        - Assigns the user or group to the vCenter Single Sign-On Role

        .EXAMPLE
        Add-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain sfo.rainpole.io -domainBindUser svc-vsphere-ad -domainBindPass VMw@re1! -principal gg-sso-admins -ssoGroup "Administrators" -type group -source external
        This example adds the group gg-sso-admins from domain sfo.rainpole.io to the Administrators vCenter Single Sign-On Group

        .EXAMPLE
        Add-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain vsphere.local -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -ssoGroup "License.Administrators" -type user -source local
        This example adds the user svc-sfo-m01-nsx01-sfo-m01-vc01 from domain vspherel.local to the License.Administrators vCenter Single Sign-On Group
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domainBindUser,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domainBindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoGroup,
        [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type,
        [Parameter (Mandatory = $true)] [ValidateSet("local", "external")] [String]$source
    )

    Try {
        if ($source -eq "external") {
            $checkAdAuthentication = Test-ADAuthentication -user $domainBindUser -pass $domainBindPass -server $domain -domain $domain -ErrorAction SilentlyContinue
            if ($checkAdAuthentication[1] -match "Authentication Successful") {
                $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force
                $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass)
                if (Test-VCFConnection -server $server) {
                    if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                        if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) {
                            if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) {
                                if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                                    if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                        if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) {
                                        if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) {
                                                if ($type -eq "group") {
                                                    $adObjectCheck = (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal })
                                                    if ($adObjectCheck) {
                                                        if (!(Get-SsoGroup -Group $targetGroup -Name $principal)) {
                                                            $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                            $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                            if (Get-SsoGroup -Group $targetGroup -Name $principal) {
                                                                Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL"
                                                            } else {  Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                            }
                                                        } else { 
                                                            Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED"
                                                        }
                                                    } else { 
                                                        Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED"
                                                    }
                                                } elseif ($type -eq "user") {
                                                    $adObjectCheck = (Get-ADUser -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal })
                                                    if ($adObjectCheck) {
                                                        if (!(Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal})) {
                                                            $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                            $ldapUser | Add-UserToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                            if (Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal}) {
                                                                Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL"
                                                            }
                                                            else { Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                            }
                                                        } else {
                                                            Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED"
                                                        }
                                                    } else { 
                                                        Write-Error "Unable to find $type ($principal) in Active Directory Domain ($domain), create and retry: PRE_VALIDATION_FAILED"
                                                    }
                                                }
                                            } else {
                                                Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED"
                                        }
                                        Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn
                                    }
                                }
                            }
                        } else {
                            Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                        }
                    }
                }
            } else {
                Write-Error "Unable to authenticate to Active Directory with user ($domainBindUser) and password ($domainBindPass), check details: PRE_VALIDATION_FAILED"
            }
        } elseif ($source -eq "local") {
            if (Test-VCFConnection -server $server) {
                if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) {
                        if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) {
                                    if (Get-IdentitySource | Where-Object { $_.Name -eq $domain }) {
                                        if ($type -eq "group") {
                                            if (!(Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail)) {
                                                $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                $ldapGroup | Add-GroupToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                if (Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail) {
                                                    Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Assigning SSO On Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain).already exists: SKIPPED"
                                            }
                                        } elseif ($type -eq "user") {
                                            if (!(Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail | Where-Object {$_.Name -eq $principal})) {
                                                $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                $ldapUser | Add-UserToSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                if (Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail| Where-Object {$_.Name -eq $principal}) {
                                                    Write-Output "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                Write-Warning "Assigning SSO Group ($ssoGroup) in vCenter Server ($($vcfVcenterDetails.vmName)) to $type ($principal) for domain ($domain), already exists: SKIPPED"
                                            }
                                        }
                                    } else {
                                        Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED"
                                }
                                Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn
                            }
                        }
                    }
                }   
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-SsoPermission

Function Undo-SsoPermission {
    <#
        .SYNOPSIS
        Remove user/group from vCenter Single Sign-On Group

        .DESCRIPTION
        The Undo-SsoPermission cmdlet removes the user or group provided from vCenter Single Sign-On Role. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the domain is present in vCenter Server as an Identity Provider
        - Removes the user or group from the vCenter Single Sign-On Role

        .EXAMPLE
        Undo-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain sfo.rainpole.io -principal gg-sso-admins -ssoGroup "Administrators" -type group -source external
        This example removes the group gg-sso-admins in domain sfo.rainpole.io from the Administrators vCenter Single Sign-On Group

        .EXAMPLE
        Undo-SsoPermission -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -sddcDomain sfo-m01 -domain vsphere.local -principal svc-sfo-m01-nsx01-sfo-m01-vc01 -ssoGroup "LicenseService.Administrators" -type user -source local
        This example removes the user svc-sfo-m01-nsx01-sfo-m01-vc01 in domain vspherel.local from the LicenseService.Administrators vCenter Single Sign-On Group
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcDomain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoGroup,
        [Parameter (Mandatory = $true)] [ValidateSet("group", "user")] [String]$type,
        [Parameter (Mandatory = $true)] [ValidateSet("local", "external")] [String]$source
    )

    Try {
        if ($source -eq "external") {
            if (Test-VCFConnection -server $server) {
                if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                    if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $sddcDomain }) {
                        if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) {
                            if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                                if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                    if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) {
                                        if (Get-IdentitySource -Server $ssoConnectionDetail | Where-Object { $_.Name -eq $domain }) {
                                            if ($type -eq "group") {
                                                if (Get-SsoGroup -Group $targetGroup -Name $principal) {
                                                    $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                    $ldapGroup | Remove-GroupFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                    if (!(Get-SsoGroup -Group $targetGroup -Name $principal)) {
                                                        Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL"
                                                    } else {
                                                        Write-Error "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                    }
                                                } else { 
                                                    Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already removed: SKIPPED"
                                                }
                                            } elseif ($type -eq "user") {
                                                if (Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal}) {
                                                    $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                    $ldapUser | Remove-UserFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                    if (!(Get-SsoPersonUser -Group $targetGroup | Where-Object {$_.Name -eq $principal})) {
                                                        Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL"
                                                    } else {
                                                        Write-Error "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                    }
                                                } else {
                                                    Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already exists: SKIPPED"
                                                }
                                            }
                                        } else {
                                            Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED"
                                    }
                                    Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn
                                }
                            }
                        }
                    } else {
                        Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                    }
                }
            }
        } elseif ($source -eq "local") {
            if (Test-VCFConnection -server $server) {
                if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $sddcDomain)) {
                        if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if ($targetGroup = Get-SsoGroup -Domain vsphere.local -Name $ssoGroup -Server $ssoConnectionDetail) {
                                    if (Get-IdentitySource | Where-Object { $_.Name -eq $domain }) {
                                        if ($type -eq "group") {
                                            if (Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail) {
                                                $ldapGroup = Get-SsoGroup -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                $ldapGroup | Remove-GroupFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                if (!(Get-SsoGroup -Group $targetGroup -Name $principal -Server $ssoConnectionDetail)) {
                                                    Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Removing SSO On Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already removed: SKIPPED"
                                            }
                                        } elseif ($type -eq "user") {
                                            if (Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail | Where-Object {$_.Name -eq $principal}) {
                                                $ldapUser = Get-SsoPersonUser -Domain $domain -Name $principal -Server $ssoConnectionDetail
                                                $ldapUser | Remove-UserFromSsoGroup -TargetGroup $targetGroup -ErrorAction SilentlyContinue
                                                if (!(Get-SsoPersonUser -Group $targetGroup -Server $ssoConnectionDetail| Where-Object {$_.Name -eq $principal})) {
                                                    Write-Output "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): SUCCESSFUL"
                                                } else {
                                                    Write-Error "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain): POST_VALIDATION_FAILED"
                                                }
                                            } else {
                                                Write-Warning "Removing SSO Group ($ssoGroup) from vCenter Server ($($vcfVcenterDetails.vmName)) for $type ($principal) for domain ($domain), already removed: SKIPPED"
                                            }
                                        }
                                    } else {
                                        Write-Error "Unable to find Identity Source in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($domain): PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "Unable to find SSO Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ssoGroup): PRE_VALIDATION_FAILED"
                                }
                                Disconnect-SsoAdminServer -Server $vcfVcenterDetails.fqdn
                            }
                        }
                    }
                }   
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SsoPermission

Function Add-SsoUser {
    <#
        .SYNOPSIS
        Assign vCenter Single Sign-On Group to user/group

        .DESCRIPTION
        The Add-SsoUser cmdlet adds a user to the vCenter Single Sign-On domain The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to Management Domain vCenter Server
        - Validates that the user does not exist
        - Adds the user to the vCenter Single Sign-On domain

        .EXAMPLE
        Add-SsoUser -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -ssoUser svc-vrslcm-vsphere-sfo-m01-vc01 -ssoPass VMw@re1!VMw@re1!
        This example adds the user svc-vrslcm-vsphere-sfo-m01-vc01 to the vCenter Single Sign-On domain vsphere.local
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-SSOConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-SSOAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (!(Get-SsoPersonUser -Domain vsphere.local -Name $ssoUser -Server $ssoConnectionDetail)) {
                                New-SsoPersonUser -UserName $ssoUser -Password $ssoPass -Server $ssoConnectionDetail | Out-Null
                                if (Get-SsoPersonUser -Domain vsphere.local -Name $ssoUser -Server $ssoConnectionDetail) {
                                    Write-Output "Adding New Single Sign-On User to vCenter Server ($($vcfVcenterDetails.vmName)) named ($ssoUser): SUCCESSFUL"
                                } else {
                                    Write-Error "Adding New Single Sign-On User to vCenter Server ($($vcfVcenterDetails.vmName)) named ($ssoUser): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Adding New Single Sign-On User to vCenter Server ($($vcfVcenterDetails.vmName)) named ($ssoUser), already exists: SKIPPED"
                            }
                            Disconnect-SsoAdminServer $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue
                        }
                    }
                }                             
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-SsoUser

Function Add-vSphereRole {
    <#
        .SYNOPSIS
        Add a vSphere role

        .DESCRIPTION
        The Add-vSphereRole cmdlet creates a role in vCenter Server. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Verifies if the role already exists and if not creates it
        - Assigns permissions to the role based on the template file provided

        .EXAMPLE
        Add-vSphereRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -roleName "NSX-T Data Center to vSphere Integration" -template .\vSphereRoles\nsx-vsphere-integration.role
        This example adds the "NSX-T Data Center to vSphere Integration" role in the management domain vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$template
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("template")) {
            $template = Get-ExternalFileName -title "Select the vSphere role template (.role)" -fileType "role" -location "C:\Program Files\WindowsPowerShell\Modules\PowerValidatedSolutions\vSphereRoles"
        } else {
            if (!(Test-Path -Path $template)) {
                Write-Error  "vSphere Role Template '$template' File Not Found"
                Break
            }
        }

        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $roleContent = Get-Content -Path $template
                            if (!(Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName })) {
                                New-VIRole -Name $roleName -Server $vcfVcenterDetails.fqdn | Out-Null
                                if (Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName }) {
                                    Foreach ($privilege in $roleContent) {
                                        if (-not ($privilege -eq $null -or $privilege -eq "")) {
                                            Set-VIRole -Server $vcfVcenterDetails.fqdn -Role $roleName -AddPrivilege (Get-VIPrivilege -ID $privilege) -Confirm:$False -ErrorAction SilentlyContinue | Out-Null
                                        }
                                    }
                                    Write-Output "Creating a new role in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): SUCCESSFUL"
                                } else {
                                    Write-Error "Creating a new role in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Creating a new role in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName), already exists: SKIPPED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-vSphereRole

Function Undo-vSphereRole {
    <#
        .SYNOPSIS
        Remove a vSphere role

        .DESCRIPTION
        The Undo-vSphereRole cmdlet removes a role from vCenter Server. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Verifies if the role exists and if it does removes it

        .EXAMPLE
        Undo-vSphereRole -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -roleName "NSX-T Data Center to vSphere Integration"
        This example removes the "NSX-T Data Center to vSphere Integration" role from the management domain vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName }) {
                                Remove-VIRole -Role $roleName -Server $vcfVcenterDetails.fqdn -Force -Confirm:$false | Out-Null
                                if (!(Get-VIRole -Server $vcfVcenterDetails.fqdn | Where-Object { $_.Name -eq $roleName })) {
                                    Write-Output "Removing a role from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing a role from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing a role from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($roleName), already exists: SKIPPED"
                            }
                            Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vSphereRole

Function Add-VMFolder {
    <#
        .SYNOPSIS
        Create a VM Folder

        .DESCRIPTION
        The Add-VMFolder cmdlet creates a VM and Template folder. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that the Workload Domain exists in the SDDC Manager inventory
        - Retrives the details of the vCenter Server for the Workload Domain provided
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the VM and Template folder is not present in the vCenter Server inventory
        - Creates VM and Template folder the folder in the vCenter Server inventory

        .EXAMPLE
        Add-VMFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myFolder"
        This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$folderName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                $datacenter = (Get-Datacenter -Cluster $cluster -Server $vcfVcenterDetails.fqdn).Name
                                if (Get-Folder -Name $folderName -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore) {
                                    Write-Warning "Adding VM and Template Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName), already exists: SKIPPED"
                                } else {
                                    (Get-View -Server $vcfVcenterDetails.fqdn (Get-View -Server $vcfVcenterDetails.fqdn -viewtype datacenter -filter @{"name" = [String]$datacenter }).vmfolder).CreateFolder($folderName) | Out-Null
                                    if ((Get-Folder -Name $folderName -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore)) {
                                        Write-Output  "Adding VM and Template Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding VM and Template Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName): POST_VALIDATION_FAILED"
                                    }
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-VMFolder

Function Add-StorageFolder {
    <#
        .SYNOPSIS
        Create a Storage Folder

        .DESCRIPTION
        The Add-StorageFolder cmdlet creates a Storage folder. The cmdlet connects to SDDC Manager using the -server,
        -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that the Workload Domain exists in the SDDC Manager inventory
        - Retrives the details of the vCenter Server for the Workload Domain provided
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the Storage folder is not present in the vCenter Server inventory
        - Creates the Storage folder in the vCenter Server inventory

        .EXAMPLE
        Add-StorageFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myStorageFolder"
        This example shows how to create the folder myStorageFolder within the VMware Cloud Foundation domain sfo-m01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$folderName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                $datacenter = (Get-Datacenter -Cluster $cluster -Server $vcfVcenterDetails.fqdn).Name
                                if (Get-Folder -Name $folderName -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore) {
                                    Write-Warning "Adding Storage Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName), already exists: SKIPPED"
                                } else {
                                    (Get-View -Server $vcfVcenterDetails.fqdn (Get-View -Server $vcfVcenterDetails.fqdn -viewtype datacenter -filter @{"name" = [String]$datacenter }).datastorefolder).CreateFolder($folderName) | Out-Null
                                    if ((Get-Folder -Name $folderName -Server $vcfVcenterDetails.fqdn -WarningAction SilentlyContinue -ErrorAction Ignore)) {
                                        Write-Output  "Adding Storage Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding Storage Folder to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($folderName): POST_VALIDATION_FAILED"
                                    }
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-StorageFolder

Function Undo-VMFolder {
    <#
        .SYNOPSIS
        Remove a VM Folder

        .DESCRIPTION
        The Undo-VMFolder cmdlet removes a VM and Template folder. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that the Workload Domain exists in the SDDC Manager inventory
        - Retrives the details of the vCenter Server for the Workload Domain provided
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the VM and Template folder is present in the vCenter Server inventory
        - Removes the VM and Template folder from the vCenter Server inventory

        .EXAMPLE
        Undo-VMFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myFolder" -folderType VM
        This example shows how to remove the folder myFolder within the VMware Cloud Foundation domain sfo-m01

        .EXAMPLE
        Undo-VMFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -foldername "myFolder" -folderType Datastore
        This example shows how to remove the storage folder myStorageFolder within the VMware Cloud Foundation domain sfo-m01
        #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$folderName,
        [Parameter (Mandatory = $true)] [ValidateSet("Datacenter", "VM", "Network", "HostAndCluster", "Datastore")] [String]$folderType
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                if (!(Get-Folder -Name $folderName -Type $folderType -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) {
                                    Write-Warning "Removing Folder Type ($folderType) from vCenter Server ($($vcfVcenterDetails.fqdn)) with name ($folderName), folder does not exist: SKIPPED"
                                } else {
                                    Get-Folder -Name $folderName -Type $folderType -Server $vcfVcenterDetails.fqdn | Remove-Folder -Confirm:$false -ErrorAction Ignore
                                    if (!(Get-Folder -Name $folderName -Type $folderType -Server $vcfVcenterDetails.fqdn -ErrorAction Ignore)) {
                                        Write-Output  "Removing Folder Type ($folderType) from vCenter Server ($($vcfVcenterDetails.fqdn)) with name ($folderName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing Folder Type ($folderType) from vCenter Server ($($vcfVcenterDetails.fqdn)) with name ($folderName): POST_VALIDATION_FAILED"
                                    }
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-VMFolder

Function Add-ResourcePool {
    <#
        .SYNOPSIS
        Create a resource pool

        .DESCRIPTION
        The Add-ResourcePool cmdlet creates a resource pool. The cmdlet connects to SDDC Manager using the -server, -user, and -password values
        to retrive the vCenter Server details from the SDDC Manager inventory and then:
        - Connects to the vCenter Server
        - Verifies that the resource pool has not already been created
        - Creates the resource pool

        .EXAMPLE
        Add-ResourcePool -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -resourcePoolName "sfo-w01-cl01-rp-workload"
        This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$resourcePoolName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (!(Get-ResourcePool -Server $vcfVcenterDetails.fqdn | Where-Object {$_.Name -eq $resourcePoolName})) {
                                    New-ResourcePool -Name $resourcePoolName -Location $cluster -Server $vcfVcenterDetails.fqdn | Out-Null
                                    if (Get-ResourcePool -Server $vcfVcenterDetails.fqdn | Where-Object {$_.Name -eq $resourcePoolName}) {
                                        Write-Output "Adding Resource Pool to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($resourcePoolName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding Resource Pool to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($resourcePoolName): FAILED"
                                    }
                                } else {
                                    Write-Warning "Adding Resource Pool to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($resourcePoolName), already exists: SKIPPED"
                                }
                                Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-ResourcePool

Function Undo-ResourcePool {
    <#
        .SYNOPSIS
        Remove a resource pool

        .DESCRIPTION
        The Undo-ResourcePool cmdlet removes a resource pool. The cmdlet connects to SDDC Manager using the -server, -user, and -password values
        to retrive the vCenter Server details from the SDDC Manager inventory and then:
        - Connects to the vCenter Server
        - Verifies that the resource pool exists in the vCenter Server inventory
        - Removes the resource pool

        .EXAMPLE
        Undo-ResourcePool -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -resourcePoolName "sfo-w01-cl01-rp-workload"
        This example shows how to create the folder myFolder within the VMware Cloud Foundation domain sfo-m01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$resourcePoolName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                #$cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (Get-ResourcePool -Server $vcenter.fqdn | Where-Object {$_.Name -eq $resourcePoolName}) {
                                    Remove-ResourcePool -ResourcePool $resourcePoolName -Server $vcenter.fqdn -Confirm:$false | Out-Null
                                    if (!(Get-ResourcePool -Server $vcenter.fqdn | Where-Object {$_.Name -eq $resourcePoolName})) {
                                        Write-Output "Removing Resource Pool from vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing Resource Pool from vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName): FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing Resource Pool from vCenter Server ($($vcenter.fqdn)) named ($resourcePoolName), does not exist: SKIPPED"
                                }
                                Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-ResourcePool

Function Add-AntiAffinityRule {
    <#
        .SYNOPSIS
        Creates a vSphere Anti-Affinity rule

        .DESCRIPTION
        The Add-AntiAffinityRule cmdlet creates a vSphere Anti-Affinity rule. The cmdlet connects to SDDC Manager using
        the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the anti-affinity rule has not already been created in the vCenter Server inventory
        - Creates the anti-affinity rule in the vCenter Server inventory

        .EXAMPLE
        Add-AntiAffinityRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName sfo-m01-anti-affinity-rule-wsa -antiAffinityVMs "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c"
        This example shows how to create a vSphere Anti-Affinity rule in the vCenter Server of the sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server,
        [Parameter (Mandatory = $true)] [String]$user,
        [Parameter (Mandatory = $true)] [String]$pass,
        [Parameter (Mandatory = $true)] [String]$domain,
        [Parameter (Mandatory = $true)] [String]$ruleName,
        [Parameter (Mandatory = $true)] [String]$antiAffinityVMs
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (!(Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) {
                                    $vmNames = $antiAffinityVMs.split(",")
                                    $vms = foreach ($name in $vmNames) { Get-VM -name $name -ErrorAction SilentlyContinue }
                                    New-DrsRule -Cluster $cluster -Name $ruleName -VM $vms -KeepTogether $false -Enabled $true | Out-Null
                                    if ((Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) {
                                        Write-Output "Adding Anti-Affinity Rule to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding Anti-Affinity Rule to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Adding Anti-Affinity Rule to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already exists: SKIPPED" 
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-AntiAffinityRule

Function Undo-AntiAffinityRule {
    <#
        .SYNOPSIS
        Removes a vSphere Anti-Affinity rule

        .DESCRIPTION
        The Undo-AntiAffinityRule cmdlet removes a vSphere Anti-Affinity rule. The cmdlet connects to SDDC Manager using
        the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the anti-affinity rule has not already been removed from the vCenter Server inventory
        - Removes the anti-affinity rule from the vCenter Server inventory

        .EXAMPLE
        Undo-AntiAffinityRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName sfo-m01-anti-affinity-rule-wsa
        This example shows how to create a vSphere Anti-Affinity rule in the vCenter Server of the sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server,
        [Parameter (Mandatory = $true)] [String]$user,
        [Parameter (Mandatory = $true)] [String]$pass,
        [Parameter (Mandatory = $true)] [String]$domain,
        [Parameter (Mandatory = $true)] [String]$ruleName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName}) {
                                    Remove-DrsRule -Rule (Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName}) -Confirm:$false | Out-Null
                                    if (!(Get-Cluster -Name $cluster | Get-DrsRule | Where-Object {$_.Name -eq $ruleName})) {
                                        Write-Output "Removing Anti-Affinity Rule from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing Anti-Affinity Rule from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing Anti-Affinity Rule from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already removed: SKIPPED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-AntiAffinityRule

Function Add-ClusterGroup {
    <#
    .SYNOPSIS
        Creates a vSphere DRS Cluster Group

        .DESCRIPTION
        The Add-ClusterGroup cmdlet creates a vSphere DRS Cluster Group. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that that the vSphere DRS Cluster Group does not already exist in the vCenter Server inventory
        - Creates the vSphere DRS Cluster Group in the vCenter Server inventory

        .EXAMPLE
        Add-ClusterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -drsGroupName "xint-vm-group-wsa" -drsGroupVMs "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c"
        This example shows how to create a vSphere DRS Cluster group in the vCenter Server of the sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server,
        [Parameter (Mandatory = $true)] [String]$user,
        [Parameter (Mandatory = $true)] [String]$pass,
        [Parameter (Mandatory = $true)] [String]$domain,
        [Parameter (Mandatory = $true)] [String]$drsGroupName,
        [Parameter (Mandatory = $true)] [String]$drsGroupVMs
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (!(Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName})) {
                                    $vmNames = $drsGroupVMs.split(",")
                                    $vms = foreach ($name in $vmNames) { Get-VM -name $name -ErrorAction SilentlyContinue }
                                    New-DrsClusterGroup -Cluster $cluster -VM $vms -Name $drsGroupName | Out-Null
                                    if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName}) {
                                        Write-Output "Adding vSphere DRS Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Adding vSphere DRS Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Adding vSphere DRS Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), already exists: SKIPPED"
                                    
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-ClusterGroup

Function Undo-ClusterGroup {
    <#
        .SYNOPSIS
        Removes a vSphere DRS Cluster Group

        .DESCRIPTION
        The Undo-ClusterGroup cmdlet removes the vSphere DRS Cluster Group. The cmdlet connects to SDDC Manager using the
        -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that that the vSphere DRS Cluster Group exist in the vCenter Server inventory
        - Removes the vSphere DRS Cluster Group in the vCenter Server inventory

        .EXAMPLE
        Undo-ClusterGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -drsGroupName "sfo-m01-vm-group-wsa"
        This example shows how to delete a vSphere DRS Cluster group from the vCenter Server of the sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server,
        [Parameter (Mandatory = $true)] [String]$user,
        [Parameter (Mandatory = $true)] [String]$pass,
        [Parameter (Mandatory = $true)] [String]$domain,
        [Parameter (Mandatory = $true)] [String]$drsGroupName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (!(Get-DrsVmToVmGroup -cluster $cluster | Where-Object {$_.DependsOnVmGroup -eq $drsGroupName})) {
                                    if ((Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName})) {
                                        Remove-DrsClusterGroup -DrsClusterGroup $drsGroupName -Server $($vcfVcenterDetails.fqdn) -Confirm:$false | Out-Null
                                        if (!(Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $drsGroupName})) {
                                            Write-Output "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): SUCCESSFUL"
                                        } else {
                                            Write-Error "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Removing vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), already removed: SKIPPED"
                                        
                                    }
                                } else {
                                    Write-Error "Unable to remove vSphere DRS Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($drsGroupName), in use by VM to VM Group: PRE_VALIDATION_FAILED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-ClusterGroup

Function Add-VmStartupRule {
    <#
        .SYNOPSIS
        Creates a VM to VM DRS rule

        .DESCRIPTION
        The Add-VmStartupRule cmdlet creates a vSphere DRS Virtual Machine to Virtual Machine startup rule. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that that the Virtual Machine to Virtual Machine startup rule does not already exist in the vCenter Server inventory
        - Creates the vSphere DRS Virtual Machine to Virtual Machine startup rule in the vCenter Server inventory

        .EXAMPLE
        Add-VmStartupRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName vm-vm-rule-wsa-vra -vmGroup sfo-m01-vm-group-wsa -dependOnVmGroup sfo-m01-vm-group-vra
        This example shows how to create a vSphere DRS Cluster group in the vCenter Server of the sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server,
        [Parameter (Mandatory = $true)] [String]$user,
        [Parameter (Mandatory = $true)] [String]$pass,
        [Parameter (Mandatory = $true)] [String]$domain,
        [Parameter (Mandatory = $true)] [String]$ruleName,
        [Parameter (Mandatory = $true)] [String]$vmGroup,
        [Parameter (Mandatory = $true)] [String]$dependOnVmGroup
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $vmGroup}) {
                                    if (Get-Cluster -Name $cluster | Get-DrsClusterGroup | Where-Object {$_.Name -eq $dependOnVmGroup}) {
                                        if (!(Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName)) {
                                            Add-DrsVmToVmGroup -name $ruleName -vmGroup $vmGroup -dependOnVmGroup $dependOnVmGroup -Enabled -cluster $cluster | Out-Null
                                            Start-Sleep 5
                                            if (Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName) {
                                                Write-Output "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL"
                                            } else {
                                                Write-Error "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED"
                                            }
                                        } else {
                                            Write-Warning "Adding vSphere DRS Virtual Machine to Virtual Machine Group to vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already exists: SKIPPED"
                                        }
                                    } else {
                                        Write-Error "vSphere DRS Group (VM Group to start after dependency) in vCenter Server ($($vcfVcenterDetails.fqdnn)) named ($dependOnVmGroup), does not exist: PRE_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Error "vSphere DRS Group (VM Group to start first) in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($vmGroup), does not exist: PRE_VALIDATION_FAILED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-VmStartupRule

Function Undo-VmStartupRule {
    <#
        .SYNOPSIS
        Remove a VM to VM DRS rule

        .DESCRIPTION
        The Undo-VmStartupRule cmdlet removes a vSphere DRS Virtual Machine to Virtual Machine startup rule. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that that the Virtual Machine to Virtual Machine startup rule has not already been removed from the vCenter Server inventory
        - Removes the vSphere DRS Virtual Machine to Virtual Machine startup rule from the vCenter Server inventory

        .EXAMPLE
        Undo-VmStartupRule -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -ruleName vm-vm-rule-wsa-vrli
        This example shows how to remove a vSphere DRS Cluster group from the vCenter Server of the sfo-m01 workload domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server,
        [Parameter (Mandatory = $true)] [String]$user,
        [Parameter (Mandatory = $true)] [String]$pass,
        [Parameter (Mandatory = $true)] [String]$domain,
        [Parameter (Mandatory = $true)] [String]$ruleName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                        if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                            if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                                $cluster = (Get-VCFCluster | Where-Object { $_.id -eq ((Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }).clusters.id) }).Name
                                if (Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName) {
                                    Remove-DrsVmToVmGroup -name $ruleName -cluster $cluster | Out-Null
                                    Start-Sleep 3
                                    if (!(Get-DrsVmToVmGroup -Cluster $cluster -Name $ruleName)) {
                                        Write-Output "Removing vSphere DRS Virtual Machine to Virtual Machine Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): SUCCESSFUL"
                                    } else {
                                        Write-Error "Removing vSphere DRS Virtual Machine to Virtual Machine Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName): POST_VALIDATION_FAILED"
                                    }
                                } else {
                                    Write-Warning "Removing vSphere DRS Virtual Machine to Virtual Machine Group from vCenter Server ($($vcfVcenterDetails.fqdn)) named ($ruleName), already exists: SKIPPED"
                                }
                                Disconnect-VIServer $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue
                            }
                        }
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-VmStartupRule

Function Move-VMtoFolder {
    <#
        .SYNOPSIS
        Moves VMs to a folder

        .DESCRIPTION
        The Move-VMtoFolder cmdlet moves the Virtual Machines to a folder. The cmdlet connects to SDDC Manager using
        the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Retrives the details of the vCenter Server for the Workload Domain provided
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates the virtual machine exists in the vCenter Server inventory
        - Moves the virtual machines provided in the -vmlist parameter

        .EXAMPLE
        Move-VMtoFolder -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -vmList "xreg-wsa01a,xreg-wsa01b,xreg-wsa01c" -folder xinst-m01-fd-wsa
        This example shows how to move a list of virtual machines to a new folder
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server,
        [Parameter (Mandatory = $true)] [String]$user,
        [Parameter (Mandatory = $true)] [String]$pass,
        [Parameter (Mandatory = $true)] [String]$domain,
        [Parameter (Mandatory = $true)] [String]$vmList,
        [Parameter (Mandatory = $true)] [String]$folder
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if ($vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain -ErrorAction SilentlyContinue) {
                    Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null
                    if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) {
                        if (Get-Folder | Where-Object {$_.Name -eq $folder}) {
                            $vmNames = $vmList.split(",")
                            foreach ($vm in $vmNames) { 
                                if (Get-VM -Name $vm -ErrorAction SilentlyContinue) {
                                    Get-VM -Name $vm | Move-VM -InventoryLocation (Get-Folder | Where-Object {$_.Name -eq $folder}) | Out-Null
                                    Write-Output "Relocating Virtual Machine in vCenter Server ($($vcenter.fqdn)) named ($vm) to folder ($folder): SUCCESSFUL"
                                } else {
                                    Write-Warning "Relocating Virtual Machines in vCenter Server ($($vcenter.fqdn)) named ($vm) to folder ($folder), Vitual Machine not found: SKIPPED"
                                }
                            }
                        } else {
                            Write-Error "Relocating Virtual Machine in vCenter Server ($($vcenter.fqdn)) folder ($folder), Folder not found: PRE_VALIDATION_FAILED"
                        }
                        Disconnect-VIServer $vcenter.fqdn -Confirm:$false -WarningAction SilentlyContinue
                    } else {
                        Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn)): PRE_VALIDATION_FAILED"
                    }
                } else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Move-VMtoFolder

Function Add-VdsPortGroup {
    <#
        .SYNOPSIS
        Create vSphere Distributed port group

        .DESCRIPTION
        The Add-VdsPortGroup cmdlet creates a vSphere Distributed port groups in vCenter Server. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible the SDDC Manager instance
        - Validates that network connectivity and authentication is possible the vCenter Server instance
        - Creates a vSphere Distributed port group in vCenter Server

        .EXAMPLE
        Add-VdsPortGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -portgroup sfo-m01-cl01-vds01-pg-vrms -vlan 2619
        This example creates a vSphere Distributed port group for VLAN ID 2619 named sfo-m01-cl01-vds01-pg-vrms in vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$portgroup,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$vlan
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (!(Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)})) {
                                $createVDPortGroup = New-VDPortGroup -Server $vcfVcenterDetails.fqdn -VDSwitch (Get-VDSwitch -Server $vcfVcenterDetails.fqdn).Name -Name $portgroup -VlanId $vlan -ErrorAction Stop
                                $createVDPortGroup | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy LoadBalanceLoadBased | Out-Null
                                if (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {($_.Name -eq $portgroup)}) {
                                    Write-Output "Creating vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($($portgroup)): SUCCESSFUL"
                                } else {
                                    Write-Error "Creating vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($($portgroup)): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Creating vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($($portgroup)), already exists: SKIPPED"
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-VdsPortGroup

Function Undo-VdsPortGroup {
    <#
        .SYNOPSIS
        Removes vSphere Distributed port group

        .DESCRIPTION
        The Undo-VdsPortGroup cmdlet removes a vSphere Distributed port groups in vCenter Server. The cmdlet connects
        to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible the SDDC Manager instance
        - Validates that network connectivity and authentication is possible the vCenter Server instance
        - Removes the vSphere Distributed port group in vCenter Server

        .EXAMPLE
        Undo-VdsPortGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -portgroup sfo-m01-cl01-vds01-pg-vrms
        This example removes the vSphere Distributed port group named sfo-m01-cl01-vds01-pg-vrms from vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$portgroup
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            if (Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {$_.Name -eq $portgroup}) {
                                Remove-VDPortGroup -Server $vcfVcenterDetails.fqdn -VDPortGroup $portGroup -Confirm:$false -ErrorAction Stop -WarningAction SilentlyContinue | Out-Null         
                                if (!(Get-VDPortGroup -Server $vcfVcenterDetails.fqdn | Where-Object {$_.Name -eq $portgroup})) {
                                    Write-Output "Removing vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($($portgroup)): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($($portgroup)): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Removing vSphere Distributed Port Group in vCenter Server ($($vcfVcenterDetails.fqdn)) named ($($portgroup)), dosen't exist: SKIPPED"
                            }
                            Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-VdsPortGroup

Function Import-vRSLCMLockerCertificate {
    <#
        .SYNOPSIS
        Add a certificate to the vRealize Suite Lifecycle Manager Locker

        .DESCRIPTION
        The Import-vRSLCMLockerCertificate cmdlet imports a PEM encoded chain file to the vRealize Suite Lifecycle
        Manager Locker. The cmdlet connects to SDDC Manager using the -server, -user, and -password values then:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Verifies that the certificate is not present in the vRealize Suite Lifecycle Manager Locker
        - Imports the certificate chain to the vRealize Suite Lifecycle Manager Locker

        .EXAMPLE
        Import-vRSLCMLockerCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -certificateAlias "xint-vrops01" -certificatePassphrase "VMw@re1!"
        This example gets the details of a certificate based on the vmid
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificatePassphrase,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certChainPath
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("certChainPath")) {
            $certChainPath = Get-ExternalFileName -title "Select the Certificate Chain PEM File (.pem)" -fileType "pem" -location "default"
        }
        else {
            if (!(Test-Path -Path $certChainPath)) {
                Write-Error  "Certificate Chain '$certChainPath' File Not Found"
                Break
            }
        }

        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (!(Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) {
                                if ($PsBoundParameters.ContainsKey("certificatePassphrase")) {
                                    Add-vRSLCMLockerCertificate -vrslcmFQDN $vcfVrslcmDetails.fqdn -certificateAlias $certificateAlias -certificatePassphrase $certificatePassphrase -certChainPath $certChainPath | Out-Null
                                } else {
                                    Add-vRSLCMLockerCertificate -vrslcmFQDN $vcfVrslcmDetails.fqdn -certificateAlias $certificateAlias -certChainPath $certChainPath | Out-Null
                                }
                                if ((Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) {
                                    Write-Output "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): SUCCESSFUL"
                                } else {
                                    Write-Error "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Importing Certificate to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias), already exist: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Import-vRSLCMLockerCertificate

Function Undo-vRSLCMLockerCertificate {
    <#
        .SYNOPSIS
        Remove a certificate from the vRealize Suite Lifecycle Manager Locker

        .DESCRIPTION
        The Undo-vRSLCMLockerCertificate cmdlet removes a certificate from the vRealize Suite Lifecycle Manager Locker.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values then:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Verifies that the certificate is present in the vRealize Suite Lifecycle Manager Locker
        - Removes the certificate from vRealize Suite Lifecycle Manager Locker

        .EXAMPLE
        Undo-vRSLCMLockerCertificate -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -certificateAlias "xint-vrops01"
        This example removes a certificate with an alias of 'xint-vrops01' from the vRealize Suite Lifecycle Manager Locker
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias
    )

    Try {

        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias}) {
                                Remove-vRSLCMLockerCertificate -vmid (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias}).vmid | Out-Null
                                if ((Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $certificateAlias})) {
                                    Write-Error "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): POST_VALIDATION_FAILED"
                                } else {
                                    Write-Output "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias): SUCCESSFUL"
                                }
                            } else {
                                Write-Warning "Removing Certificate from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($certificateAlias), does not exist: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Undo-vRSLCMLockerCertificate

Function New-vRSLCMLockerPassword {
    <#
        .SYNOPSIS
        Add a password to the vRealize Suite Lifecycle Manager Locker Locker

        .DESCRIPTION
        The New-vRSLCMLockerPassword cmdlet adds a password to the vRealize Suite Lifecycle Manager Locker Locker. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values then:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Verifies that the password is not present in the vRealize Suite Lifecycle Manager Locker
        - Adds the password to the vRealize Suite Lifecycle Manager Locker

        .EXAMPLE
        New-vRSLCMLockerPassword -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias xint-vrops01-admin -password VMw@re1! -description "vRealize Operations Admin" -userName xint-vrops01-admin
        This example adds a password with an alias of 'xint-vrops01-admin' to the vRealize Suite Lifecycle Manager Locker
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (!(Get-vRSLCMLockerPassword -alias $alias)) {
                                if ($PsBoundParameters.ContainsKey("description")) {
                                    $lockerPassword = Add-vRSLCMLockerPassword -alias $alias -password $password -description $description -userName $userName
                                } else {
                                    $lockerPassword = Add-vRSLCMLockerPassword -alias $alias -password $password -userName $userName
                                }
                                if ((Get-vRSLCMLockerPassword -alias $alias)) {
                                    Write-Output "Adding Password to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL"
                                } else {
                                    Write-Error "Adding Password to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Warning "Adding Password to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), already exists: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRSLCMLockerPassword

Function Undo-vRSLCMLockerPassword {
    <#
        .SYNOPSIS
        Remove a password from the vRealize Suite Lifecycle Manager Locker

        .DESCRIPTION
        The Undo-vRSLCMLockerPassword cmdlet removes a password from the vRealize Suite Lifecycle Manager Locker. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values then:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Verifies that the password is present in the vRealize Suite Lifecycle Manager Locker
        - Removes the password from the vRealize Suite Lifecycle Manager Locker

        .EXAMPLE
        Undo-vRSLCMLockerPassword -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias xint-vrops01-admin
        This example removes a password with an alias of 'xint-vrops01-admin' from the vRealize Suite Lifecycle Manager Locker
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (Get-vRSLCMLockerPassword -alias $alias) {
                                Remove-vRSLCMLockerPassword -vmid (Get-vRSLCMLockerPassword -alias $alias).vmid | Out-Null
                                if ((Get-vRSLCMLockerPassword -alias $alias)) {
                                    Write-Error "Removing Password from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED"
                                } else {
                                    Write-Output "Removing Password from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL"
                                }
                            } else {
                                Write-Warning "Removing Password from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), does not exist: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Undo-vRSLCMLockerPassword

Function New-vRSLCMLockerLicense {
    <#
        .SYNOPSIS
        Add a license to the vRealize Suite Lifecycle Manager Locker

        .DESCRIPTION
        The New-vRSLCMLockerLicense cmdlet adds a license to the vRealize Suite Lifecycle Manager Locker. The cmdlet
        connects to SDDC Manager using the -server, -user, and -password values then:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - CValidates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Verifies that the license is not present in the vRealize Suite Lifecycle Manager Locker
        - Adds the license to the vRealize Suite Lifecycle Manager Locker

        .EXAMPLE
        New-vRSLCMLockerLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias "vRealize Automation" -license "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
        This example adds a license with an alias of 'vRealize Automation' to the vRealize Suite Lifecycle Manager Locker
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (!(Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license})) {
                                if (!(Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias})) {
                                    $newRequest = Add-vRSLCMLockerLicense -alias $alias -license $license
                                    Start-Sleep 3
                                    $status = Watch-vRSLCMRequest -vmid $($newRequest.requestId)
                                    if ($status -match "COMPLETED") {
                                        if ((Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license})) {
                                            Write-Output "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Error "$status"
                                    }
                                } else {
                                    Write-Warning "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), already exists: SKIPPED"
                                }
                            } else {
                                Write-Warning "Adding License to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with license ($license), already exists: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRSLCMLockerLicense

Function Undo-vRSLCMLockerLicense {
    <#
        .SYNOPSIS
        Remove a license to the vRealize Suite Lifecycle Manager Locker

        .DESCRIPTION
        The Undo-vRSLCMLockerLicense cmdlet removes a license from the vRealize Suite Lifecycle Manager Locker. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values then:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Verifies that the license is present in the vRealize Suite Lifecycle Manager Locker
        - Removes the license to the vRealize Suite Lifecycle Manager Locker

        .EXAMPLE
        Undo-vRSLCMLockerLicense -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -alias "vRealize Automation"
        This example removes a license with an alias of 'vRealize Automation' from the vRealize Suite Lifecycle Manager Locker
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias}) {
                                Remove-vRSLCMLockerLicense -vmid (Get-vRSLCMLockerLicense | Where-Object {$_.alias -eq $alias}).vmid | Out-Null
                                if (Get-vRSLCMLockerLicense | Where-Object {$_.key -eq $license}) {
                                    Write-Error "Removing License from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): POST_VALIDATION_FAILED"
                                } else {
                                    Write-Output "Removing License from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias): SUCCESSFUL"
                                }
                            } else {
                                Write-Warning "Removing License from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($alias), does not exist: SKIPPED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Undo-vRSLCMLockerLicense

Function New-vRSLCMDatacenter {
    <#
        .SYNOPSIS
        Adds a datacenter to vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The New-vRSLCMDatacenter cmdlet adds a datacenter to the vRealize Suite Lifecycle Manager inventory. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the datacenter has not already been created in the inventory
        - Creates the datacenter in the inventory

        .EXAMPLE
        New-vRSLCMDatacenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -datacenterName xint-m01-dc01 -location "San Francisco, California, US"
        This example adds a datacenter to the vRealize Suite Lifecycle Manager inventory
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$location
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { 
                            if (!(Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue )) {
                                Add-vRSLCMDatacenter -datacenterName $datacenterName -location $location | Out-Null
                                if (Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue ) {
                                    Write-Output "Adding Datacenter to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory name ($datacenterName): SUCCESSFUL"
                                } else {
                                    Write-Error "Adding Datacenter to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory name ($datacenterName): POST_VALIDATION_FAILED"
                                }
                            }   else {
                                Write-Warning "Adding Datacenter to the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory name ($datacenterName), already exists: SKIPPED"
                            }
                        }
                    }
                }                         
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRSLCMDatacenter

Function New-vRSLCMDatacenterVcenter {
    <#
        .SYNOPSIS
        Adds a vCenter Server to a Datacenter to vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The New-vRSLCMDatacenterVcenter cmdlet adds a vCenter Server to a Datacenter to the vRealize Suite Lifecycle
        Manager inventory. The cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the vCenter Server has not already been added to the Datacenter
        - Adds the vCenter Server to the Datacenter

        .EXAMPLE
        New-vRSLCMDatacenterVcenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -datacenterName xint-m01-dc01 -vcenterFqdn sfo-m01-vc01.sfo.rainpole.io -userLockerAlias sfo-m01-vc01-sfo-m01-dc01
        This example adds a vCenter Server to a Datacenter in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userLockerAlias
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { 
                            if (Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue ) {
                                if (Get-vRSLCMLockerPassword -alias $userLockerAlias) {
                                    if (!(Get-vRSLCMDatacenterVcenter -datacenterVmid (Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid -vcenterName  ($vcenterFqdn.Split(".")[0]) -ErrorAction SilentlyContinue)) {
                                        Add-vRSLCMDatacenterVcenter -datacenterVmid (Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid -vcenterFqdn $vcenterFqdn -userLockerAlias $userLockerAlias | Out-Null
                                        Start-Sleep 5
                                        if (Get-vRSLCMDatacenterVcenter -datacenterVmid (Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid -vcenterName ($vcenterFqdn.Split(".")[0]) -ErrorAction SilentlyContinue) {
                                            Write-Output "Adding vCenter Server to Datacenter ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($($vcenterFqdn.Split(".")[0])): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding vCenter Server to Datacenter ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($($vcenterFqdn.Split(".")[0])): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Adding vCenter Server to Datacenter ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($($vcenterFqdn.Split(".")[0])), already exists: SKIPPED"
                                    }
                                } else {
                                    Write-Error "Unable to find Password alias in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) named ($userLockerAlias): PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to find Datacenter named ($datacenterName) in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }                         
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRSLCMDatacenterVcenter

Function Undo-vRSLCMDatacenter {
    <#
        .SYNOPSIS
        Deletes a datacenter from vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Undo-vRSLCMDatacenter cmdlet deletes a datacenter from the vRealize Suite Lifecycle Manager inventory. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vRealize Suite Lifecycle Manager
        - Validates that the datacenter has not already been removed from the inventory
        - Deletes the datacenter from the inventory

        .EXAMPLE
        Undo-vRSLCMDatacenter -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -datacenterName xint-m01-dc01
        This example deletes a datacenter from the vRealize Suite Lifecycle Manager inventory
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) { 
                            if (Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue ) {
                                Remove-vRSLCMDatacenter -datacenterVmid ((Get-vRSLCMDatacenter -datacenterName $datacenterName).datacenterVmid) | Out-Null
                                Start-Sleep 2
                                if (!(Get-vRSLCMDatacenter -datacenterName $datacenterName -ErrorAction SilentlyContinue )) {
                                    Write-Output "Removing Datacenter from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory named ($datacenterName): SUCCESSFUL"
                                } else {
                                    Write-Error "Removing Datacenter from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory named ($datacenterName): POST_VALIDATION_FAILED"
                                }
                            }   else {
                                Write-Warning "Removing Datacenter from the vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) inventory named ($datacenterName), does not exist: SKIPPED"
                            }
                        }
                    }
                }                         
            }
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Undo-vRSLCMDatacenter

Function Add-VmGroup {
    <#
        .SYNOPSIS
        Add a VM Group

        .DESCRIPTION
        The Add-VmGroup cmdlet adds a Virtual Machine to an existing VM Group. The cmdlet connects to SDDC Manager
        using the -server, -user, and -password values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Validates that the the VM Group provided exists and that its a VM Group not a VM Host Group
        - Adds the Virtual Machines provided using -vmList

        .EXAMPLE
        Add-VmGroup -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-m01 -name "primary_az_vmgroup" -vmList "xint-vra01a,xint-vra01b,xint-vra01c"
        This example adds the vRealize Automation cluster VMs to the VM Group called primary_az_vmgroup
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmList
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if ($vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain) {
                    Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -Pass $vcenter.ssoAdminPass | Out-Null
                    if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) {
                        $vmGroupExists = Get-DrsClusterGroup -Server $vcenter.fqdn -Name $name -ErrorAction Ignore
                        if ($vmGroupExists.GroupType -eq "VMGroup") {
                            $vmNames = $vmList.split(",")
                            foreach ($vm in $vmNames) { Set-DrsClusterGroup -VM $vm -Server $vcenter.fqdn -DrsClusterGroup (Get-DrsClusterGroup | Where-Object {$_.Name -eq $name} -WarningAction SilentlyContinue -ErrorAction Ignore) -Add | Out-Null }
                            Write-Output "Adding Virtual Machines ($vmList) to VM/Host Group in vCenter Server ($($vcenter.fqdn)) named ($name): SUCCESSFUL"
                        } else {
                            Write-Error "Adding Virtual Machines ($vmList) to VM/Host Group in vCenter Server ($($vcenter.fqdn)) named ($name), does not exist or not a VM Group: POST_VALIDATION_FAILED"
                        }
                    } else {
                        Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn)): PRE_VALIDATION_FAILED"
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-VmGroup

Function Add-WorkspaceOneDirectoryGroup {
    <#
        .SYNOPSIS
        Adds Active Directory Group to sync in Workspace ONE Access Appliance

        .DESCRIPTION
        The Add-WorkspaceOneDirectoryGroup cmdlet adds an Active Directory Group to sync in Workspace ONE Access Appliance
        - Validates that network connectivity and authentication is possible to Workspace ONE Access
        - Adds Active Directory Groups to Workspace ONE Access

        .EXAMPLE
        Add-WorkspaceOneDirectoryGroup -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -bindUser svc-vsphere-ad -bindPass VMw@re1! -baseDnGroup "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -adGroups "gg-vrli-admins","gg-vrli-users","gg-vrli-viewers"
        This example adds Active Directory groups to Workspace ONE Access directory
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDnGroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$adGroups
    )

    Try {
        if (Test-WSAConnection -server $server) {
            if (Test-WSAAuthentication -server $server -user $user -pass $pass) {
                if ((Test-ADAuthentication -user $bindUser -pass $bindPass -server $domain -domain $domain) -match "AD Authentication Successful") {
                    if (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }) {
                        $configuredGroups = New-Object System.Collections.Generic.List[System.Object]
                        $allGroups = New-Object System.Collections.Generic.List[System.Object]
                        $existingGroupList = Get-WSAGroup | Where-Object {$_.displayName -Match $domain} | Select-Object displayName
                        foreach ($existingGroup in $existingGroupList) {
                            $groupName = ($existingGroup.displayname.Split("@"))[0]
                            $configuredGroups.Add($groupName)
                            $allGroups.Add($groupName)
                        }                    
                        $missingGroups = Compare-Object $adGroups $configuredGroups |  Where-Object { $_.SideIndicator -eq '<=' } | Foreach-Object { $_.InputObject }
                        foreach ($newGroup in $missingGroups) {
                            $allGroups.Add($newGroup)
                        }
                        $allGroups.ToArray() | Out-Null

                        $mappedGroupObject = @()
                        foreach ($group in $allGroups) {
                            $adGroupDetails = Get-ADPrincipalGuid -domain $domain -user $bindUser -pass $bindPass -principal $group
                            if ($adGroupDetails) {
                                $groupsObject = @()
                                $groupsObject += [pscustomobject]@{
                                    'horizonName' = $adGroupDetails.Name
                                    'dn'          = $adGroupDetails.DistinguishedName
                                    'objectGuid'  = $adGroupDetails.ObjectGuid
                                    'groupBaseDN' = $baseDnGroup
                                    'source'      = "DIRECTORY"
                                }
                                $mappedGroupObject += [pscustomobject]@{
                                    'mappedGroup' = ($groupsObject | Select-Object -Skip 0)
                                    'selected'    = $true
                                }
                            } else {
                                Write-Error "Group $group is not available in Active Directory Domain"
                            }
                        }
                        $mappedGroupObjectData = @()
                        $mappedGroupObjectData += [pscustomobject]@{
                            'mappedGroupData' = $mappedGroupObject
                            'selected'        = $false
                        }
                        $identityGroupObject = @()
                        $identityGroupObject += [pscustomobject]@{
                            $baseDnGroup = ($mappedGroupObjectData | Select-Object -Skip 0)
                        }
                        $adGroupObject = @()
                        $adGroupObject += [pscustomobject]@{
                            'identityGroupInfo'         = ($identityGroupObject | Select-Object -Skip 0)
                            'excludeNestedGroupMembers' = $false
                        }
                        $adGroupJson = $adGroupObject | ConvertTo-Json -Depth 10 

                        $adGroupJson | Out-File -Encoding UTF8 -FilePath .\adGroups.json

                        Set-WSADirectoryGroup -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId -json $adGroupJson | Out-Null
                        Start-WSADirectorySync -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId | Out-Null
                        Remove-Item .\adGroups.json -Force -Confirm:$false
                        Write-Output "Adding Active Directory Groups in Workspace ONE Access ($server): SUCCESSFUL"
                    } else {
                        Write-Error "Active Directory Domain ($domain) does not exist, check details and try again: PRE_VALIDATION_FAILED"
                    }
                } else {
                    Write-Error "Domain User ($bindUser) Authentication Failed: PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-WorkspaceOneDirectoryGroup

Function Undo-WorkspaceOneDirectoryGroup {
    <#
        .SYNOPSIS
        Removes Active Directory Group from Workspace ONE Access

        .DESCRIPTION
        The Undo-WorkspaceOneDirectoryGroup cmdlet removes an Active Directory Group from Workspace ONE Access.
        - Validates that network connectivity and authentication is possible to Workspace ONE Access
        - Remove Active Directory Groups from Workspace ONE Access

        .EXAMPLE
        Undo-WorkspaceOneDirectoryGroup -server sfo-wsa01.sfo.rainpole.io -user admin -pass VMw@re1! -domain sfo.rainpole.io -bindUser svc-vsphere-ad -bindPass VMw@re1! -baseDnGroup "ou=Security Groups,dc=sfo,dc=rainpole,dc=io" -adGroups "gg-vrli-admins","gg-vrli-users","gg-vrli-viewers"
        This example removes Active Directory groups from Workspace ONE Access directory
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDnGroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$adGroups
    )

    Try {
        if (Test-WSAConnection -server $server) {
            if (Test-WSAAuthentication -server $server -user $user -pass $pass) {
                if ((Test-ADAuthentication -user $bindUser -pass $bindPass -server $domain -domain $domain) -match "AD Authentication Successful") {
                    if (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }) {
                        $configuredGroups = New-Object System.Collections.Generic.List[System.Object]
                        $allGroups = New-Object System.Collections.Generic.List[System.Object]
                        $existingGroupList = Get-WSAGroup | Where-Object {$_.displayName -Match $domain} | Select-Object displayName
                        foreach ($existingGroup in $existingGroupList) {
                            $groupName = ($existingGroup.displayname.Split("@"))[0]
                            $configuredGroups.Add($groupName)
                        }                    
                        $requiredGroups = Compare-Object $adGroups $configuredGroups | Foreach-Object { $_.InputObject } #| Where-Object { $_.SideIndicator -eq '==' } | Foreach-Object { $_.InputObject }
                        foreach ($newGroup in $requiredGroups) {
                            $allGroups.Add($newGroup)
                        }
                        $allGroups.ToArray() | Out-Null
                        $mappedGroupObject = @()
                        foreach ($group in $allGroups) {
                            $adGroupDetails = Get-ADPrincipalGuid -domain $domain -user $bindUser -pass $bindPass -principal $group
                            if ($adGroupDetails) {
                                $groupsObject = @()
                                $groupsObject += [pscustomobject]@{
                                    'horizonName' = $adGroupDetails.Name
                                    'dn'          = $adGroupDetails.DistinguishedName
                                    'objectGuid'  = $adGroupDetails.ObjectGuid
                                    'groupBaseDN' = $baseDnGroup
                                    'source'      = "DIRECTORY"
                                }
                                $mappedGroupObject += [pscustomobject]@{
                                    'mappedGroup' = ($groupsObject | Select-Object -Skip 0)
                                    'selected'    = $true
                                }
                            } else {
                                Write-Error "Group $group is not available in Active Directory Domain"
                            }
                        }
                        $mappedGroupObjectData = @()
                        $mappedGroupObjectData += [pscustomobject]@{
                            'mappedGroupData' = $mappedGroupObject
                            'selected'        = $false
                        }
                        $identityGroupObject = @()
                        $identityGroupObject += [pscustomobject]@{
                            $baseDnGroup = ($mappedGroupObjectData | Select-Object -Skip 0)
                        }
                        $adGroupObject = @()
                        $adGroupObject += [pscustomobject]@{
                            'identityGroupInfo'         = ($identityGroupObject | Select-Object -Skip 0)
                            'excludeNestedGroupMembers' = $false
                        }
                        $adGroupJson = $adGroupObject | ConvertTo-Json -Depth 10 
                        $adGroupJson | Out-File -Encoding UTF8 -FilePath .\adGroups.json
                        Set-WSADirectoryGroup -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId -json $adGroupJson | Out-Null
                        Start-WSADirectorySync -directoryId (Get-WSADirectory | Where-Object { ($_.name -eq $domain) }).directoryId | Out-Null
                        Remove-Item .\adGroups.json -Force -Confirm:$false
                        Write-Output "Removing Active Directory Groups in Workspace ONE Access ($server): SUCCESSFUL"
                    } else {
                        Write-Error "Active Directory Domain ($domain) does not exist, check details and try again: PRE_VALIDATION_FAILED"
                    }
                } else {
                    Write-Error "Domain User ($bindUser) Authentication Failed: PRE_VALIDATION_FAILED"
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-WorkspaceOneDirectoryGroup

Function Add-WorkspaceOneDirectoryConnector {
    <#
        .SYNOPSIS
        Adds a connector to the directory in Workspace ONE Access Appliance

        .DESCRIPTION
        The Add-WorkspaceOneDirectoryConnector cmdlet adds a connector to the directory in Workspace ONE Access Appliance

        .EXAMPLE
        Add-WorkspaceOneDirectoryConnector -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo.rainpole.io -wsaNode xint-wsa01b.rainpole.io -wsaUser admin -wsaPass VMw@re1! -bindUserPass VMw@re1!
        This example adds Active Directory groups to Workspace ONE Access directory
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaNode,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUserPass
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfWsaDetails = Get-WSAServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-WSAConnection -server $vcfWsaDetails.loadBalancerFqdn) {
                        if (Test-WSAAuthentication -server $vcfWsaDetails.loadBalancerFqdn -user $wsaUser -pass $wsaPass) { 
                            if ($directoryId = (Get-WSADirectory | Where-Object {$_.name -eq $domain}).directoryId) {
                                if (Get-WSAConnector | Where-Object {$_.host -eq $wsaNode}) {
                                    if (!(Get-WSADirectory -directoryId $directoryId -connector | Where-Object {$_.host -eq $wsaNode})) {
                                        Add-WSAConnector -wsaNode $wsaNode -domain $domain -bindUserPass $bindUserPass | Out-Null
                                        if (Get-WSADirectory -directoryId $directoryId -connector | Where-Object {$_.host -eq $wsaNode}) {
                                            Write-Output "Adding Connector to Directory ($domain) in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode): SUCCESSFUL"
                                        } else {
                                            Write-Error "Adding Connector to Directory ($domain) in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode): POST_VALIDATION_FAILED"
                                        }
                                    } else {
                                        Write-Warning "Adding Connector to Directory ($domain) in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode), already exists: SKIPPED"
                                    }
                                } else {
                                    Write-Error "Unable to find node in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($wsaNode): PRE_VALIDATION_FAILED"
                                }
                            } else {
                                Write-Error "Unable to find Active Directory domain in Workspace ONE Access ($($vcfWsaDetails.loadBalancerFqdn)) named ($domain): PRE_VALIDATION_FAILED"
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-WorkspaceOneDirectoryConnector

Function Update-SddcDeployedFlavor {
    <#
        .SYNOPSIS
        Add a Validated Solution tag

        .DESCRIPTION
        The Update-SddcDeployedFlavor cmdlet adds a Validated Solution tag to the vCenter Server Advanced Setting
        `config.SDDC.Deployed.Flavor`. The cmdlet connects to SDDC Manager using the -server, -user, and -password
        values:
        - Validates that network connectivity and authentication is possible to SDDC Manager
        - Validates that network connectivity and authentication is possible to vCenter Server
        - Adds a Validated Solution tag to the vCenter Server Advanced Setting `config.SDDC.Deployed.Flavor`

        .EXAMPLE
        Update-SddcDeployedFlavor -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -vvsTag IAM
        This example adds the IAM tag to the `config.SDDC.Deployed.Flavor` vCenter Server Advanced Setting
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateSet("IAM","DRI","ILA","IOM","PCA","PDR","ALB")] [String]$vvsTag
    )

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($vcfVcenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) {
                            $advancedSetting = Get-AdvancedSetting -Name "config.SDDC.Deployed.Flavor" -Entity $vcfVcenterDetails.fqdn -Server $vcfVcenterDetails.fqdn
                            [Array]$flavours = $advancedSetting.Value -Split ", "
                            $newFlavours = New-Object System.Collections.Generic.List[System.Object]
                            Foreach ($flavour in $flavours) {
                                if (!($flavour -eq $vvsTag)) {
                                    $newFlavours += $flavour
                                }
                            }
                            $newFlavours += $vvsTag
                            $newFlavours = $newFlavours | Sort-Object
                            [String]$updatedFlavour = $newFlavours -Join ", " 
                            Set-AdvancedSetting -AdvancedSetting $advancedSetting -Value $updatedFlavour -Confirm:$false | Out-Null
                            Disconnect-VIServer -Server $vcfVcenterDetails.fqdn -Confirm:$false -WarningAction SilentlyContinue | Out-Null
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Update-SddcDeployedFlavor

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region S U P P O R T I N G F U N C T I O N S ###########

#####################################################################
#Region Begin Active Directory Functions ######

Function Test-ADAuthentication {
    <#
        .SYNOPSIS
        Test authetication against Active Directory

        .DESCRIPTION
        The Test-ADAuthentication cmdlet tests the credentials provided against Active Directory domain

        .EXAMPLE
        Test-ADAuthentication -user svc-vsphere-ad -pass VMw@re1! -server sfo.rainpole.io -domain sfo.rainpole.io
        This example check that the svc-vsphere-ad user can authenticate to the sfo.rainpole.io domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [String]$server,
        [Parameter (Mandatory = $false)] [String]$domain = $env:USERDOMAIN
    )

    Try {
        Add-Type -AssemblyName System.DirectoryServices.AccountManagement
        $contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
        $argumentList = New-Object -TypeName "System.Collections.ArrayList"
        $null = $argumentList.Add($contextType)
        $null = $argumentList.Add($domain)
        if ($null -ne $server) {
            $argumentList.Add($server)
        }
        $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $argumentList -ErrorAction SilentlyContinue
        if ($null -eq $principalContext) {
            Write-Error "$domain\$user - AD Authentication Failed"
        }
        if ($principalContext.ValidateCredentials($user, $pass)) {
            Write-Output "$domain\$user - AD Authentication Successful"
        }
        else {
            Write-Error "$domain\$user - AD Authentication Failed"
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Test-ADAuthentication

Function Get-ADPrincipalGuid {
    <#
        .SYNOPSIS
        Get principal GUID details

        .DESCRIPTION
        The Get-ADPrincipalGuid cmdlet retrieves the GUID details for an active directory user or group Active Directory domain

        .EXAMPLE
        Get-ADPrincipalGuid -domain sfo.rainple.io -user svc-vsphere-ad -pass VMw@re1! -principal gg-sso-admin
        This example retrives the details for th gg-sso-admin domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal
    )

    Try {
        $checkAdAuthentication = Test-ADAuthentication -user $user -pass $pass -server $domain -domain $domain
        if ($checkAdAuthentication -contains "2") {
            $securePassword = ConvertTo-SecureString -String $pass -AsPlainText -Force
            $creds = New-Object System.Management.Automation.PSCredential ($user, $securePassword)
            $nsxAdminGroupObject = (Get-ADGroup -Server $domain -Credential $creds -Filter { SamAccountName -eq $principal })
            $nsxAdminGroupObject
        }
        else {
            Write-Error "Domain User $user Authentication Failed"
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-ADPrincipalGuid

#EndRegion End Active Directory Functions ######
#####################################################################

#####################################################################
#Region Begin Cloud Foundation Functions ######

Function Get-vCenterServerDetail {
    Param (
        [Parameter (Mandatory = $false)] [String]$server,
        [Parameter (Mandatory = $false)] [String]$user,
        [Parameter (Mandatory = $false)] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateSet("MANAGEMENT", "VI")][String]$domainType,
        [Parameter (Mandatory = $false)] [String]$domain
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("user") -or (!$PsBoundParameters.ContainsKey("pass"))) {
            # Request Credentials
            $creds = Get-Credential
            $user = $creds.UserName.ToString()
            $pass = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("server")) {
            $server = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io"
        }
        Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null

        if ($accessToken) {
            if ($PsBoundParameters.ContainsKey("domainType")) {
                # Dynamically build vCenter Server details based on Cloud Foundation domain type
                $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.type -eq $domainType }
            }
            if ($PsBoundParameters.ContainsKey("domain")) {
                # Dynamically build vCenter Server details based on Cloud Foundation domain name
                $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }
            }
            if ($vcfWorkloadDomainDetails) {
                $vcenterServerDetails = Get-VCFvCenter | Where-Object { $_.id -eq $($vcfWorkloadDomainDetails.vcenters.id) }
                $vcenterCredentialDetails = Get-VCFCredential | Where-Object { $_.resource.resourceId -eq $($vcenterServerDetails.id) }
                $pscCredentialDetails = Get-VCFCredential | Where-Object { $_.resource.resourceType -eq "PSC" }
                $vcenterServer = New-Object -TypeName psobject
                $vcenterServer | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcenterServerDetails.fqdn
                $vcenterServer | Add-Member -notepropertyname 'vmName' -notepropertyvalue $vcenterServerDetails.fqdn.Split(".")[0]
                $vcfDetail = Get-VCFManager
                if ( ($vcfDetail.version).Split("-")[0] -gt "4.1.0.0") {
                    $vcenterServer | Add-Member -notepropertyname 'ssoAdmin' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "SYSTEM") }).username
                    $vcenterServer | Add-Member -notepropertyname 'ssoAdminPass' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "SYSTEM") }).password
                }
                else {
                    $vcenterServer | Add-Member -notepropertyname 'ssoAdmin' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "USER") }).username
                    $vcenterServer | Add-Member -notepropertyname 'ssoAdminPass' -notepropertyvalue ($pscCredentialDetails | Where-Object { ($_.credentialType -eq "SSO" -and $_.accountType -eq "USER") }).password
                }
                $vcenterServer | Add-Member -notepropertyname 'root' -notepropertyvalue ($vcenterCredentialDetails | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "USER") }).username
                $vcenterServer | Add-Member -notepropertyname 'rootPass' -notepropertyvalue ($vcenterCredentialDetails | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "USER") }).password
                $vcenterServer
            }
            else {
                Write-Error "Unable to find Workload Domain type or domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
            }
        }
        else {
            Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials"
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vCenterServerDetail

Function Get-NsxtServerDetail {
    Param (
        [Parameter (Mandatory = $false)] [String]$fqdn,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password,
        [Parameter (Mandatory = $false)] [String]$domain,
        [Parameter( Mandatory = $false)] [ValidateSet("MANAGEMENT", "VI")] [String]$domainType,
        [Parameter (Mandatory = $false)] [switch]$listNodes = $false
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io"
        }
        Request-VCFToken -fqdn $fqdn -Username $username -Password $password | Out-Null

        if ($accessToken) {
            if ($PsBoundParameters.ContainsKey("domainType")) {
                # Dynamically build vCenter Server details based on Cloud Foundation domain type
                $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.type -eq $domainType }
            }
            if ($PsBoundParameters.ContainsKey("domain")) {
                # Dynamically build vCenter Server details based on Cloud Foundation domain name
                $vcfWorkloadDomainDetails = Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }
            }
            if ($vcfWorkloadDomainDetails) {
                $nsxtServerDetails = Get-VCFNsxtcluster | Where-Object { $_.id -eq $($vcfWorkloadDomainDetails.nsxtCluster.id) }
                $nsxtCreds = Get-VCFCredential | Where-Object { $_.resource.resourceId -eq $($nsxtServerDetails.id) }

                $nsxtCluster = New-Object -TypeName PSCustomObject
                $nsxtCluster | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $nsxtServerDetails.vipFqdn
                $nsxtCluster | Add-Member -notepropertyname 'adminUser' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM" -and $_.resource.domainName -eq $vcfWorkloadDomainDetails.name) }).username 
                $nsxtCluster | Add-Member -notepropertyname 'adminPass' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM" -and $_.resource.domainName -eq $vcfWorkloadDomainDetails.name) }).password
                $nsxtCluster | Add-Member -notepropertyname 'rootUser' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM" -and $_.resource.domainName -eq $vcfWorkloadDomainDetails.name) }).username
                $nsxtCluster | Add-Member -notepropertyname 'rootPass' -notepropertyvalue ($nsxtCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM" -and $_.resource.domainName -eq $vcfWorkloadDomainDetails.name) }).password
                if ($listNodes) {
                    $nsxtCluster | Add-Member -notepropertyname 'nodes' -notepropertyvalue $nsxtServerDetails.nodes
                }
                $nsxtCluster
            }
            else {
                Write-Error "Workload domainType or domain name does not exist"
                Break
            }
        }
        else {
            Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials"
            Break
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-NsxtServerDetail

Function Get-vRSLCMServerDetail {
    Param (
        [Parameter (Mandatory = $false)] [String]$fqdn,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io"
        }

        if (Test-VCFConnection -server $fqdn) {
            if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) {
                if (Get-VCFvRSLCM) {
                    # Get vRSLCM Server Details
                    $vRSLCMFQDN = Get-VCFvRSLCM
                    $vRSLCMCreds = Get-VCFCredential -resourceName $vRSLCMFQDN.fqdn
                    $vrslcmDetails = New-Object -TypeName PSCustomObject
                    $vrslcmDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vRSLCMFQDN.fqdn
                    $vrslcmDetails | Add-Member -notepropertyname 'adminUser' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).username
                    $vrslcmDetails | Add-Member -notepropertyname 'adminPass' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "API" -and $_.accountType -eq "SYSTEM") }).password
                    $vrslcmDetails | Add-Member -notepropertyname 'rootUser' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).username
                    $vrslcmDetails | Add-Member -notepropertyname 'rootPassword' -notepropertyvalue ($vRSLCMCreds | Where-Object { ($_.credentialType -eq "SSH" -and $_.accountType -eq "SYSTEM") }).password
                    $vrslcmDetails
                }
                else {
                    Write-Error "Unable to obtain vRealize Suite Lifecycle Manager details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED"
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vRSLCMServerDetail

Function Get-WSAServerDetail {
    Param (
        [Parameter (Mandatory = $false)] [String]$fqdn,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io"
        }

        if (Test-VCFConnection -server $fqdn) {
            if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) {
                if (Get-VCFvRA) {
                    $vcfWsaDetails = Get-VCFWSA
                    #$wsaCreds = Get-VCFCredential -resourceName $vcfWsaDetails.fqdn
                    $wsaDetails = New-Object -TypeName PSCustomObject
                    $wsaDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcfWsaDetails.nodes.fqdn
                    $wsaDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vcfWsaDetails.loadBalancerIpAddress
                    $wsaDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vcfWsaDetails.loadBalancerFqdn
                    $wsaDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vcfWsaDetails.nodes.ipAddress[0]
                    $wsaDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vcfWsaDetails.nodes.ipAddress[1]
                    $wsaDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vcfWsaDetails.nodes.ipAddress[2]
                    $wsaDetails
                }
                else {
                    Write-Error "Unable to obtain Workspace ONE Access details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED"
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-WSAServerDetail

Function Get-vRAServerDetail {
    Param (
        [Parameter (Mandatory = $false)] [String]$fqdn,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io"
        }

        if (Test-VCFConnection -server $fqdn) {
            if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) {
                if (Get-VCFvRA) {
                    $vcfVraDetails = Get-VCFvRA
                    $vraCreds = Get-VCFCredential -resourceName $vcfVraDetails.loadBalancerFqdn
                    $vraDetails = New-Object -TypeName PSCustomObject
                    $vraDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcfVraDetails.nodes.fqdn
                    $vraDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vcfVraDetails.loadBalancerIpAddress
                    $vraDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vcfVraDetails.loadBalancerFqdn
                    $vraDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vcfVraDetails.nodes.ipAddress[0]
                    $vraDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vcfVraDetails.nodes.ipAddress[1]
                    $vraDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vcfVraDetails.nodes.ipAddress[2]
                    $vraDetails
                }
                else {
                    Write-Error "Unable to obtain vRealize Automation details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED"
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vRAServerDetail

Function Get-vROPsServerDetail {
    <#
        .SYNOPSIS
        Gather details about vRealize Operations Manager

        .DESCRIPTION
        The Get-vROPsServerDetail cmdlet connects to SDDC Manager and gathers details about vRealize Operations Manager
        from the SDDC Manager inventory.

        .EXAMPLE
        Get-vROPsServerDetail -fqdn sfo-vcf01.sfo.rainpole.io -username administrator@vsphere.local -password VMw@re1!
        This example gathers details about vRealize Opertations Manager
      #>


    Param (
        [Parameter (Mandatory = $false)] [String]$fqdn,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io"
        }

        if (Test-VCFConnection -server $fqdn) {
            if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) {
                if (Get-VCFvROPS) {
                    $vcfVropsDetails = Get-VCFvROPs
                    $vropsCreds = Get-VCFCredential -resourceName $vcfVropsDetails.loadBalancerFqdn
                    $vropsDetails = New-Object -TypeName PSCustomObject
                    $vropsDetails | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vcfVropsDetails.nodes.fqdn
                    $vropsDetails | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vcfVropsDetails.loadBalancerIp
                    $vropsDetails | Add-Member -notepropertyname 'loadBalancerFqdn' -notepropertyvalue $vcfVropsDetails.loadBalancerFqdn
                    $vropsNode1FQDN = $vcfVropsDetails.nodes.fqdn[0]
                    $vropsNode1IP = [System.Net.Dns]::GetHostAddresses("$vropsNode1FQDN").IPAddressToString
                    $vropsDetails | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vropsNode1IP
                    $vropsNode2FQDN = $vcfVropsDetails.nodes.fqdn[1]
                    $vropsNode2IP = [System.Net.Dns]::GetHostAddresses("$vropsNode2FQDN").IPAddressToString
                    $vropsDetails | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vropsNode2IP
                    $vropsNode3FQDN = $vcfVropsDetails.nodes.fqdn[2]
                    $vropsNode3IP = [System.Net.Dns]::GetHostAddresses("$vropsNode3FQDN").IPAddressToString
                    $vropsDetails | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vropsNode3IP
                    $vropsDetails | Add-Member -notepropertyname 'adminUser' -notepropertyvalue $vropsCreds.username
                    $vropsDetails | Add-Member -notepropertyname 'adminPass' -notepropertyvalue $vropsCreds.password
                    $vropsDetails
                }
                else {
                    Write-Error "Unable to obtain vRealize Operations Manager details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED"
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vROPsServerDetail

Function Get-vRLIServerDetail {
    Param (
        [Parameter (Mandatory = $false)] [String]$fqdn,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "SDDC Manager access token not found. Please enter the SDDC Manager FQDN, e.g., sfo-vcf01.sfo.rainpole.io"
        }

        if (Test-VCFConnection -server $fqdn) {
            if (Test-VCFAuthentication -server $fqdn -user $username -pass $password) {
                if (Get-VCFvRLI) {
                    $vrliVcfDetail = Get-VCFvRLI
                    $vrliCreds = Get-VCFCredential -resourceName $vrliVcfDetail.loadBalancerFqdn
                    $vrliDetail = New-Object -TypeName PSCustomObject
                    $vrliDetail | Add-Member -notepropertyname 'fqdn' -notepropertyvalue $vrliVcfDetail.loadBalancerFqdn
                    $vrliDetail | Add-Member -notepropertyname 'loadBalancerIpAddress' -notepropertyvalue $vrliVcfDetail.loadBalancerIpAddress
                    $vrliDetail | Add-Member -notepropertyname 'node1IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[0]
                    $vrliDetail | Add-Member -notepropertyname 'node2IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[1]
                    $vrliDetail | Add-Member -notepropertyname 'node3IpAddress' -notepropertyvalue $vrliVcfDetail.nodes.ipAddress[2]
                    $vrliDetail | Add-Member -notepropertyname 'node1Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[0]
                    $vrliDetail | Add-Member -notepropertyname 'node2Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[1]
                    $vrliDetail | Add-Member -notepropertyname 'node3Fqdn' -notepropertyvalue $vrliVcfDetail.nodes.fqdn[2]
                    $vrliDetail | Add-Member -notepropertyname 'adminUser' -notepropertyvalue $vrliCreds.username
                    $vrliDetail | Add-Member -notepropertyname 'adminPass' -notepropertyvalue $vrliCreds.password
                    $vrliDetail
                }
                else {
                    Write-Error "Unable to obtain vRealize Log Insight details from SDDC Manager ($fqdn), check deployment status: PRE_VALIDATION_FAILED"
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vRLIServerDetail

Function Get-VCFDnsSearchDomain {
    <#
        .SYNOPSIS
        Get the search domains configured in an SDDC Manager appliance

        .DESCRIPTION
        The Get-VCFDnsSearchDomain cmdlet gets the search domains configured in an SDDC Manager appliance

        .EXAMPLE
        Get-VCFDnsSearchDomain
        This example gets all search domains configured in an SDDC Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sddcManagerVmName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sddcManagerRootPass
    )

    Try {
        $scriptCommand = "cat /etc/resolv.conf"
        try {
            $output = Invoke-VMScript -VM $sddcManagerVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $sddcManagerRootPass -Server $vcfVcenterDetails.fqdn -ErrorAction Stop
        }
        catch {
            if ($_.Exception -match "Failed to authenticate with the guest operating system") {
                $PSCmdlet.ThrowTerminatingError(
                    [System.Management.Automation.ErrorRecord]::new(
                        ([System.Security.Authentication.InvalidCredentialException]"Retrieving DNS search domains from SDDC Manager - invalid credentials: PRE_VALIDATION_FAILED"),
                        'Invoke-VMScript',
                        [System.Management.Automation.ErrorCategory]::AuthenticationError,
                        ""
                    )
                )
            }
            elseif ($_.Exception -match "Value cannot be found for the mandatory parameter VM" -or $_.Exception -match "Could not find VirtualMachine with name") {
                $PSCmdlet.ThrowTerminatingError(
                    [System.Management.Automation.ErrorRecord]::new(
                        ([System.Management.Automation.ItemNotFoundException]"Retrieving DNS search domains from SDDC Manager - invalid SDDC Manager appliance name: PRE_VALIDATION_FAILED"),
                        'Invoke-VMScript',
                        [System.Management.Automation.ErrorCategory]::InvalidArgument,
                        ""
                    )
                )
            }
        }
        $outputArray = ($output.Scriptoutput.Split("`r`n") | Where-Object {$_ -match "search" -and $_ -notmatch "search domains"}).Split(" ")
        $searchDomains = @()
        foreach ($item in $outputArray) {
            if ($item -notmatch "search") {
                $searchDomains += $item
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }

    if ($searchDomains) {
        return $searchDomains
    } else {
        Write-Error "Unable to locate any DNS search domains on ($sddcManagerVmName) : POST_VALIDATION_FAILED"
    }

}
Export-ModuleMember -Function Get-VCFDnsSearchDomain

#EndRegion End Cloud Foundation Functions ######
#####################################################################

#####################################################################
#Region Begin vSphere API Endpoint Functions ######

Function Request-vSphereApiToken {
    <#
        .SYNOPSIS
        Request an authentication token for the vSphere REST API

        .DESCRIPTION
        The Request-vSphereApiToken cmdlet requests an authentication token for the vSphere REST API

        use -admin to set the Admin token for vCenter Server Management Interface
        .EXAMPLE
        Request-vSphereApiToken -Fqdn sfo-w01-vc01.sfo.rainpole.io -Username administrator@vsphere.local -Password VMw@re1!
        This example requests a vSphere REST API authentication token for user administrator@vsphere.local from vCenter Server sfo-w01-vc01.sfo.rainpole.io

        .EXAMPLE
        Get-vCenterServerDetail -Server sfo-vcf01.sfo.rainpole.io -User administrator@vsphere.local -Pass VMw@re1! -Domain sfo-w01 | Request-vSphereApiToken
        This example requests a vSphere REST API authentication token for user administrator@vsphere.local from the vCenter Server that manages VI workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$admin,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psobject]$inputObject
    )

    if ($inputObject) {
        $username = $inputObject.ssoAdmin
        $password = $inputObject.ssoAdminPass
        $fqdn = $inputObject.fqdn
        $sddcManager = (Get-VCFManager).fqdn
    }
    else {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "vCenter Server FQDN not found. Please enter a value, e.g., sfo-m01-vc01.sfo.rainpole.io"
        }
    }

    Try {
        $vcAuthHeaders = createvCenterAuthHeader($username, $password)
        $Global:vcApiServer = $fqdn
        $Global:vcApiAdminServer = $fqdn + ":5480"

        # Perform the vCenter REST API call to authenticate and retrieve the session token
        if ($PsBoundParameters.ContainsKey("admin")) {
            $uri = "https://$vcApiAdminServer/rest/com/vmware/cis/session"
            if ($PSEdition -eq 'Core') {
                $vcApiAdminSession = (Invoke-WebRequest -Method 'POST' -Uri $uri -Headers $vcAuthHeaders -UseBasicParsing -SkipCertificateCheck | ConvertFrom-Json).Value
            } else {
                $vcApiAdminSession = (Invoke-WebRequest -Method 'POST' -Uri $uri -Headers $vcAuthHeaders -UseBasicParsing | ConvertFrom-Json).Value
            }
        } else {
            $uri = "https://$vcApiServer/rest/com/vmware/cis/session"
            if ($PSEdition -eq 'Core') {
                $vcApiSession = (Invoke-WebRequest -Method 'POST' -URI $uri -Headers $vcAuthHeaders -UseBasicParsing -SkipCertificateCheck | ConvertFrom-Json).Value
            } else {
                $vcApiSession = (Invoke-WebRequest -Method 'POST' -URI $uri -Headers $vcAuthHeaders -UseBasicParsing | ConvertFrom-Json).Value
            }
        }

        # Use the session token to build the header used from here on
        $Global:vcApiHeaders = @{"vmware-api-session-id" = $vcApiSession }
        $vcApiHeaders.Add("Content-Type", "application/json")

        # Use the session token to build the header for admin interface used from here on
        if ($admin){
            $Global:vcApiAdminHeaders = @{"vmware-api-session-id" = $vcApiAdminSession }
            $vcApiAdminHeaders.Add("Content-Type", "application/json")
        }

        # Validate credentials by executing an API call

        $newUri = "https://$vcApiServer/api/appliance/system/version"
        $oldUri = "https://$vcApiServer/rest/appliance/system/version"

        # Checking against the vCenter API
        # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        if ($PSEdition -eq 'Core') {
            Try {
                $response = Invoke-RestMethod -Method GET -Uri $newUri -Headers $vcApiHeaders -SkipCertificateCheck
                if ($response) {
                    $responseSplit = $response.version.Split(".")
                    $global:vCenterApi = $responseSplit[0..2] -join ""
                }
            }
            Catch {
                $errorStatus = $_.Exception.Response.StatusCode
            }
            if ($errorStatus -eq "NotFound") {
                $response = Invoke-RestMethod -Method GET -Uri $oldUri -Headers $vcApiHeaders -SkipCertificateCheck
                $responseSplit = $response.value.version.Split(".")
                $global:vCenterApi = $responseSplit[0..2] -join ""
            }
        }
        else {
            Try {
                $response = Invoke-RestMethod -Method GET -Uri $newUri -Headers $vcApiHeaders

                if ($response) {
                    $responseSplit = $response.version.Split(".")
                    $global:vCenterApi = $responseSplit[0..2] -join ""
                }
            }
            Catch {
                $errorStatus = $_.Exception.Response.StatusCode
            }

            if ($errorStatus -eq "NotFound") {
                $response = Invoke-RestMethod -Method GET -Uri $oldUri -Headers $vcApiHeaders
                $responseSplit = $response.value.version.Split(".")
                $global:vCenterApi = $responseSplit[0..2] -join ""
            }
        }
        if ($response) {
            if ($inputObject) {
                Write-Output "Successfully Requested New API Token for vCenter Server $vcApiServer via SDDC Manager $sddcManager"
            }
            else {
                Write-Output "Successfully Requested New API Token for vCenter Server $vcApiServer"
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-vSphereApiToken

Function Request-VcenterApiToken {
    <#
        .SYNOPSIS
        Request an authentication token for the vCenter Server REST API

        .DESCRIPTION
        The Request-VcenterApiToken cmdlet requests an authentication token for the vCenter Server REST API

        .EXAMPLE
        Request-VcenterApiToken -fqdn sfo-w01-vc01.sfo.rainpole.io -username administrator@vsphere.local -password VMw@re1!
        This example requests a vCenter Server REST API authentication token for user administrator@vsphere.local from vCenter Server sfo-w01-vc01.sfo.rainpole.io
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$skipCertificateCheck
    )

    if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) { # Request Credentials
        $creds = Get-Credential
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }
    if (!$PsBoundParameters.ContainsKey("fqdn")) {
        $fqdn = Read-Host "vCenter Server FQDN not found. Please enter a value, e.g., sfo-m01-vc01.sfo.rainpole.io"
    }
    if ($PsBoundParameters.ContainsKey("skipCertificateCheck")) {
        if (-not("placeholder" -as [type])) {
            add-type -TypeDefinition @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public static class Placeholder {
    public static bool ReturnTrue(object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; }

    public static RemoteCertificateValidationCallback GetDelegate() {
        return new RemoteCertificateValidationCallback(Placeholder.ReturnTrue);
    }
}
"@

} 
        [System.Net.ServicePointManager]::ServerCertificateValidationCallback = [placeholder]::GetDelegate()
    }

    Try {
        Remove-Item variable:vcenterApiSession -Force -Confirm:$false -ErrorAction Ignore
        Remove-Item variable:vcenterApiHeaders -Force -Confirm:$false -ErrorAction Ignore
        Remove-Item variable:response -Force -Confirm:$false -ErrorAction Ignore
        Remove-Item variable:errorStatus -Force -Confirm:$false -ErrorAction Ignore
        $Global:vcenterAuthHeaders = createvCenterAuthHeader ($username, $password)
        $Global:vcenterApiServer = $fqdn

        Try {
            $uri = "https://$vcenterApiServer/api/session" # Perform the vCenter REST API call to authenticate and retrieve the session token
            $response = Invoke-WebRequest -Method 'POST' -Uri $uri -Headers $vcenterAuthHeaders -UseBasicParsing
            
        } Catch {
            $errorStatus = $_.Exception
        }
        if ($response.StatusCode -eq '201') {
            $vcenterApiSession = $response | ConvertFrom-Json
        } elseif ($response.StatusCode -eq '201') {
            $vcenterApiSession = ($response | ConvertFrom-Json).Value
        }
        if ($vcenterApiSession) {
            $Global:vcenterApiHeaders = @{"vmware-api-session-id" = $vcenterApiSession } # Use the session token to build the header used from here on
            $vcenterApiHeaders.Add("Content-Type", "application/json")
            Write-Output "Successfully Requested New API Session Token for vCenter Server: $vcenterApiServer"
        }
        if ($errorStatus -match "401") {
            Write-Warning "Unable to Obtain an API Session Token from vCenter Server: $vcenterApiServer (401 Unauthorized)"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-VcenterApiToken

Function Connect-vSphereMobServer {
    <#
        .SYNOPSIS
        Connect to the vSphere Managed Object Browser (MOB)
        
        .DESCRIPTION
        The Connect-vSphereMobServer cmdlet is used to connect to the vSphere Managed Object Browser (MOB)
        
        .EXAMPLE
        Connect-vSphereMobServer -server sfo-m01-vc01.sfo.rainpole.io -username administrator@vsphere.local -password VMw@re1!
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $password
    )

    Try {
        $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
        $credential = New-Object System.Management.Automation.PSCredential($username, $securePassword)
        $Global:DefaultMobServer = @{
            Server = $server
            Credential = $credential
            skipCertificateCheck = $true
        }
        $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.GetRoles"
        $params = @{
            Uri = $uri
            SessionVariable = "mobSession"
            Credential = $Global:DefaultMobServer.Credential
            Method = "GET"
        }
        $response = Invoke-WebRequest @params -UseBasicParsing
        if ($response.StatusCode -eq 200) {
            $null = $response -match 'name="vmware-session-nonce" type="hidden" value="?([^\s^"]+)"'
            $Global:DefaultMobServer.SessionNonce = $matches[1]
            $Global:DefaultMobServer.WebSession = $mobSession
            Write-Verbose "Connected to vSphere MOB Server ($($Global:DefaultMobServer.Server))"
        }
        else {
            Throw "Failed to login to vSphere MOB Server ($($Global:DefaultMobServer.Server))"
        } 
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Connect-vSphereMobServer

Function Disconnect-vSphereMobServer {
    <#
        .SYNOPSIS
        Disconnects from the vSphere Managed Object Browser (MOB)
        
        .DESCRIPTION
        The Disconnect-vSphereMobServer cmdlet is used to disconnect from the vSphere Managed Object Browser (MOB)
        
        .EXAMPLE
        Disconnect-vSphereMobServer
    #>


    Try {
        $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/logout"
        $response = Invoke-WebRequest -Method GET -Uri $uri -WebSession $Global:DefaultMobServer.WebSession -UseBasicParsing
        $Global:DefaultMobServer.Server = $null
        $Global:DefaultMobServer.WebSession = $null
        $Global:DefaultMobServer.SessionOnce = $null
        if ($response.StatusCode -eq 200) {
            Write-Verbose "Disconnect from vSphere MOB Server ($($Global:DefaultMobServer.Server))"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Disconnect-vSphereMobServer

Function Get-VCVersion {
    <#
        .SYNOPSIS
        Get the version

        .DESCRIPTION
        The Get-VCVersion cmdlet gets the version of the vCenter Server

        .EXAMPLE
        Get-VCVersion
        This example gets the version of the vCenter Server
    #>


    Try {
        $uri = "https://$vcApiServer/api/appliance/system/version"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VCVersion

Function Get-VCConfigurationNTP {
    <#
        .SYNOPSIS
        Get NTP configuration

        .DESCRIPTION
        The Get-VCConfigurationNTP cmdlet gets the NTP configuration of vCenter Server

        .EXAMPLE
        Get-VCConfigurationNTP
        This example gets the NTP configuration of the vCenter Server
    #>


    Try {
        $uri = "https://$vcApiServer/api/appliance/ntp"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VCConfigurationNTP

Function Get-VCConfigurationDNS {
    <#
        .SYNOPSIS
        Get DNS configuration

        .DESCRIPTION
        The Get-VCConfigurationDNS cmdlet gets the DNS configuration of vCenter Server

        .EXAMPLE
        Get-VCConfigurationDNS
        This example gets the DNS configuration of the vCenter Server
    #>


    Try {
        $uri = "https://$vcApiServer/api/appliance/networking/dns/servers"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VCConfigurationDNS

Function Get-VCPasswordPolicy {
    <#
    .SYNOPSIS
        Get the global password policy.

        .DESCRIPTION
        The Get-VCPasswordPolicy cmdlet gets global password policy for the vCenter Server

        .EXAMPLE
        Get-VCPasswordPolicy
        This example gets the global password policy of the vCenter Server
    #>


    Try {
        $uri = "https://$vcApiServer/api/appliance/local-accounts/global-policy"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VCPasswordPolicy

Function Set-VCPasswordPolicy {
    <#
        .SYNOPSIS
        Set the global password policy

        .DESCRIPTION
        The Set-VCPasswordPolicy cmdlet configures the global password policy for the vCenter Server

        .EXAMPLE
        Set-VCPasswordPolicy -maxDays 120 -minDays 1 -warnDays 14
        This example configures the global password policy of the vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxDays,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$minDays,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$warnDays
    )

    Try {
        $uri = "https://$vcApiServer/api/appliance/local-accounts/global-policy"
        $body = '{ "max_days": '+$maxDays+', "min_days": '+$minDays+', "warn_days": '+$warnDays+' }'
        $response = Invoke-RestMethod -Method PUT -Uri $uri -Headers $vcApiHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-VCPasswordPolicy

Function Get-VCRootPasswordExpiry {
    <#
    .SYNOPSIS
        Get the vCenter Servver root user password expiry date.

        .DESCRIPTION
        The Get-VCRootPasswordExpiry cmdlet gets password expiration settings for the vCenter Server root account

        .EXAMPLE
        Get-VCRootPasswordExpiry
        This example gets the password policy of the vCenter Server root account
    #>


    Try {
        if ($vcenterApiHeaders) {
            $uri = "https://$vcenterApiServer/rest/appliance/local-accounts/root"
            (Invoke-RestMethod -Method GET -Uri $uri -Headers $vcenterApiHeaders).Value
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VCRootPasswordExpiry

Function Get-VCPasswordExpiry {
    <#
    .SYNOPSIS
        Get the vcenter password expiry date.

        .DESCRIPTION
        The Get-VCPasswordPolicy cmdlet gets password expiration settings for the vCenter Server root account

        .EXAMPLE
        Get-VCPasswordExpiry
        This example gets the password policy of the vCenter Server
    #>


    Try {
        $uri = "https://$vcApiAdminServer/rest/appliance/local-accounts/root"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiAdminHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VCPasswordExpiry

Function Set-VCPasswordExpiry {
    <#
        .SYNOPSIS
        Set the vcenter password expiry date

        .DESCRIPTION
        The Set-VCPasswordExpiry cmdlet configures password expiration settings for the vCenter Server root account

        .EXAMPLE
        Set-VCPasswordExpiry -passwordExpires $true -email "admin@rainpole.io" -maxDaysBetweenPasswordChange 91
        This example configures the configures password expiration settings for the vCenter Server root account

        Set-VCPasswordExpiry -passwordExpires $false
        This example configures the configures password expiration settings for the vCenter Server root account to never expire
    #>


    Param (
        [Parameter (Mandatory = $false, ParameterSetName = 'neverexpire')] [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [Bool]$passwordExpires,
        [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$email,
        [Parameter (Mandatory = $true, ParameterSetName = 'expire')] [ValidateNotNullOrEmpty()] [String]$maxDaysBetweenPasswordChange
    )

    Try {
        $uri = "https://$vcApiAdminServer/rest/appliance/local-accounts/root"

        if ($passwordExpires) {
            $body = '{"config":{"password_expires": "'+ $passwordExpires +'", "email": "'+ $email+ '", "max_days_between_password_change": "' + $maxDaysBetweenPasswordChange + '" }}'
        }
        else {
            $body = '{"config":{"password_expires": "'+ $passwordExpires + '"}}'
        }
        $response = Invoke-RestMethod -Method PATCH -Uri $uri -Headers $vcApiAdminHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-VCPasswordExpiry

Function Get-GlobalPermission {
    <#
        .SYNOPSIS
        Get vSphere Global Permission

        .DESCRIPTION
        The Get-GlobalPermission cmdlet gets a list of vSphere Global Permission

        .EXAMPLE
        Get-GlobalPermission
        This example shows how to gets a list of vSphere Global Permission
    #>


    Try {
        $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.GetGlobalAccessControlList"
        $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)"
        $params = @{
            Uri = $uri
            WebSession = $Global:DefaultMobServer.WebSession
            Credential = $Global:DefaultMobServer.Credential
            Method = "POST"
            Body = $body
            UseBasicParsing = $false
        }
        $response = Invoke-WebRequest @params
        $vsphereRoles = Get-VIRole | Select-Object Name, @{N="Id";E={@($_.Id)}} # Gather vSphere Roles and their Id
        $roleLookup = @{}
            foreach ($role in $vsphereRoles) {
                $roleLookup."$($role.Id)" = $role.Name
            }
        # Extract the data from the parsed HTML
        $table = $response.ParsedHtml.body.getElementsByTagName("table")[3]
        $td = $table.getElementsByTagName("tr")[4].getElementsByTagName("td")[2]
        $li = $td.getElementsByTagName("ul")[0].getElementsByTagName("li")
            
        foreach ($item in $li) {
            if ($item.innerHTML.StartsWith("<TABLE")) {
                $principalTable = $item.getElementsByTagName("tr")[3].getElementsByTagName("td")[2].getElementsByTagName("table")[0]
                $principal = $principalTable.getElementsByTagName("tr")[4].getElementsByTagName("td")[2].innerText
                $isGroup = $principalTable.getElementsByTagName("tr")[3].getElementsByTagName("td")[2].innerText
                $type = Switch ($isGroup) {
                    $true {"group"}
                    $false {"user"}
                }
                $role = $item.getElementsByTagName("tr")[10].getElementsByTagName("li")[0].innerText
                $propagate = $item.getElementsByTagName("tr")[9].getElementsByTagName("td")[2].innerText
    
                [PSCustomObject] @{
                    Principal = $principal
                    Type = $type
                    Role = $RoleLookup.$($Role)
                    Propagate = $propagate
                }
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-GlobalPermission

Function Add-GlobalPermission {
    <#
        .SYNOPSIS
        Add a vSphere Global Permission

        .DESCRIPTION
        The Add-GlobalPermission cmdlet adds a new user or group a vSphere Global Permission

        .EXAMPLE
        Add-GlobalPermission -principal gg-vc-admins -roleId -1 -propagate true -type group
        This example shows how to add the Administrator global permission to a group called svc-vc-admins
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId,
        [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [String]$propagate,
        [Parameter (Mandatory = $true)] [ValidateSet("group","user")] [String]$type
    )

    Try {
        $userEscaped = [uri]::EscapeUriString($principal) # Escape username
        $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.AddGlobalAccessControlList" # vSphere MOB URL to private enableMethods
        # The POST data payload must include the vmware-session-nonce variable + URL-encoded
        if ($type -eq "group") {
            $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A++++++%3Cgroup%3Etrue%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++%3Croles%3E$roleId%3C%2Froles%3E%0D%0A+++%3Cpropagate%3E$propagate%3C%2Fpropagate%3E%0D%0A%3C%2Fpermissions%3E"
        }
        else {
            $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A++++++%3Cgroup%3Efalse%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++%3Croles%3E$roleId%3C%2Froles%3E%0D%0A+++%3Cpropagate%3E$propagate%3C%2Fpropagate%3E%0D%0A%3C%2Fpermissions%3E"
        }
        $params = @{
            Uri = $uri
            WebSession = $Global:DefaultMobServer.WebSession
            Credential = $Global:DefaultMobServer.Credential
            Method = "POST"
            Body = $body
            UseBasicParsing = $true
        }
        $response = Invoke-WebRequest @params
        if ($response.StatusCode -eq 200) {
            Write-Verbose "Successfully added vCenter Global Permission for ($principal)"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-GlobalPermission

Function Remove-GlobalPermission {
    <#
        .SYNOPSIS
        Remove a vSphere Global Permission

        .DESCRIPTION
        The Remove-GlobalPermission cmdlet removes a user or group from a vSphere Global Permission

        .EXAMPLE
        Remove-GlobalPermission -principal gg-vc-admins -type group
        This example shows how to remove the Administrator global permission from the group called svc-vc-admins
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateSet("group","user")] [String]$type
    )

    Try {
        $userEscaped = [uri]::EscapeUriString($principal) # Escape username
        $uri = "https://$($Global:DefaultMobServer.Server)/invsvc/mob3/?moid=authorizationService&" + "method=AuthorizationService.RemoveGlobalAccess"
        if ($type -eq "group") {
            $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&principals=%3Cprincipals%3E%0D%0A+++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A+++%3Cgroup%3Etrue%3C%2Fgroup%3E%0D%0A%3C%2Fprincipals%3E"
        }
        else {
            $body = "vmware-session-nonce=$($Global:DefaultMobServer.SessionNonce)&principals=%3Cprincipals%3E%0D%0A+++%3Cname%3E$userEscaped%3C%2Fname%3E%0D%0A+++%3Cgroup%3Efalse%3C%2Fgroup%3E%0D%0A%3C%2Fprincipals%3E"
        }     
        $params = @{
            Uri = $uri
            WebSession = $Global:DefaultMobServer.WebSession
            Credential = $Global:DefaultMobServer.Credential
            Method = "POST"
            Body = $body
            UseBasicParsing = $true
        }
        $response = Invoke-WebRequest @params
        if ($response.StatusCode -eq 200) {
            Write-Verbose "Successfully removed vCenter Gobal Permission for ($principal)"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-GlobalPermission

Function Get-SsoPasswordPolicies {
    <#
        .SYNOPSIS
        Get vSphere Single-Sign On password policies

        .DESCRIPTION
        The Get-SsoPasswordPolicies cmdlet gets the vSphere Single-Sign On password policies

        .EXAMPLE
        Get-SsoPasswordPolicies -ssoAdminPass VMw@re1! -ssoDomain vsphere.local -vmName sfo-m01-vc01 -rootPass VMw@re1!
        This example shows how to get vSphere Single-Sign On password policies
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoAdminPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoDomain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass
    )

    Try {
        $a, $b = $ssoDomain.split(".")
        $scriptCommand = "/opt/likewise/bin/ldapsearch -h localhost -w $ssoAdminPass -x -D `"cn=Administrator,cn=Users,dc=$a,dc=$b`" -b `"cn=password and lockout policy,dc=$a,dc=$b`" | grep vmwPassword"
        $output = Invoke-VMScript -ScriptText $scriptCommand -vm $vmName -GuestUser "root" -GuestPassword $rootPass
        $output.scriptOutput
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-SsoPasswordPolicies

Function Add-DrsVmToVmGroup {
    <#
        .SYNOPSIS
        Creates a vSphere VM to VM Group

        .DESCRIPTION
        The Add-DrsVmToVmGroup cmdlet creates a vSphere VM to VM Group

        .EXAMPLE
        Add-DrsVmToVmGroup -name vm-vm-rule-wsa-vra -vmGroup sfo-m01-vm-group-wsa -dependOnVmGroup sfo-m01-vm-group-vra -Enabled -cluster sfo-m01-cl01
        This example shows how to create a vSphere VM to VM group in the vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmGroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$dependOnVmGroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$enabled=$true
    )

    Try {
        $updateCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster}

        $spec = New-Object VMware.Vim.ClusterConfigSpecEx
        $spec.RulesSpec = New-Object VMware.Vim.ClusterRuleSpec[] (1)
        $spec.RulesSpec[0] = New-Object VMware.Vim.ClusterRuleSpec
        $spec.RulesSpec[0].Operation = 'add'
        $spec.RulesSpec[0].Info = New-Object VMware.Vim.ClusterDependencyRuleInfo
        $spec.RulesSpec[0].Info.DependsOnVmGroup = $dependOnVmGroup
        $spec.RulesSpec[0].Info.VmGroup = $vmGroup
        $spec.RulesSpec[0].Info.Name = $name
        $spec.RulesSpec[0].Info.UserCreated = $true
        $spec.RulesSpec[0].Info.Enabled = $true

        $ClusterToReconfig = Get-View -Id $updateCluster.ExtensionData.MoRef
        $ClusterToReconfig.ReconfigureComputeResource_Task($spec, $true)
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-DrsVmToVmGroup

Function Remove-DrsVmToVmGroup {
    <#
        .SYNOPSIS
        Remove a vSphere VM to VM Group

        .DESCRIPTION
        The Remove-DrsVmToVmGroup cmdlet removes a vSphere VM to VM Group

        .EXAMPLE
        Remove-DrsVmToVmGroup -name vm-vm-rule-wsa-vrli -cluster sfo-m01-cl01
        This example shows how to remove a vSphere VM to VM group from vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster
    )

    Try {
        $updateCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster}

        $spec = New-Object VMware.Vim.ClusterConfigSpecEx
        $spec.RulesSpec = New-Object VMware.Vim.ClusterRuleSpec[] (1)
        $spec.RulesSpec[0] = New-Object VMware.Vim.ClusterRuleSpec
        $spec.RulesSpec[0].RemoveKey = (Get-DrsVmToVmGroup -name $name -cluster $cluster).Key
        $spec.RulesSpec[0].Operation = 'remove'
    
        $ClusterToReconfig = Get-View -Id $updateCluster.ExtensionData.MoRef
        $ClusterToReconfig.ReconfigureComputeResource_Task($spec, $true)
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-DrsVmToVmGroup

Function Get-DrsVmToVmGroup {
    <#
        .SYNOPSIS
        Gets all vSphere VM to VM Group

        .DESCRIPTION
        The Get-DrsVmToVmGroup cmdlet retrieves the vSphere VM to VM Group

        .EXAMPLE
        Get-DrsVmToVmGroup -name vm-vm-rule-wsa-vra -cluster sfo-m01-cl01
        This example shows how to retrieve a vSphere VM to VM group in the vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster
    )

    Try {
        $getCluster = Get-Cluster | Where-Object {$_.Name -eq $cluster}
        if ($PsBoundParameters.ContainsKey("name")){
            $getCluster.ExtensionData.Configuration.Rule | Where-Object {$_.Name -eq $name}
        }
        else {
            $getCluster.ExtensionData.Configuration.Rule
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-DrsVmToVmGroup

Function Get-VcLicense {
    <#
        .SYNOPSIS
        Get list of licenses in vCenter Server

        .DESCRIPTION
        The Get-VcLicense cmdlet gets a list of licenses in vCenter Server

        .EXAMPLE
        Get-VcLicense
        This example shows how to get a list of licenses in vCenter Server
    #>


    Try {
        $licenseManager = Get-View LicenseManager
        $LicenseManager.Licenses
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VcLicense

Function New-VcLicense {
    <#
        .SYNOPSIS
        Add a license to vCenter Server

        .DESCRIPTION
        The New-VcLicense cmdlet adds a license to vCenter Server

        .EXAMPLE
        New-VcLicense -licenseKey <license_key>
        This example shows how to add a license to vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$licenseKey
    )

    Try {
        $licenseManager = Get-View LicenseManager
        $licenseManager.AddLicense($licenseKey,$null)
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-VcLicense

Function Remove-VcLicense {
    <#
        .SYNOPSIS
        Remove a license from vCenter Server

        .DESCRIPTION
        The Remove-VcLicense cmdlet removes a license from vCenter Server

        .EXAMPLE
        Remove-VcLicense -licenseKey <license_key>
        This example shows how to remove a license from vCenter Server
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$licenseKey
    )

    Try {
        $licenseManager = Get-View LicenseManager
        $licenseManager.RemoveLicense($licenseKey)
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-VcLicense

Function Get-SubscribedLibrary {
    <#
        .SYNOPSIS
        Retrieves the specified Subscribed Content Library

        .DESCRIPTION
        The Get-SubscribedLibrary cmdlet retrieves the specified Subscribed Content Library

        .EXAMPLE
        Get-SubscribedLibrary -name Kubernetes
        This example retrieves the Subscribed Content Library named Kubernetes
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name
    )

    Try {    
        $body = '{ "name": "' + $name + '", "type": "SUBSCRIBED" }' 
        $subscribedLibraryId = Invoke-RestMethod -Method POST -Uri "https://$vcApiServer/api/content/library?action=find" -Headers $vcApiHeaders -body $body
        $return = Invoke-RestMethod -Method GET -URI "https://$vcApiServer/api/content/subscribed-library/$subscribedLibraryId" -Headers $vcApiHeaders
        $return
    }
    Catch {
        Write-Error $_.Exception.Message 
    }
}
Export-ModuleMember -Function Get-SubscribedLibrary

Function Get-VcenterBackupStatus {
    <#
        .SYNOPSIS
        Returns a list of all backup jobs performed on a vCenter Server instance.

        .DESCRIPTION
        The Get-VcenterBackupStatus cmdlet returns a list of all backups performed on a vCenter Server instance.

        .EXAMPLE
        Get-VcenterBackupStatus | Select-Object -Last 1
        This example demonstrates piping the results of this function into Select-Object to return the status of the last backup.
    #>


    Try {
        if ($vcenterApiHeaders) {
            $uri = "https://$vcenterApiServer/rest/appliance/recovery/backup/job/details"
            (Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vcenterApiHeaders).Value
        }
    }
    Catch {
        $errorStatus = $_.Exception
    }
}
Export-ModuleMember -Function Get-VcenterBackupStatus

Function Get-SnapshotStatus {
    <#
        .SYNOPSIS
        Returns the status of a virtual machine's snapshots.

        .DESCRIPTION
        The Get-SnapshotStatus cmdlet returns the status of a virtual machine's snapshots.

        .EXAMPLE
        Get-SnapshotStatus -vm "foo"
        This example returns the status of the snapshots for the virtual machine named "foo".
    #>


    Param (
        [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vm
    )

    Try {
        $response = Get-VM $vm | Get-Snapshot | Select-Object -Property Name, Created, isCurrent # Get the snapshot details
        $response # Return the snapshot details
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-SnapshotStatus

Function Get-SnapshotConsolidation {
    <#
        .SYNOPSIS
        Returns the status of a virtual machine's need for snapshot consolidation.

        .DESCRIPTION
        The Get-SnapshotConsolidation cmdlet returns the status of a virtual machine's need for snapshot consolidation.

        .EXAMPLE
        Get-SnapshotConsolidation -vm "foo"
        This example returns the status of the snapshot consolidation for the virtual machine named "foo".
    #>


    Param (
        [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vm
    )

    Try {
        $response = (Get-View -ViewType VirtualMachine -Filter @{'Name' = $vm }).Runtime.ConsolidationNeeded # Get the consolidation status
        $response # Return the consolidation status
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-SnapshotConsolidation

Function Get-EsxiAlert {
    <#
        .SYNOPSIS
        Returns the triggered alarms for an ESXi host.

        .DESCRIPTION
        The Get-EsxiAlert cmdlet returns all triggered alarms for ESXi host.

        .EXAMPLE
        Get-EsxiAlert -host sfo-w01-esx01.sfo.rainpole.io
        This example returns all triggered alarms for and ESXi host named sfo-w01-esx01.sfo.rainpole.io.
    #>


    Param (

        [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$host
    )
    $vmhosts = Get-VMHost
    $vmhost = $vmhosts | Where-Object {$_.name -eq $host}
    foreach ($triggeredAlarm in $vmhost.ExtensionData.TriggeredAlarmState) {
        $alarm = "" | Select-Object Entity, Alarm, Status, Time, Acknowledged, AckBy, AckTime
        $alarm.Alarm = (Get-AlarmDefinition -id $triggeredAlarm.alarm).name
        $alarm.Entity =  ( $vmhosts | Where-Object {$_.id -eq $triggeredAlarm.Entity} ).name # or just $host
        $alarm.Status = $triggeredAlarm.OverallStatus
        $alarm.Time = $triggeredAlarm.Time
        $alarm.Acknowledged = $triggeredAlarm.Acknowledged
        $alarm.AckBy = $triggeredAlarm.AcknowledgedByUser
        $alarm.AckTime = $triggeredAlarm.AcknowledgedTime
        $alarm
    }
}
Export-ModuleMember -Function Get-EsxiAlert

Function Get-VsanHealthTest {
    <#
        .SYNOPSIS
        Returns the vSAN healthcheck tests from a vSAN cluster in vCenter Server.

        .DESCRIPTION
        The Get-VsanHealthTest cmdlet returns all vSAN healthcheck tests from a VSAN cluster in vCenter Server.

        .EXAMPLE
        Get-VsanHealthTest -cluster sfo-m01-c01
        This example returns all vSAN healthcheck tests from vSAN cluster sfo-m01-c01 in connected vCenter Server.
    #>


    Param (
        [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster
    )

    $vsanClusterHealthSystem = Get-VSANView -Id "VsanVcClusterHealthSystem-vsan-cluster-health-system"
    $clusterView = (Get-Cluster -Name $cluster).ExtensionData.MoRef
    $results = $vsanClusterHealthSystem.VsanQueryVcClusterHealthSummary($clusterView,$null,$null,$true,$null,$null,'defaultView')
    $healthCheckGroups = $results.groups
    
    $healthTests = New-Object System.Collections.ArrayList
    
    foreach ($healthCheckGroup in $healthCheckGroups) {
        foreach ($test in $healthCheckGroup.GroupTests) {
            $testResult = [pscustomobject] @{
                GroupName = $healthCheckGroup.GroupName
                TestName = $test.TestName
                TestHealth = $test.TestHealth.ToUpper()
            }
            $healthTests += $testResult
        }
    }
    $healthTests 
}
Export-ModuleMember -Function Get-VsanHealthTest

Function Get-VcenterTriggeredAlarm {
    <#
        .SYNOPSIS
        Returns the triggered alarms for a vCenter Server instance.

        .DESCRIPTION
        The Get-VcenterTriggeredAlarm cmdlet returns all triggered alarms from vCenter Server instance.

        .EXAMPLE
        Get-VcenterTriggeredAlarm -server sfo-w01-vc01.sfo.rainpole.io
        This example returns all triggered alarms for a vCenter Server instance named sfo-w01-vc01.sfo.rainpole.io.
    #>


    Param (
        [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    $rootFolder = Get-Folder -Server $server "Datacenters"
    foreach ($triggeredAlarm in $rootFolder.ExtensionData.TriggeredAlarmState) {
        $alarm = "" | Select-Object EntityType, Alarm, Status, Time, Acknowledged, AckBy, AckTime
        $alarm.Alarm = (Get-View -Server $server $triggeredAlarm.Alarm).Info.Name
        $alarm.EntityType = (Get-View -Server $server $triggeredAlarm.Entity).GetType().Name
        $alarm.Status = $triggeredAlarm.OverallStatus
        $alarm.Time = $triggeredAlarm.Time
        $alarm.Acknowledged = $triggeredAlarm.Acknowledged
        $alarm.AckBy = $triggeredAlarm.AcknowledgedByUser
        $alarm.AckTime = $triggeredAlarm.AcknowledgedTime
        $alarm
    }
}
Export-ModuleMember -Function Get-VcenterTriggeredAlarm

#EndRegion End vSphere API Endpoint Functions ######
#####################################################################

#####################################################################
#Region Begin Workspace ONE Access Functions ######

Function Request-WSAToken {
    <#
        .SYNOPSIS
        Connects to the specified Workspace ONE Access instance to obtain a session token

        .DESCRIPTION
        The Request-WSAToken cmdlet connects to the specified Workspace ONE Access instance and requests a session token

        .EXAMPLE
        Request-WSAToken -fqdn sfo-wsa01.sfo.rainpole.io -user admin -pass VMware1!
        This example shows how to connect to a Workspace ONE Access instance and request a session token
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    If ( -not $PsBoundParameters.ContainsKey("user") -or ( -not $PsBoundParameters.ContainsKey("pass"))) {
        # Request Credentials
        $creds = Get-Credential
        $user = $creds.UserName.ToString()
        $pass = $creds.GetNetworkCredential().password
    }

    $Global:workSpaceOne = $fqdn

    # Validate credentials by executing an API call
    $wsaHeaders = @{"Content-Type" = "application/json" }
    $wsaHeaders.Add("Accept", "application/json; charset=utf-8")
    $uri = "https://$workSpaceOne/SAAS/API/1.0/REST/auth/system/login"
    $body = '{"username": "' + $user + '", "password": "' + $pass + '", "issueToken": "true"}'

    Try {
        # Checking against the API
        # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        if ($PSEdition -eq 'Core') {
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body -SkipCertificateCheck
            $Global:sessionToken = "HZN " + $response.sessionToken
        }
        else {
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body
            $Global:sessionToken = "HZN " + $response.sessionToken
        }
        if ($response.sessionToken) {
            Write-Output "Successfully Requested New Session Token From Workspace ONE Access instance: $fqdn"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-WSAToken

Function Get-WSAIdentityProvider {
    <#
        .SYNOPSIS
        Get identity providers

        .DESCRIPTION
        The Get-WSAIdentityProvider cmdlets retrieves a list of identity providers in Workspace ONE Access

        .EXAMPLE
        Get-WSAIdentityProvider
        This example retrives a list of identity providers in Workspace ONE Access
    #>


    Try {
        $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.identityprovider.summary.list+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/identityProviders?onlyEnabledAdapters=true"
        $response = Invoke-RestMethod -Uri $uri -Method 'GET' -Headers $wsaHeaders
        $response.items
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAIdentityProvider

Function Get-WSAConnector {
    <#
        .SYNOPSIS
        Get connectors

        .DESCRIPTION
        The Get-WSAConnector cmdlets retrieves a list of connectors in Workspace ONE Access

        .EXAMPLE
        Get-WSAConnector
        This example retrives a list of connectors in Workspace ONE Access
    #>


    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.connector+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
        $response.items
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAConnector

Function Add-WSAConnector {
    <#
        .SYNOPSIS
        Add connector to identity providor

        .DESCRIPTION
        The Add-WSAConnector cmdlets adds a connector to an identity providoer in Workspace ONE Access

        .EXAMPLE
        Add-WSAConnector -wsaFqdn xint-wsa01b.rainpole.io -domain sfo.rainpole.io -bindUserPass VMw@re1!
        This example adds a connector to an identity providoer in Workspace ONE Access
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaNode,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindUserPass
    )

    Try {
        $identityProviderId = (Get-WSAIdentityProvider | Where-Object {$_.directoryConfigurations.name -eq $domain}).id
        $directoryId = (Get-WSADirectory | Where-Object {$_.name -eq $domain}).directoryId
        $connectorId = (Get-WSAConnector | Where-Object {$_.host -eq $wsaNode}).instanceId

        $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.connector.management.connector+json"}
        $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.connector.management.directory.bindDetails+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances/$connectorId/associatedirectory?idp=$identityProviderId"
        $body = '{"directoryId": "' + $directoryId + '", "directoryBindPassword":"' + $bindUserPass + '", "usedForAuthentication":true, "bindToAD":true}'
        $response = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $wsaHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-WSAConnector

Function Get-WSADirectory {
    <#
        .SYNOPSIS
        Get diretories

        .DESCRIPTION
        The Get-WSADirectory cmdlets retrieves all directories in Workspace ONE Access

        .EXAMPLE
        Get-WSADirectory
        This example retrives a list of directories in Workspace ONE Access

        .EXAMPLE
        Get-WSADirectory -connector
        This example retrives a list of connectors for a directory in Workspace ONE Access
    #>


    Param (
        [Parameter (ParameterSetName = "connector", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$directoryId,
        [Parameter (ParameterSetName = "connector",Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$connector
    )

    Try {
        if ($PsBoundParameters.ContainsKey("connector")){
            $wsaHeaders = @{"Accept" = ""}
            $wsaHeaders.Add("Authorization", "$sessionToken")
            $uri = "https://xint-wsa01.rainpole.io/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/connectors"
            $response = Invoke-RestMethod -Uri $uri -Method 'GET' -Headers $wsaHeaders
            $response.items
        }
        else {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json" }
            $wsaHeaders.Add("Authorization", "$sessionToken")
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs"
            $response = Invoke-RestMethod -Uri $uri -Method 'GET' -Headers $wsaHeaders
            $response.items
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSADirectory

Function Get-WSADirectoryDomain {
    <#
        .SYNOPSIS
        Get directory domains

        .DESCRIPTION
        The Get-WSADirectoryDomain cmdlets retrieves a list of directory domains in Workspace ONE Access

        .EXAMPLE
        Get-WSADirectoryDomain -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac
        This example retrives a list of directory domains in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$directoryId
    )

    Try {
        $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.connector.management.directory.domain.list+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/domains"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
        $response.items
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSADirectoryDomain

Function Add-WSALdapDirectory {
    <#
        .SYNOPSIS
        Create an LDAP directory

        .DESCRIPTION
        The Add-WSALdapDirectory cmdlets creates a new LDAP Active Directory connection in Workspace ONE Access

        .EXAMPLE
        Add-WSALdapDirectory -domainName sfo.rainpole.io -baseDn "ou=VVD,dc=sfo,dc=rainpole,dc=io" -bindDn "cn=svc-wsa-ad,ou=VVD,dc=sfo,dc=rainpole,dc=io"
        This example creates a new LDAP Active Directory connection in Workspace ONE Access
      #>

    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$baseDn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$bindDn,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificate
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json" }
        $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.ad.over.ldap+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        if ($PsBoundParameters.ContainsKey("certificate")){
            #read certificate file contents as certdata
            $certdata = (Get-Content ($certificate)) -join "\n"
            $body = '{
                "useSRV":true,
                "directoryType":"ACTIVE_DIRECTORY_LDAP",
                "directorySearchAttribute":"sAMAccountName",
                "directoryConfigId":null,
                "useGlobalCatalog":false,
                "syncConfigurationEnabled":false,
                "useStartTls":true,
                "userAttributeMappings":[],
                "name":"'
 + $domainName + '",
                "baseDN":"'
 + $baseDn + '",
                "bindDN":"'
 + $bindDn + '",
                "sslCertificate":"'
 + $certdata + '"
            }'

        }else{
            $body = '{
                "useSRV":true,
                "directoryType":"ACTIVE_DIRECTORY_LDAP",
                "directorySearchAttribute":"sAMAccountName",
                "directoryConfigId":null,
                "useGlobalCatalog":false,
                "syncConfigurationEnabled":false,
                "useStartTls":false,
                "userAttributeMappings":[],
                "name":"'
 + $domainName + '",
                "baseDN":"'
 + $baseDn + '",
                "bindDN":"'
 + $bindDn + '"
            }'

        }
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs"
        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-WSALdapDirectory

Function Set-WSABindPassword {
    <#
        .SYNOPSIS
        Create an LDAP directory

        .DESCRIPTION
        The Set-WSABindPassword cmdlets creates a new LDAP Active Directory connection in Workspace ONE Access

        .EXAMPLE
        Set-WSABindPassword -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -connectorId 59ee9717-a09e-45b6-9e5f-8d92a55a1825 -password VMw@re1!
        This example creates a new LDAP Active Directory connection in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$connectorId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.details+json" }
        $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.connector+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $body = '{"directoryId":"' + $directoryId + '","directoryBindPassword":"' + $pass + '","usedForAuthentication":true}'
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/connectorinstances/$connectorId/associatedirectory"
        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSABindPassword

Function Set-WSASyncSetting {
    <#
        .SYNOPSIS
        Set directory sync schedule

        .DESCRIPTION
        The Set-WSASyncSetting cmdlets configures the directory sync schedule in Workspace ONE Access

        .EXAMPLE
        Set-WSASyncSetting -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac
        This example configures the directory sync schedule in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.syncschedule+json" }
        $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.syncschedule+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $body = '{"frequency":"fifteenMinutes"}'
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile"
        Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSASyncSetting

Function Start-WSADirectorySync {
    <#
        .SYNOPSIS
        Start an directory sync

        .DESCRIPTION
        The Start-WSADirectorySync cmdlets triggers a directory sync in Workspace ONE Access

        .EXAMPLE
        Start-WSADirectorySync -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac
        This example starts a directory sync in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.sync+json" }
        $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.v1.0+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $body = '{"ignoreSafeguards":true}'
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile/sync"
        Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Start-WSADirectorySync

Function Set-WSADirectoryUser {
    <#
        .SYNOPSIS
        Add users to directory

        .DESCRIPTION
        The Set-WSADirectoryUser cmdlets configures the user/ou that should be sycncronised for Workspace ONE Access

        .EXAMPLE
        Set-WSADirectoryUser -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -json (Get-Content -Raw .\adUsers.json)
        This example configures the user/ou that should be sycncronised for Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.users+json" }
        $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.users+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile"
        Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $json
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSADirectoryUser

Function Set-WSADirectoryGroup {
    <#
        .SYNOPSIS
        Add groups to directory

        .DESCRIPTION
        The Set-WSADirectoryGroup cmdlets configures the groups/ou that should be sycncronised for Workspace ONE Access

        .EXAMPLE
        Set-WSADirectoryUser -directoryId a1c985d5-0eeb-4a66-bc51-11eda9321aac -json (Get-Content -Raw .\adGroups.json)
        This example configures the groups/ou that should be sycncronised for Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$directoryId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.groups+json" }
        $wsaHeaders.Add("Accept", "application/vnd.vmware.horizon.manager.connector.management.directory.sync.profile.groups+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$directoryId/syncprofile"
        $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSADirectoryGroup

Function Get-WSASmtpConfiguration {
    <#
        .SYNOPSIS
        Get SMTP configuration

        .DESCRIPTION
        The Get-WSASmtpConfiguration cmdlets retrieves the SMTP configurtion of Workspace ONE Access

        .EXAMPLE
        Get-WSASmtpConfiguration
        This example gets the current SMTP configuration of Workspace ONE Access
      #>


    Try {
        $wsaHeaders = @{"Accept" = "application/json, text/plain, */*" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/system/config/smtp"
        $response = Invoke-RestMethod $uri -Headers $wsaHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSASmtpConfiguration

Function Set-WSASmtpConfiguration {
    <#
        .SYNOPSIS
        Set SMTP configuration

        .DESCRIPTION
        The Set-WSASmtpConfiguration cmdlets configures the SMTP configurtion of Workspace ONE Access

        .EXAMPLE
        Set-WSASmtpConfiguration
        This example sets the SMTP configuration of Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        $wsaHeaders = @{"Accept" = "application/json, text/plain, */*" }
        $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.system.config.smtp+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        if (-not $PsBoundParameters.ContainsKey("pass")) {
            $body = '{ "host": "' + $fqdn + '", "port": ' + $port + ', "user": "' + $user + '", "password": "' + $pass + '"}'
        }
        else {
            $body = '{ "host": "' + $fqdn + '", "port": ' + $port + ', "user": "' + $user + '" }'
        }
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/system/config/smtp"
        $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSASmtpConfiguration

Function Set-WSARoleMember {
    <#
        .SYNOPSIS
        Set WSA Role Member

        .DESCRIPTION
        The Set-WSARoleMember cmdlets updates the Role with the given group

        .EXAMPLE
        Set-WSARoleMember -id 55048dee-fe1b-404a-936d-3e0b86a7209e -groupId fe515568-fdcd-43c7-9971-e834d7246203
        This example updates the Role with the given GroupId in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles/$id"

               $json = @"
                        {
                  "schemas": [
                    "urn:scim:schemas:core:1.0"
                  ],
                  "members": [
                    {
                      "value": "$groupId",
                      "type": "Group"
                    }
                  ]
                }
"@

            $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -body $json -headers $wsaHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSARoleMember

Function Get-WSARole {
    <#
        .SYNOPSIS
        Get roles

        .DESCRIPTION
        The Get-WSARole cmdlets retrieves the roles in Workspace ONE Access

        .EXAMPLE
        Get-WSARole
        This example retrieves the roles in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles/$id"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response
        }
        else {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Roles"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response.Resources
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSARole

Function Get-WSAGroup {
    <#
        .SYNOPSIS
        Get groups

        .DESCRIPTION
        The Get-WSAGroup cmdlets retrieves the groups in Workspace ONE Access

        .EXAMPLE
        Get-WSAGroup
        This example retrieves the groups in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups/$id"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response
        }
        else {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response.Resources
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAGroup

Function Get-WSAUser {
    <#
        .SYNOPSIS
        Get users

        .DESCRIPTION
        The Get-WSAUser cmdlets retrieves the users in Workspace ONE Access

        .EXAMPLE
        Get-WSAUser
        This example retrieves the users in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Users/$id"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response
        }
        else {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Users"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response.Resources
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAUser

Function Get-WSARuleSet {
    <#
        .SYNOPSIS
        Get rulesets

        .DESCRIPTION
        The Get-WSARuleSet cmdlets retrieves the rulesets in Workspace ONE Access

        .EXAMPLE
        Get-WSARuleSet
        This example retrieves the rulesets in Workspace ONE Access
      #>


    Try {
        $wsaHeaders = @{"Accept-Type" = "application/json, text/plain, */*" }
        $wsaHeaders.Add("Content-Type", "application/vnd.vmware.vidm.accesscontrol.ruleset.list+json")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/acs/rulesets"
        $response = Invoke-RestMethod $uri -Headers $wsaHeaders
        $response.items
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSARuleSet

Function Get-WSAOAuthToken {
    <#
        .SYNOPSIS
        Get AOuth Token

        .DESCRIPTION
        The Get-WSAOAuthToken cmdlets gets an OAuth token from Workspace ONE Access

        .EXAMPLE
        Get-WSAOAuthToken
        This example retrieves the am OAuth oken from Workspace ONE Access
      #>


    Try {
        $wsaHeaders = @{"Content-Type" = "application/x-www-form-urlencoded; charset=UTF-8" }
        $wsaHeaders.Add("Accept", "application/json, text/javascript, */*; q=0.01")
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/admin/settings/OAuthClient/generateRandomOAuthSecret"
        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAOAuthToken

Function Get-WSAClient {
    <#
        .SYNOPSIS
        Get clients

        .DESCRIPTION
        The Get-WSAClient cmdlets gets a list of clients in Workspace ONE Access

        .EXAMPLE
        Get-WSAClient
        This example retrieves all clients in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clientId
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.oauth2client+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        if ($PsBoundParameters.ContainsKey("clientId")) {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients/$clientId"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response
        }
        else {
            $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
            $response.items
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAClient

Function Add-WSAClient {
    <#
        .SYNOPSIS
        Add a client

        .DESCRIPTION
        The Add-WSAClient cmdlets add a client in Workspace ONE Access

        .EXAMPLE
        Add-WSAClient -json .\SampleJson\nsxClient.json
        This example retrieves all clients in Workspace ONE Access
      #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clientId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sharedSecret
    )

    Try {
        $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.horizon.manager.oauth2client+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $body = '{
            "clientId": "'
 + $clientId + '",
            "secret": "'
 + $sharedSecret + '",
            "scope": "admin",
            "authGrantTypes": "refresh_token client_credentials",
            "redirectUri": "",
            "tokenType": "Bearer",
            "tokenLength": 32,
            "accessTokenTTL": 8,
            "refreshTokenTTL": 1440,
            "refreshTokenIdleTTL": 4,
            "rememberAs": "'
 + $clientId + '",
            "displayUserGrant": false,
            "internalSystemClient": false,
            "inheritanceAllowed": true
        }'

        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/oauth2clients"
        Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-WSAClient

Function Add-WSARoleAssociation {
    <#
       .SYNOPSIS
       Add the AD group to the WSA role

       .DESCRIPTION
       Add the AD group to the given WSA role.

       .EXAMPLE
       Add-WSARoleAssociation -roleId "1d0b09a1-8744-4f85-8c4f-ac104e586010" -groupId "1e942dc6-94ba-43ef-97ce-9ba34fee1609"
   #>


   Param (
       [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId,
       [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId
   )

   Try {
       $wsaHeaders = @{"Content-Type" = "application/vnd.vmware.vidm.accesscontrol.ruleset.associations.bulk.request+json" }
       $wsaHeaders.Add("Authorization", "$sessionToken")
       $uri = "https://$workSpaceOne/acs/associations/rulesets/$roleId"
       $body = '{
                   "operations": [
                               {
                               "users": [],
                               "groups": [
                                   "'
+$groupId+'"
                               ],
                               "associationMethodTO": "POST"
                               },
                               {
                               "users": [],
                               "groups": [],
                               "associationMethodTO": "DELETE"
                               }
                   ]
               }'


       $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body
       $response
   }
   Catch {
       Write-Error $_.Exception.Message
   }
}
Export-ModuleMember -Function Add-WSARoleAssociation

Function Get-WSARoleId {
   <#
       .SYNOPSIS
       Get role id for role name

       .DESCRIPTION
       Get the role id corresponding to the given role name

       .EXAMPLE
       Get-WSARoleId -role "Super Admin"
       This retrieves the id for the Super Admin role
   #>


   Param (
       [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role
   )

   Try {
       $wsaHeaders = @{"Content-Type" = "application/json" }
       $wsaHeaders.Add("Authorization", "$sessionToken")
       $uri = "https://$workSpaceOne/acs/rulesets"
       $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
       $roledetails = $response.items | Where-Object {$_.name -eq $role}
       $roleId=$roledetails._links.self.href.split('/')[3]
       $roleId
   }
   Catch {
       Write-Error $_.Exception.Message
   }
}
Export-ModuleMember -Function Get-WSARoleId

Function Get-WSAActiveDirectoryGroupDetail {
   <#
       .SYNOPSIS
       Get details of the given Active Directory group

       .DESCRIPTION
       Get details from Workspace ONE Access of the given Active Directory group

       .EXAMPLE
       Get-WSAActiveDirectoryGroupDetail -group "gg-wsa-admins"
   #>


   Param (
       [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group
   )

   Try {
       $wsaHeaders = @{"Content-Type" = "application/json" }
       $wsaHeaders.Add("Authorization", "$sessionToken")
       $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/scim/Groups/.search?locale=en"
       $body = '{
                   "attributes": "id,displayName",
                   "filter": "(displayName co \"'
 + $group + '\")"
                }'

       $response = Invoke-RestMethod $uri -Method 'POST' -Headers $wsaHeaders -body $body
       $response
   }
   Catch {
       Write-Error $_.Exception.Message
   }
}
Export-ModuleMember -Function Get-WSAActiveDirectoryGroupDetail

Function Get-WSARoleAssociation {
   <#
       .SYNOPSIS
       Get associations for the given Role Id

       .DESCRIPTION
       Get details of associations for the given Role Id. This has details of the groups associated with a role.

       .EXAMPLE
       Get-WSARoleAssociation -roleId "1d0b09a1-8744-4f85-8c4f-ac104e586010"
   #>


   Param (
       [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$roleId
   )

   Try {
       $wsaHeaders = @{"Content-Type" = "application/json" }
       $wsaHeaders.Add("Authorization", "$sessionToken")
       $uri = "https://$workSpaceOne/acs/associations/rulesets/$roleId"
       $response = Invoke-RestMethod $uri -Method 'GET' -Headers $wsaHeaders
       $response
   }
   Catch {
       Write-Error $_.Exception.Message
   }
}
Export-ModuleMember -Function Get-WSARoleAssociation

Function Get-WSAPasswordLockout {
    <#
        .SYNOPSIS
        Get password lockout policy

        .DESCRIPTION
        Get details of the password lockout policy for Workspace ONE Access

        .EXAMPLE
        Get-WSAPasswordLockout
    #>


    Try {
        $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.password.lockout+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/passwordlockoutconfig"
        $response = Invoke-RestMethod $uri -Headers $wsaHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAPasswordLockout

Function Set-WSAPasswordLockout {
    <#
        .SYNOPSIS
        Set password lockout policy

        .DESCRIPTION
        Set details of the password lockout policy for Workspace ONE Access

        .EXAMPLE
        Set-WSAPasswordLockout
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$numAttempts,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$attemptInterval,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$unlockInterval
    )

    Try {
        $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.password.lockout+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.password.lockout+json")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/passwordlockoutconfig"
        $body = '{"numAttempts":'+$numAttempts+',"attemptInterval":'+$attemptInterval+',"unlockInterval":'+$unlockInterval+'}'
        $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSAPasswordLockout

Function Get-WSAPasswordPolicy {
    <#
        .SYNOPSIS
        Get password policy

        .DESCRIPTION
        Get details of the password policy for Workspace ONE Access

        .EXAMPLE
        Get-WSAPasswordPolicy
    #>


    Try {
        $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/tenants/tenant/passwordpolicy"
        $response = Invoke-RestMethod $uri -Headers $wsaHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-WSAPasswordPolicy

Function Set-WSAPasswordPolicy {
    <#
        .SYNOPSIS
        Set password lockout policy

        .DESCRIPTION
        Set details of the password lockout policy for Workspace ONE Access

        .EXAMPLE
        Set-WSAPasswordPolicy -minLen 6 -minLower 0 -minUpper 0 -minDigit 0 -minSpecial 0 -history 0 -maxConsecutiveIdenticalCharacters 3 -maxPreviousPasswordCharactersReused 2 -tempPasswordTtlInHrs 167 -passwordTtlInDays 81 -notificationThresholdInDays 16 -notificationIntervalInDays 11
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minLen,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minLower,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minUpper,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minDigit,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$minSpecial,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$history,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxConsecutiveIdenticalCharacters,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$maxPreviousPasswordCharactersReused,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$tempPasswordTtlInHrs,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$passwordTtlInDays,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$notificationThresholdInDays,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$notificationIntervalInDays

    )

    Try {
        $wsaHeaders = @{"Accept" = "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json" }
        $wsaHeaders.Add("Authorization", "$sessionToken")
        $wsaHeaders.Add("Content-Type", "application/vnd.vmware.horizon.manager.tenants.tenant.passwordpolicy+json")
        $uri = "https://$workSpaceOne/SAAS/jersey/manager/api/tenants/tenant/passwordpolicy"
        $passwordTtlInHours = [int]$passwordTtlInDays * 24
        $notificationThresholdInMilliSec = [int]$notificationThresholdInDays * 24 * 3600 * 1000
        $notificationIntervalInMilliSec = [int]$notificationIntervalInDays * 24 * 3600 * 1000
        $body = '{
            "minLen":'
+$minLen+',
            "minLower":'
+$minLower+',
            "minUpper":'
+$minUpper+',
            "minDigit":'
+$minDigit+',
            "minSpecial":'
+$minSpecial+',
            "history":'
+$history+',
            "maxConsecutiveIdenticalCharacters":'
+$maxConsecutiveIdenticalCharacters+',
            "maxPreviousPasswordCharactersReused":'
+$maxPreviousPasswordCharactersReused+',
            "tempPasswordTtl":'
+$tempPasswordTtlInHrs+',
            "passwordTtlInHours":'
+$passwordTtlInHours+',
            "notificationThreshold":'
+$notificationThresholdInMilliSec+',
            "notificationInterval":'
+$notificationIntervalInMilliSec+'
        }'

        Write-OutPut $body
        $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $wsaHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WSAPasswordPolicy

#EndRegion End Workspace ONE Access Functions ######
#####################################################################

#####################################################################
#Region Begin NSX-T Data Center Functions ######

Function Request-NsxtToken {
    <#
        .SYNOPSIS
        Connects to the specified NSX Manager

        .DESCRIPTION
        The Request-NsxtToken cmdlet connects to the specified NSX Manager with the supplied credentials

        .EXAMPLE
        Request-NsxtToken -fqdn sfo-w01-nsx01.sfo.rainpole.io -username admin -password VMware1!VMw@re1!
        This example shows how to connect to NSX Manager

        .EXAMPLE
        Get-NsxtServerDetail -fqdn sfo-vcf01.sfo.rainpole.io -username admin@local -password VMw@re1!VMw@re1! -domain sfo-w01 | Request-NsxtToken
        This example shows how to connect to NSX Manager using pipeline input from Get-NsxtServerDetail
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()][String]$fqdn,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psobject]$inputObject,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$skipCertificateCheck
    )

    if ($inputObject) {
        $username = $inputObject.adminUser
        $password = $inputObject.adminPass
        $fqdn = $inputObject.fqdn
        $sddcManager = (Get-VCFManager).fqdn
    } else {
        if (!$PsBoundParameters.ContainsKey("username") -or (!$PsBoundParameters.ContainsKey("password"))) {
            # Request Credentials
            $creds = Get-Credential
            $username = $creds.UserName.ToString()
            $password = $creds.GetNetworkCredential().password
        }
        if (!$PsBoundParameters.ContainsKey("fqdn")) {
            $fqdn = Read-Host "NSX Manager FQDN not found, please enter a value e.g. sfo-m01-nsx01.sfo.rainpole.io"
        }
    }

    if ($PsBoundParameters.ContainsKey("skipCertificateCheck")) {
        if (-not("placeholder" -as [type])) {
            add-type -TypeDefinition @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public static class Placeholder {
    public static bool ReturnTrue(object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; }

    public static RemoteCertificateValidationCallback GetDelegate() {
        return new RemoteCertificateValidationCallback(Placeholder.ReturnTrue);
    }
}
"@

} 
        [System.Net.ServicePointManager]::ServerCertificateValidationCallback = [placeholder]::GetDelegate()
    }

    # Validate credentials by executing an API call
    $Global:nsxtHeaders = createBasicAuthHeader $username $password
    $Global:nsxtmanager = $fqdn
    $uri = "https://$nsxtmanager/api/v1/logical-ports"

    Try {
        # Checking against the NSX Managers API
        # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        if ($PSEdition -eq 'Core') {
            $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $nsxtHeaders -SkipCertificateCheck
        } else {
            $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $nsxtHeaders
        }
        if ($response) {
            if ($inputObject) {
                Write-Output "Successfully Requested New API Token for NSX Manager $nsxtmanager via SDDC Manager $sddcManager"
            } else {
                Write-Output "Successfully Requested New API Token for NSX Manager $nsxtmanager"
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
New-Alias -name Request-NsxToken -Value Request-NsxtToken
Export-ModuleMember -Alias Request-NsxToken -Function Request-NsxtToken

Function Get-NsxtComputeManager {
    <#
    .SYNOPSIS
    Retrieves a list of compute managers from NSX Manager

    .DESCRIPTION
    The Get-NsxtComputeManager cmdlet gets compute managers from NSX Manager

    .EXAMPLE
    Get-NsxtComputeManager
    This example gets all compute managers

    .EXAMPLE
    Get-NsxtComputeManager -vCenterServer "sfo-m01-vc01.sfo.rainpole.io"
    This example gets the compute manager named "sfo-m01-vc01.sfo.rainpole.io"
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vCenterServer
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("vCenterServer")) {
            $uri = "https://$nsxtManager/api/v1/fabric/compute-managers"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results
        }
        elseif ($PsBoundParameters.ContainsKey("vCenterServer")) {
            $uri = "https://$nsxtManager/api/v1/fabric/compute-managers"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $responseChecked = $response.results | Where-Object { $_.server -eq $vCenterServer }

            if (!$responseChecked) {
                Write-Output "Compute Manager $vCenterServer was not found."
            }
            elseif ($responseChecked) {
                $responseChecked
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtComputeManager

Function Set-NsxtComputeManager {
    <#
    .SYNOPSIS
    Configure a set of parameters on a compute manager

    .DESCRIPTION
    The Set-NsxtComputeManager cmdlet configures a set of parameters on a compute manager

    .EXAMPLE
    Get-NsxtComputeManager -vCenterServer sfo-w01-vc01.sfo.rainpole.io | Set-NsxtComputeManager -EnableTrust:$true
    This example enables trust (sets OIDC provider to true) for Compute Manager sfo-w01-vc01.sfo.rainpole.io
    In this release, it is required to use pipeline input from Get-NsxtComputeManager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Bool]$EnableTrust,
        [Parameter (ValueFromPipeline, Mandatory = $true)] [psObject]$inputObject
    )

    # Validating pipeline input resource_type
    if ($inputObject.resource_type -ne "ComputeManager") {
        Write-Error "Invalid pipeline passthrough."
        break
    }
    elseif ($inputObject.resource_type -eq "ComputeManager") {
        $computeManagerId = $inputObject.id
        $computeManagerDisplayName = $inputObject.display_name
        $computeManagerRevision = $inputObject._revision
        $computeManagerFqdn = $inputObject.server
        $computeManagerOriginType = $inputObject.origin_type
        $computeManagerSetAsOidcProvider = $inputObject.set_as_oidc_provider
        $computeManagerCredentialType = $inputObject.credential.credential_type
        $computeManagerCredentialThumbprint = $inputObject.credential.thumbprint
    }

    if ($EnableTrust -eq $computeManagerSetAsOidcProvider) {
        Write-Error -Message "Compute Manager trust is already set to $EnableTrust."
        break
    }

    $json = @"
{
"_revision" : $computeManagerRevision,
"server" : "$computeManagerFqdn",
"display_name" : "$computeManagerDisplayName",
"origin_type" : "$computeManagerOriginType",
"set_as_oidc_provider" : "$EnableTrust",
"credential" :
{
    "credential_type" : "$computeManagerCredentialType",
    "thumbprint" : "$computeManagerCredentialThumbprint"
}
}
"@


    Try {
        $uri = "https://$nsxtManager/api/v1/fabric/compute-managers/$computeManagerId"
        $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtComputeManager

Function Get-NsxtVidm {
    <#
        .SYNOPSIS
        Get Identity Manager Configuration

        .DESCRIPTION
        The Get-NsxtVidm cmdlet gets the Identity Manager Configuration

        .EXAMPLE
        Get-NsxtVidm
        This example gets the Identity Manager Configuration
    #>


    Try {
        $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtVidm

Function Set-NsxtVidm {
    <#
        .SYNOPSIS
        Set Identity Manager Configuration

        .DESCRIPTION
        The Set-NsxtVidm cmdlet configures Identity Manager in NSX-T Manager

        .EXAMPLE
        Set-NsxtVidm
        This example configures the Identity Manager in NSX-T Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wsaHostname,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$thumbprint,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$clientId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sharedSecret,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxHostname,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$disable
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm"
        if ($PsBoundParameters.ContainsKey("disable")) {
            $status = "false"
        }
        else {
            $status = "true"
        }
        $body = '{
            "lb_enable": false,
            "vidm_enable": '
 + $status + ',
            "host_name": "'
 + $wsaHostname + '",
            "thumbprint": "'
 + $thumbprint + '",
            "client_id": "'
 + $clientId + '",
            "client_secret": "'
 + $sharedSecret + '",
            "node_host_name": "'
 + $nsxHostname + '"
        }'

        $response = Invoke-RestMethod $uri -Method 'PUT' -Headers $nsxtHeaders -body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtVidm

Function Get-NsxtRole {
    <#
        .SYNOPSIS
        Gets NSX-T Manager roles

        .DESCRIPTION
        The Get-NsxtRole cmdlet gets the roles in NSX-T Manager

        .EXAMPLE
        Get-NsxtRole
        This example gets all roles in NSX-T Manager
    #>


    Try {
        $uri = "https://$nsxtManager/api/v1/aaa/roles"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtRole

Function Set-NsxtRole {
    <#
        .SYNOPSIS
        Adds a role to a user/group

        .DESCRIPTION
        The Set-NsxtRole cmdlet assigns users/groups to roles

        .EXAMPLE
        Set-NsxtRole -principle "gg-nsx-enterprise-admins@lax.rainpole.io"
        This example assigned the provided group the Enterprise Admin role
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateSet("remote_group", "remote_user")] [String]$type,
        [Parameter (Mandatory = $true)] [ValidateSet("lb_admin", "security_engineer", "vpn_admin", "network_op", "netx_partner_admin", "gi_partner_admin", "security_op", "network_engineer", "lb_auditor", "auditor", "enterprise_admin")] [String]$role,
        [Parameter (Mandatory = $true)] [ValidateSet("LDAP", "VIDM", "OIDC")] [String]$identitySource
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/aaa/role-bindings"
        $body = '{
            "name": "'
 + $principal + '",
            "type": "'
 + $type + '",
            "identity_source_type": "'
 + $identitySource + '",
            "roles": [
                    {
                        "role": "'
 + $role + '"
                    }
                ]
            }'

        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtRole

Function Remove-NsxtRole {
    <#
        .SYNOPSIS
        Delete a user/group role assignment

        .DESCRIPTION
        The Remove-NsxtRole cmdlet removes a user/group role in NSX-T Manager

        .EXAMPLE
        Remove-NsxtRole -id
        This example removes the role for the user/group based on the id
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/aaa/role-bindings/$id"
        $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-NsxtRole

Function Get-NsxtUser {
    <#
        .SYNOPSIS
        Gets all users and groups

        .DESCRIPTION
        The Get-NsxtUser cmdlet gets all users and groups in NSX-T Manager

        .EXAMPLE
        Get-NsxtUser
        This example gets all users and grops in NSX-T Manager
    #>


    Try {
        $uri = "https://$nsxtManager/api/v1/aaa/role-bindings"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtUser

Function Get-NsxtVidmUser {
    <#
        .SYNOPSIS
        Gets vIDM users

        .DESCRIPTION
        The Get-NsxtVidmUser cmdlet gets all vIDM users from NSX-T Manager

        .EXAMPLE
        Get-NsxtVidmUser -searchString svc
        This example gets all vIDM users starting with 'svc' from NSX-T Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateLength(3, 255)] [String]$searchString
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/aaa/vidm/users?search_string=$searchString"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtVidmUser

Function Get-NsxtVidmGroup {
    <#
        .SYNOPSIS
        Gets vIDM groups

        .DESCRIPTION
        The Get-NsxtVidmGroup cmdlet gets all vIDM groups from NSX-T Manager

        .EXAMPLE
        Get-NsxtVidmGroup -searchString gg-
        This example gets all vIDM groups starting with gg- from NSX-T Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateLength(3, 255)] [String]$searchString
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/aaa/vidm/groups?search_string=$searchString"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtVidmGroup

Function Get-NsxEdgeCluster {
    <#
        .SYNOPSIS
        Retrieves NSX-T Edge Cluster(s)

        .DESCRIPTION
        The Get-NsxtEdgeCluster cmdlet retrieves NSX-T Edge Cluster(s)

        .EXAMPLE
        Get-NsxtEdgeCluster
        This example returns any NSX-T Edge Clusters

        .EXAMPLE
        Get-NsxtEdgeCluster -Name "sfo-w01-ec01"
        This example returns any NSX-T Edge Clusters
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$Name
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("Name")) {
            $uri = "https://$nsxtmanager/api/v1/edge-clusters"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results
        }
        elseif ($PsBoundParameters.ContainsKey("Name")) {
            $uri = "https://$nsxtmanager/api/v1/edge-clusters"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $responseChecked = $response.results | Where-Object { $_.display_name -eq $Name }

            if (!$responseChecked) {
                Write-Output "NSX-T Edge Cluster $Name was not found."
            }
            elseif ($responseChecked) {
                $responseChecked
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxEdgeCluster

Function Get-NsxtTransportZone {
    <#
        .SYNOPSIS
        Get a list of Transport Zones

        .DESCRIPTION
        The Get-NsxtTransportZone cmdlet retrieves a list of Transport Zones

        .EXAMPLE
        Get-NsxtTransportZone
        This example gets all Transport Zones

        .EXAMPLE
        Get-NsxtTransportZone -name overlay-tz-sfo-w01-nsx01.sfo.rainpole.io
        This example gets the Transport Zone with the name "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io"
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$nsxtManager/api/v1/transport-zones"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results | Sort-Object display_name
        }
        elseif ($PsBoundParameters.ContainsKey("Name")) {
            $uri = "https://$nsxtManager/api/v1/transport-zones"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $responseChecked = $response.results | Where-Object { $_.display_name -eq $name }

            if (!$responseChecked) {
                Write-Output "NSX Transport Zone $name was not found"
            }
            elseif ($responseChecked) {
                $responseChecked
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTransportZone

Function New-NsxtSegment {
    <#
        .SYNOPSIS
        Create a new NSX-T Segment

        .DESCRIPTION
        The New-NsxtSegment cmdlet creates NSX-T Segments

        .EXAMPLE
        New-NsxtSegment -Name "sfo-w01-xreg-seg01" -GatewayType "Tier1" -ConnectedGateway "sfo-w01-ec01-t1-gw01" -Cidr "192.168.31.1/24" -TransportZone "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io"
        This example creates an NSX-T Overlay Segment with the name "sfo-w01-xreg-seg01", connected to Tier-1 gateway "sfo-w01-ec01-t1-gw01", Transport Zone "overlay-tz-sfo-w01-nsx01.sfo.rainpole.io", and CIDR address of "192.168.31.1/24"
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Name,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ConnectedGateway,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$Cidr,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$TransportZone,
        [Parameter (Mandatory = $false)] [ValidateSet("Tier0", "Tier1")] [String]$GatewayType,
        [Parameter (Mandatory = $true)] [ValidateSet("Overlay", "VLAN")] [String]$SegmentType,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$VlanId
    )

    if ($GatewayType -eq "Tier0") {
        $connectivityPath = (Get-NsxtTier0Gateway -Name $ConnectedGateway).path
    }
    elseif ($GatewayType -eq "Tier1") {
        $connectivityPath = (Get-NsxtTier1Gateway -Name $ConnectedGateway).path
    }
    elseif (!$GatewayType -and $VlanId) {
        Write-Output "Valid VLAN segment configuration"
    }
    else {
        Write-Error "Gateway type not defined"
    }

    $transportZoneId = (Get-NsxtTransportZone -Name $TransportZone).id

    if ($SegmentType -match "overlay") {

        $json = @"
{
"display_name" : "$Name",
"subnets" : [{ "gateway_address" : "$Cidr" }],
"connectivity_path" : "$connectivityPath",
"transport_zone_path" : "/infra/sites/default/enforcement-points/default/transport-zones/$transportZoneId"
}
"@


    }
    elseif ($SegmentType -match "vlan") {

        $json = @"
{
"display_name" : "$Name",
"vlan_ids" : [ "$VlanId" ],
"transport_zone_path" : "/infra/sites/default/enforcement-points/default/transport-zones/$transportZoneId"
}
"@


    }
    else {
        Write-Error "SegmentType $SegmentType is invalid."
    }

    Try {
        $uri = "https://$nsxtManager/policy/api/v1/infra/segments/$Name"
        $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -Body $json -headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtSegment

Function Get-NsxtSegment {
    <#
        .SYNOPSIS
        Get a list of Segments

        .DESCRIPTION
        The Get-NsxtSegment cmdlet retrieves a list of Segments

        .EXAMPLE
        Get-NsxtSegment
        This example gets all Segments

        .EXAMPLE
        Get-NsxtSegment -name sfo-w01-kub-seg01
        This example gets the segment with the name sfo-w01-kub-seg01
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$nsxtManager/policy/api/v1/infra/segments/"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results | Sort-Object display_name
        }
        elseif ($PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$nsxtManager/policy/api/v1/infra/segments/"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results | Where-Object { $_.display_name -eq $name }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtSegment

Function Remove-NsxtSegment {
    <#
        .SYNOPSIS
        Removes a named Segment

        .DESCRIPTION
        The Remove-NsxtSegment cmdlet removes a named segment.

        .EXAMPLE
        Remove-NsxtSegment -name sfo-w01-kub-seg01
        This example removes the segment with the name sfo-w01-kub-seg01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name
    )

    Try {
        $uri = "https://$nsxtManager/policy/api/v1/infra/segments/$Name"
        $response = Invoke-RestMethod -Method DELETE -URI $uri -ContentType application/json -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-NsxtSegment

Function Get-NsxtTier0Gateway {
    <#
        .SYNOPSIS
        Get a list of Tier 0 Gateways

        .DESCRIPTION
        The Get-NsxtTier0 cmdlet retrieves a list of Tier 0 Gateways

        .EXAMPLE
        Get-NsxtTier0Gateway
        This example returns all Tier 0 Gateways

        .EXAMPLE
        Get-NsxtTier0Gateway -name sfo-w01-ec01-t0-gw01
        This example returns the Tier 0 Gateway named sfo-w01-ec01-t0-gw01

        .EXAMPLE
        Get-NsxtTier0Gateway -id 84a6c7a5-9fe8-4446-8684-814663399584
        This example returns the Tier 0 Gateway based on its id
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("name") -and !$PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results
        }
        elseif ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s/$id"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results | Where-Object { $_.display_name -eq $name }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTier0Gateway

Function Get-NsxtTier1Gateway {
    <#
        .SYNOPSIS
        Get a list of Tier 1 Gateways

        .DESCRIPTION
        The Get-NsxtTier1Gateway cmdlet retrieves a list of Tier 1 Gateways

        .EXAMPLE
        Get-NsxtTier1Gateway
        This example returns all Tier 1 Gateways

        .EXAMPLE
        Get-NsxtTier1Gateway -name sfo-w01-ec01-t1-gw01
        This example returns the Tier 1 Gateway named sfo-w01-ec01-t1-gw01

        .EXAMPLE
        Get-NsxtTier1Gateway -id 84a6c7a5-9fe8-4446-8684-814663399584
        This example returns the Tier 1 Gateway based on its id
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ( -not $PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results
        }
        elseif ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$id"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results | Where-Object { $_.display_name -eq $name }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTier1Gateway

Function Get-NsxtPrefixList {
    <#
        .SYNOPSIS
        Get Tier-0 Gateway IP Prefix Lists

        .DESCRIPTION
        The Get-NsxtTier0PrefixList cmdlet retrieves the IP Prefix Lists assigned to a Tier-0 Gateway

        .EXAMPLE
        Get-NsxtPrefixList -tier0Gateway sfo-w01-ec01-t0-gw01
        This example returns all IP Prefix Lists

        .EXAMPLE
        Get-NsxtPrefixList -tier0Gateway sfo-w01-ec01-t0-gw01 -name sfo-w01-cl01-prefix-list
        This example returns the IP Prefix List based on the prefix name provided

        .EXAMPLE
        Get-NsxtTier0Gateway -name sfo-w01-ec01-t0-gw01 | Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list
        This example returns the IP Prefix List based on the prefix name provided
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    # Validating pipeline input resource_type
    if ($inputObject -and $inputObject.resource_type -eq "Tier0") {
        $tier0Gateway = $inputObject.display_name
        $uriPath = $inputObject.path
    }
    elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") {
        Write-Error "Invalid pipeline passthrough. Exiting."
        Break
    }
    elseif (!$inputObject -and $Tier0Gateway) {
        $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path
    }
    else {
        if (!$tier0Gateway) {
            $tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter"
        }
    }

    Try {
        if (!$name) {
            $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists"
            $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ErrorAction SilentlyContinue
            $response.results
        }
        elseif ($name) {
            $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists"
            $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ErrorAction SilentlyContinue
            $response.results | Where-Object { $_.display_name -eq $name }
        }
    }
    Catch {
        if ($_.Exception -match "400" -or $_.Exception -match "Bad Request") {
            Write-Output $uri
            Write-Error "The NSX Tier-0 Gateway was not properly defined"

        }
    }
}
Export-ModuleMember -Function Get-NsxtPrefixList

Function New-NsxtPrefixList {
    <#
        .SYNOPSIS
        Creates a Tier-0 Gateway IP Prefix List

        .DESCRIPTION
        The New-NsxtPrefixList cmdlet creates a Prefix List on a specified Tier-0 Gateway

        .EXAMPLE
        New-NsxtPrefixList -name sfo-w01-cl01-prefix-list -tier0Gateway sfo-w01-ec01-t0-gw01 -subnetCIDR 192.168.20.0/24 -action PERMIT
        This example creates a new IP Prefix List on a Tier 0 Gateway
    #>


    Param (
        [Parameter (Mandatory = $false)] [String]$name,
        [Parameter (Mandatory = $false)] [String]$tier0Gateway,
        [Parameter (Mandatory = $false)] [String]$subnetCIDR,
        [Parameter (Mandatory = $false)] [String]$GE,
        [Parameter (Mandatory = $false)] [String]$LE,
        [Parameter (Mandatory = $false)] [ValidateSet("PERMIT", "DENY")] [String]$action,
        [Parameter (Mandatory = $false)] [String]$json,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    # Validating pipeline input resource_type
    if ($inputObject -and $inputObject.resource_type -eq "Tier0") {
        $uriPath = $inputObject.path
        $Tier0Gateway = $inputObject.display_name
    }
    elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") {
        Write-Error "Invalid pipeline passthrough. Exiting."
        Break
    }
    elseif (!$inputObject) {
        if (!$Tier0Gateway) {
            $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter"
            $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path
        }
    }

    if (!$json) {
        if (!$GE -or !$LE) {
            $Json = @"
{
    "display_name" : "$Name",
    "prefixes" :
    [
        {
        "network" : "$SubnetCIDR",
        "action" : "$Action"
        }
    ]
}
"@

        }
        elseif ($GE -and $LE) {
            $Json = @"
{
    "display_name" : "$Name",
    "prefixes" :
    [
        {
        "network" : "$SubnetCIDR",
        "action" : "$Action",
        "ge" : "$GE",
        "le" : "$LE"
        }
    ]
}
"@

        }
        else {
            Write-Error "Invalid subnet configuration."
        }
    }

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$name"
        $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtPrefixList

Function Remove-NsxtPrefixList {
    <#
        .SYNOPSIS
        Remove an IP Prefix List from a Tier-0 Gateway

        .DESCRIPTION
        The Remove-NsxtPrefixList cmdlet removes a IP Prefix List from a specified Tier-0 Gateway

        .EXAMPLE
        Remove-NsxtPrefixList -name sfo-w01-cl01-prefix-list -tier0Gateway sfo-w01-ec01-t0-gw01
        This example removes a Prefix List on a Tier 0 Gateway
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tier0Gateway
    )

    Try {
        $gatewayId = (Get-NsxtTier0Gateway -name $tier0Gateway).id
        $uri = "https://$nsxtManager/policy/api/v1/infra/tier-0s/$gatewayId/prefix-lists/$name"
        $response = Invoke-RestMethod -Method DELETE -URI $uri -ContentType application/json -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-NsxtPrefixList

Function Add-NsxtPrefix {
    <#
        .SYNOPSIS
        Add a single entry to an existing NSX IP Prefix List

        .DESCRIPTION
        The Add-NsxtPrefix cmdlet adds a single entry to an existing NSX IP Prefix List

        .EXAMPLE
        Get-NsxtPrefixList -name sfo-w01-cl01-prefix-list | Add-NsxtPrefix -subnetCIDR 192.168.21.0/24 -LE 32 -GE 28 -action PERMIT
        This example adds an IP Prefix entry on an existing IP Prefix List
    #>


    Param (
        [Parameter (Mandatory = $false)] [String]$prefixListName,
        [Parameter (Mandatory = $false)] [String]$tier0Gateway,
        [Parameter (Mandatory = $false)] [String]$subnetCIDR,
        [Parameter (Mandatory = $false)] [String]$GE,
        [Parameter (Mandatory = $false)] [String]$LE,
        [Parameter (Mandatory = $false)] [String]$action,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    if (!$inputObject -and $tier0Gateway -and $prefixListName) {
        $uriPath = (Get-NsxtTier0Gateway -Name $tier0Gateway).path
        $existingPrefixes = (Get-NsxtPrefixList -Name $prefixListName -Tier0Gateway $tier0Gateway).prefixes
    }

    if ($inputObject -and $inputObject.resource_type -eq "PrefixList") {
        $uriPath = $inputObject.parent_path
        $Tier0GatewayId = $inputObject.parent_path.Split('/')[3]
        $PrefixListName = $inputObject.display_name
        $existingPrefixes = $inputObject.prefixes

        $getTier0Gateway = Get-NsxtTier0Gateway -name $tier0GatewayId -ErrorAction SilentlyContinue

        if ($getTier0Gateway -eq "NSX Tier-0 Gateway $tier0GatewayId was not found") {
            $tier0Gateway = (Get-NsxtTier0Gateway -Id $tier0GatewayId).display_name
        }
        else {
            $Tier0Gateway = $Tier0GatewayId
        }

    }
    elseif ($inputObject -and $inputObject.resource_type -ne "PrefixList") {
        Write-Error "Invalid pipeline passthrough"
        Break
    }

    $prefixes = @()

    $prefixes += $existingPrefixes

    if (!$GE -or !$LE) {
        $newPrefix = @{
            network = $subnetCIDR
            action  = $action
        }
    }
    elseif ($GE -and $LE) {
        $newPrefix = @{
            network = $subnetCIDR
            action  = $action
            ge      = $GE
            le      = $LE
        }
    }
    else {
        Write-Error "Invalid subnet configuration"
    }

    $prefixes += $newPrefix
    $prefixesJson = $prefixes | ConvertTo-Json

    $json = @"
    {
        "display_name": "$PrefixListName",
        "prefixes": $prefixesJson
    }
"@


    Try {
        $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/prefix-lists/$PrefixListName"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders
        $response

        if (!$response) {
            $output = Get-NsxtPrefixList -Name $PrefixListName -Tier0Gateway $Tier0Gateway
            $output
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-NsxtPrefix

Function Get-NsxtRouteMap {
    <#
        .SYNOPSIS
        Get Tier-0 Gateway Route Maps

        .DESCRIPTION
        The Get-NsxtRouteMap cmdlet retrieves the Route Maps assigned to a specified Tier-0 Gateway

        .EXAMPLE
        Get-NsxtRouteMap -tier0Gateway sfo-w01-ec01-t0-gw01
        This example gets all Route Maps on the Tier-0 Gateway

        .EXAMPLE
        Get-NsxtRouteMap -tier0Gateway sfo-w01-ec01-t0-gw01 -name sfo-w01-ec01-t0-gw01-routemap
        This example gets a specific route map by name from the Tier-0 Gateway
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$tier0Gateway,
        [Parameter (Mandatory = $false)] [String]$name,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    # Validating pipeline input resource_type
    if ($inputObject -and $inputObject.resource_type -eq "Tier0") {
        $tier0Gateway = $inputObject.display_name
        $uriPath = $inputObject.path
    }
    elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") {
        Write-Error "Invalid pipeline passthrough. Exiting."
        Break
    }
    elseif (!$inputObject) {
        if (!$tier0Gateway) {
            Write-Output "Tier 0 Gateway: $Tier0Gateway"
            $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter"
        }
        $uriPath = (Get-NsxtTier0Gateway -Name $tier0Gateway).path
    }

    Try {
        if (!$PsBoundParameters.ContainsKey("Name")) {
            $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results
        }
        elseif ($PsBoundParameters.ContainsKey("Name")) {
            $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results | Where-Object { $_.display_name -eq $Name }
        }
    }
    Catch {
        if ($_.Exception -match "400" -or $_.Exception -match "Bad Request") {
            Write-Error "The NSX Tier-0 Gateway was not properly defined."
        }
    }
}
Export-ModuleMember -Function Get-NsxtRouteMap

Function New-NsxtRouteMap {
    <#
        .SYNOPSIS
        Creates a Route Map on a specified Tier-0 Gateway

        .DESCRIPTION
        The New-NsxtRouteMap cmdlet creates a Route Map on a specified Tier-0 Gateway

        .EXAMPLE
        New-NsxtRouteMap -Name sfo-w01-cl01-route-map -Tier0Gateway sfo-w01-ec01-t0-gw01 -PrefixList sfo-w01-ec01-prefix-list
        This example creates a new Route Map on a Tier-0 Gateway

        .EXAMPLE
        Net-NsxtTier0Gateway sfo-w01-ec01-t0-gw01 | Get-NsxtPrefixList -Name sfo-w01-ec01-prefix-list | New-NsxtRouteMap -Name sfo-w01-cl01-route-map
        This example creates a new Route Map on a Tier-0 Gateway
    #>


    Param (
        [Parameter (Mandatory = $false)] [String]$Name,
        [Parameter (Mandatory = $false)] [String]$Tier0Gateway,
        [Parameter (Mandatory = $false)] [String]$PrefixList,
        [Parameter (Mandatory = $false)] [String]$Action,
        [Parameter (Mandatory = $false)] [String]$Json,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    if ($inputObject) {
        if ($inputObject.resource_type -eq "Tier0") {
            $Tier0Gateway = $inputObject.display_name
            $Tier0GatewayId = $inputObject.id
            $uriPath = $inputObject.path
        }
        elseif ($inputObject.resource_type -eq "PrefixList") {
            $Tier0GatewayId = $inputObject.parent_path.Split('/')[3]
            $PrefixListPath = $inputObject.path
            $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name
            $uriPath = $inputObject.parent_path
        }
        else {
            Write-Error "Invalid pipeline passthrough. Exiting."
            Break
        }
    } elseif (!$inputObject){
        $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path
    }

    if (!$PrefixListPath) {
        $PrefixListPath = $uriPath+"/prefix-lists/"+$PrefixList
    }

    $json = @"
{
    "display_name" : "$Name",
    "entries" :
    [
        {
        "action" : "$Action",
        "prefix_list_matches" : [ "$prefixListPath" ]
        }
    ]
}
"@


    Try {
        $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps/$Name"
        $response = Invoke-RestMethod -Method PUT -URI $uri -ContentType application/json -body $json -headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtRouteMap

Function Remove-NsxtRouteMap {
    <#
        .SYNOPSIS
        Remove a Route Map from a specified Tier-0 Gateway

        .DESCRIPTION
        The Remove-NsxtRouteMap cmdlet removes a Route Map attached to a specified Tier-0 Gateway

        .EXAMPLE
        Remove-NsxtRouteMap -name sfo-w01-ec01-t0-gw01-routemap -tier0Gateway sfo-w01-ec01-t0-gw01
        This example removes the Route Map sfo-w01-ec01-t0-gw01-routemap from Tier-0 Gateway sfo-w01-ec01-t0-gw01
    #>


    Param (
        [Parameter (Mandatory = $false)] [String]$name,
        [Parameter (Mandatory = $false)] [String]$tier0Gateway,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    if ($inputObject) {
        if ($inputObject.resource_type -eq "Tier0RouteMap") {
            $Name = $inputObject.display_name
            $Tier0GatewayId = $inputObject.parent_path.Split('/')[3]
            $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name
            $uriPath = $inputObject.parent_path
        }
        elseif ($inputObject.resource_type -eq "Tier0" -and $Name -and !$Tier0Gateway) {
            $Tier0GatewayId = $inputObject.id
            $Tier0Gateway = $inputObject.display_name
            $uriPath = $inputObject.path
        }
        else {
            Write-output $inputObject.resource_type
            Write-Error "Invalid pipeline passthrough. Exiting."
            Break
        }
    }
    elseif (!$inputObject) {
        if (!$tier0Gateway) {
            $tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter"
        }
        $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path
    }

    Try {
        $getRouteRedistribution = Get-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway
        if ($getRouteRedistribution.route_redistribution_config.redistribution_rules.route_map_path -eq $preCheckRouteMap.path) {
            $getRouteRedistribution | Set-NsxtRouteRedistributionPolicy -tier0Gateway $tier0Gateway -RemoveRouteMap:$True | Out-Null
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/route-maps/$name"
        $response = Invoke-RestMethod -Method DELETE -URI $uri -headers $nsxtHeaders -ContentType application/json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
        Break
    }
}
Export-ModuleMember -Function Remove-NsxtRouteMap

Function Get-NsxtRouteRedistributionPolicy {
    <#
        .SYNOPSIS
        Get the route redistribution policy from a Tier-0 Gateway

        .DESCRIPTION
        The Get-NsxtRouteRedistributionPolicy cmdlet get the route redistribution policy from a Tier-0 Gateway

        .EXAMPLE
        Get-NsxtRouteRedistributionPolicy -tier0Gateway sfo-w01-ec01-t0-gw01
        This example returns the route redistribution policy for Tier-0 Gateway sfo-w01-ec01-t0-gw01
    #>


    Param (
        [Parameter (Mandatory = $false)] [String]$tier0Gateway,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    if ($inputObject -and $inputObject.resource_type -eq "Tier0") {
        $Tier0Gateway = $inputObject.display_name
        $uriPath = $inputObject.path
    }
    elseif ($inputObject -and $inputObject.resource_type -ne "Tier0") {
        Write-Error "Invalid pipeline passthrough. Exiting."
        Break
    }
    elseif (!$inputObject) {
        if (!$Tier0Gateway) {
            $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter"
        }
        $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path
    }

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/locale-services/default"
        $response = Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders -ContentType application/json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember Get-NsxtRouteRedistributionPolicy

Function Set-NsxtRouteRedistributionPolicy {
    <#
        .SYNOPSIS
        Set the route redistriution policy for a Tier 0 Gateway

        .DESCRIPTION
        The Set-NsxtRouteRedistributionPolicy cmdlet sets the route redistriution policy for a Tier 0 Gateway

        .EXAMPLE
        Get-NsxtRouteRedistributionPolicy -tier0Gateway "sfo-w01-ec01-t0-gw01" | Set-NsxtRouteRedistributionPolicy -RouteMap "sfo-w01-ec01-t0-gw01-routemap"
        This example sets the RouteMap "sfo-w01-ec01-t0-gw01-routemap" on the route redistribution policy for Tier-0 Gateway "sfo-w01-t0-ec01-t0-gw01"
    #>


    Param (
        [Parameter (Mandatory = $false)] [String]$tier0Gateway,
        [Parameter (Mandatory = $false)] [String]$routeMap,
        [Parameter (Mandatory = $false)] [Bool]$removeRouteMap,
        [Parameter (ValueFromPipeline, Mandatory = $true)] [psObject]$inputObject
    )

    if ($inputObject -and $inputObject.resource_type -eq "LocaleServices") {
        $Tier0GatewayId = $inputObject.parent_path.Split('/')[3]
        $Tier0Gateway = (Get-NsxtTier0Gateway -Id $Tier0GatewayId).display_name
        $edgeClusterPath = $inputObject.edge_cluster_path
        $bgpEnabled = $inputObject.route_redistribution_config.bgp_enabled
        $routeRedistributionName = $inputObject.route_redistribution_config.redistribution_rules.name
        $routeRedistributionTypes = $inputObject.route_redistribution_config.redistribution_rules.route_redistribution_types
        $uriPath = $inputObject.parent_path
    }
    elseif ($inputObject -and $inputObject.resource_type -ne "LocaleServices") {
        Write-Error "Invalid pipeline passthrough. Exiting."
        Break
    }

    if (!$inputObject) {
        if (!$Tier0Gateway) {
            $Tier0Gateway = Read-Host -Prompt "Tier-0 Gateway not defined. Type in the name of your Tier-0 Gateway, then press Enter"
        }

        $getRedistributionPolicy = Get-NsxtTier0Gateway -Name $Tier0Gateway

        $edgeClusterPath = $getRedistributionPolicy.edge_cluster_path
        $bgpEnabled = $getRedistributionPolicy.route_redistribution_config.bgp_enabled
        $routeRedistributionName = $getRedistributionPolicy.route_redistribution_config.redistribution_rules.name
        $routeRedistributionTypes = $getRedistributionPolicy.route_redistribution_config.redistribution_rules.route_redistribution_types
        $uriPath = (Get-NsxtTier0Gateway -Name $Tier0Gateway).path
    }

    $routeMapPath = "/infra/tier-0s/$Tier0GatewayId/route-maps/$RouteMap"

    foreach ($routeRedistributionType in $routeRedistributionTypes) {
        $routeRedistributionTypeString += @"
"$routeRedistributionType",
"@

    }

    $routeRedistributionTypeString = $routeRedistributionTypeString.Substring(0, $routeRedistributionTypeString.Length - 1)

    if ($RemoveRouteMap -eq $true) {
        $json = @"
{
    "edge_cluster_path" : "$edgeClusterPath",
    "route_redistribution_config" :
    {
        "bgp_enabled" : "$bgpEnabled",
        "redistribution_rules" :
        [
            {
            "name" : "$routeRedistributionName",
            "route_redistribution_types" : [ $routeRedistributionTypeString ]
            }
        ]
    }
}
"@

    }
    elseif ($RemoveRouteMap -eq $false -or !$RemoveRouteMap) {
        $json = @"
{
    "edge_cluster_path" : "$edgeClusterPath",
    "route_redistribution_config" :
    {
        "bgp_enabled" : "$bgpEnabled",
        "redistribution_rules" :
        [
            {
            "name" : "$routeRedistributionName",
            "route_redistribution_types" : [ $routeRedistributionTypeString ],
            "route_map_path" : "$routeMapPath"
            }
        ]
    }
}
"@

    }

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1"+$uriPath+"/locale-services/default"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -headers $nsxtHeaders -ContentType application/json -body $json
        $response

        if (!$response) {
            $output = Get-NsxtRouteRedistributionPolicy -Tier0Gateway $Tier0Gateway
            $output
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember Set-NsxtRouteRedistributionPolicy

Function Get-NsxtManagerAuthPolicy {
    <#
        .SYNOPSIS
        Get the Authentication Policy for NSX Manager Nodes

        .DESCRIPTION
        The Get-NsxtManagerAuthPolicy cmdlet getss the current authentication policy for NSX Manager Node

        .EXAMPLE
        Get-NsxtManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io"
        This example returns the current Authentication policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManagerNode
    )

    Try {
        $requestingURL = "https://" + $nsxtManagerNode + "/api/v1/node/aaa/auth-policy"
        $response = Invoke-RestMethod -Method GET -URI $requestingURL -ContentType application/json -headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember Get-NsxtManagerAuthPolicy

Function Set-NsxtManagerAuthPolicy {
    <#
        .SYNOPSIS
        Set the Authentication Policy for NSX Manager Node

        .DESCRIPTION
        The Set-NsxtManagerAuthPolicy cmdlet configures the authentication policy for NSX Manager Node

        .EXAMPLE
        Set-NsxManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" -api_lockout_period 900 -api_reset_period 120 -api_max_attempt 5 -cli_lockout_period 900 -cli_max_attempt 5 -min_passwd_length 15
        This example customized the Authentication policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManagerNode,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_lockout_period,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_reset_period,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$api_max_attempt,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_lockout_period,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_max_attempt,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$min_passwd_length
    )

    $authPolicyBody = @{}
    if ($PsBoundParameters.ContainsKey("api_lockout_period")) {
        $authPolicyBody+= @{api_failed_auth_lockout_period = $api_lockout_period}
    }
    if ($PsBoundParameters.ContainsKey("api_reset_period")) {
        $authPolicyBody += @{api_failed_auth_reset_period = $api_reset_period}
    }
    if ($PsBoundParameters.ContainsKey("api_max_attempt")) {
        $authPolicyBody += @{api_max_auth_failures = $api_max_attempt}
    }
    if ($PsBoundParameters.ContainsKey("cli_lockout_period")) {
        $authPolicyBody += @{cli_failed_auth_lockout_period = $cli_lockout_period}
    }
    if ($PsBoundParameters.ContainsKey("cli_max_attempt")) {
        $authPolicyBody += @{cli_max_auth_failures = $cli_max_attempt}
    }
    if ($PsBoundParameters.ContainsKey("min_passwd_length")) {
        $authPolicyBody += @{minimum_password_length = $min_passwd_length}
    }

    Try {
        $requestingURL = "https://" + $nsxtManagerNode + "/api/v1/node/aaa/auth-policy"
        $response = Invoke-RestMethod -Method PUT -URI $requestingURL -ContentType application/json -headers $nsxtHeaders -Body ($authPolicyBody | ConvertTo-Json)
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember Set-NsxtManagerAuthPolicy

Function Get-NsxtEdgeNodeAuthPolicy {
    <#
        .SYNOPSIS
        Get the Authentication Policy for NSX Edge Nodes

        .DESCRIPTION
        The Get-NsxtEdgeNodeAuthPolicy cmdlet getss the authentication policy for NSX Edge Nodes

        .EXAMPLE
        Get-NsxtEdgeNodeAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io"
        This example returns the password policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManager,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtEdgeNodeID
    )

    Try {
        $requestingURL = "https://" + $nsxtManager + "/api/v1/transport-nodes/" + $nsxtEdgeNodeID + "/node/aaa/auth-policy"
        $response = Invoke-RestMethod -Method GET -URI $requestingURL -ContentType application/json -headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember Get-NsxtEdgeNodeAuthPolicy

Function Set-NsxtEdgeNodeAuthPolicy {
    <#
        .SYNOPSIS
        Set the Authentication Policy for NSX Manager Nodes

        .DESCRIPTION
        The Set-NsxtManagerAuthPolicy cmdlet getss the authentication policy for NSX Manager Nodes

        .EXAMPLE
        Set-NsxManagerAuthPolicy -nsxtManagerNode "sfo-m01-nsx01a.sfo.rainpole.io" -api_lockout_period 900 -api_reset_period 120 -api_max_attempt 5 -cli_lockout_period 900 -cli_max_attempt 5 -min_passwd_length 15
        This example customized the password policy in NSX manager node sfo-m01-nsx01a.sfo.rainpole.io.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtManager,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$nsxtEdgeNodeID,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_lockout_period,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$cli_max_attempt,
        [Parameter (Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int]$min_passwd_length
    )

    $authPolicyBody = @{}
    if ($PsBoundParameters.ContainsKey("cli_lockout_period")) {
        $authPolicyBody += @{cli_failed_auth_lockout_period = $cli_lockout_period}
    }
    if ($PsBoundParameters.ContainsKey("cli_max_attempt")) {
        $authPolicyBody += @{cli_max_auth_failures = $cli_max_attempt}
    }
    if ($PsBoundParameters.ContainsKey("min_passwd_length")) {
        $authPolicyBody += @{minimum_password_length = $min_passwd_length}
    }

    Try {
        $requestingURL = "https://" + $nsxtManager + "/api/v1/transport-nodes/" + $nsxtEdgeNodeID + "/node/aaa/auth-policy"
        $response = Invoke-RestMethod -Method PUT -URI $requestingURL -ContentType application/json -headers $nsxtHeaders -Body ($authPolicyBody | ConvertTo-Json)
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember Set-NsxtEdgeNodeAuthPolicy

Function Get-NsxtSyslogStatus {
    <#
        .SYNOPSIS
        Gets the status of the Syslog Service

        .DESCRIPTION
        The Get-NsxtSyslogStatus cmdlet gets the status of the Syslog Service for NSX-T Data Center components

        .EXAMPLE
        Get-NsxtSyslogStatus -type node
        This example gets the status of the syslog service for NSX Manager node

        .EXAMPLE
        Get-NsxtSyslogStatus -type transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe
        This example gets the status of the syslog service for NSX Edge node
    #>


    Param (
        [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node,
        [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport,
        [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ($PsBoundParameters.ContainsKey("node")) {
            $uri = "https://$nsxtManager/api/v1/node/services/syslog/status"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
            $response
        }
        if ($PsBoundParameters.ContainsKey("transport")) {
            $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/status"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtSyslogStatus

Function Get-NsxtSyslogExporter {
    <#
        .SYNOPSIS
        Gets Syslog exporters

        .DESCRIPTION
        The Get-NsxtSyslogExporter cmdlet gets the Syslog exporters configures for NSX-T Data Center components

        .EXAMPLE
        Get-NsxtSyslogExporter -node
        This example gets the configuration of the syslog exporters for NSX Manager node

        .EXAMPLE
        Get-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe
        This example gets the configuration of the syslog exporters for NSX Edge node
    #>


    Param (
        [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node,
        [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport,
        [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ($PsBoundParameters.ContainsKey("node")) {
            $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
            $response.results
        }
        if ($PsBoundParameters.ContainsKey("transport")) {
            $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
            $response.results
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtSyslogExporter

Function Set-NsxtSyslogExporter {
    <#
        .SYNOPSIS
        Sets Syslog exporters

        .DESCRIPTION
        The Set-NsxtSyslogExporter cmdlet Sets the Syslog exporters configures for NSX-T Data Center components

        .EXAMPLE
        Set-NsxtSyslogExporter -node -exporterName Syslog1 -logLevel INFO -port 514 -protocol TCP -server sfo-vrli01.sfo.rainpole.io
        This example gets the status of the syslog service for NSX Manager node

        .EXAMPLE
        Set-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe -exporterName Syslog1 -logLevel INFO -port 514 -protocol TCP -server sfo-vrli01.sfo.rainpole.io
        This example gets the status of the syslog service for NSX Edge node
    #>


    Param (
        [Parameter ( ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node,
        [Parameter ( ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport,
        [Parameter ( ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exporterName,
        [Parameter ( Mandatory = $true)] [ValidateSet("EMERG", "ALERT", "CRIT", "ERR", "WARNING", "NOTICE", "INFO", "DEBUG")]  [String]$logLevel,
        [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$port,
        [Parameter ( Mandatory = $true)] [ValidateSet("TCP", "TLS", "UDP", "LI", "LI-TLS")] [String]$protocol,
        [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server
    )

      Try {
        $json = '{
            "exporter_name": "'
 + $exporterName + '",
            "level": "'
 + $logLevel + '",
            "port": '
 + $port + ',
            "protocol": "'
 + $protocol + '",
            "server": "'
 + $server + '"
        }'


        if ($PsBoundParameters.ContainsKey("node")) {
            $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters"
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -ContentType application/json -body $json
            $response
        }
        if ($PsBoundParameters.ContainsKey("transport")) {
            $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters"
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -ContentType application/json -body $json
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtSyslogExporter

Function Remove-NsxtSyslogExporter {
    <#
        .SYNOPSIS
        Delete Syslog exporters

        .DESCRIPTION
        The Remove-NsxtSyslogExporter cmdlet deletes the Syslog exporters for NSX-T Data Center components

        .EXAMPLE
        Remove-NsxtSyslogExporter -node -exporterName Syslog1
        This example deletes the syslog exporters for NSX Manager node

        .EXAMPLE
        Remove-NsxtSyslogExporter -transport -id f3bd5bf0-23cd-4c6f-8de5-ab065f74d7fe -exporterName Syslog1
        This example deletes the syslog exporters for for NSX Edge node
    #>


    Param (
        [Parameter (ParameterSetName = 'node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$node,
        [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [Switch]$transport,
        [Parameter (ParameterSetName = 'transport', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter ( Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$exporterName
    )

    Try {
        if ($PsBoundParameters.ContainsKey("node")) {
            $uri = "https://$nsxtManager/api/v1/node/services/syslog/exporters/$exporterName"
            $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders
            $response
        }
        if ($PsBoundParameters.ContainsKey("transport")) {
            $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/node/services/syslog/exporters/$exporterName"
            $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $nsxtHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-NsxtSyslogExporter

Function Copy-vRealizeLoadBalancer {
    <#
        .SYNOPSIS
        Creates a Load Balancer for vRealize component failover

        .DESCRIPTION
        Creates a new loadbalancer in a secondary VMware Cloud Foundation instance by duplicating the settings of the existing load balancer in the instance where the vRealize components are currently running

        .EXAMPLE
        Copy-vRealizeLoadBalancer -sddcManagerAFQDN sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPassword VMw@re1! -sddcManagerBFQDN lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPassword VMw@re1! -serviceInterfaceIP 192.168.11.3 -wsaCertName xint-wsa01
        This example copies settings from Load Balancer in SDDC A to a new Load Balancer in SDDC B
    #>

    
    Param (
        [Parameter (Mandatory = $true)] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [String]$sddcManagerAPassword,
        [Parameter (Mandatory = $true)] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [String]$sddcManagerBPassword,
        [Parameter (Mandatory = $true)] [String]$serviceInterfaceIp,
        [Parameter (Mandatory = $true)] [String]$wsaCertName
    )

    Try {
        # Setup Parameters
        $t1Name = "recovery-t1-gw01"
        $siName = "recovery-t1-gw01-si01"
        $lbName = "recovery-lb01"

        #Retrieve Edge Cluster Details from SDDC Manager B
        Request-VCFToken -fqdn $sddcManagerBFqdn -Username $sddcManagerBUser -Password $sddcManagerBPassword | Out-Null
        $mgmtNsxtClusterID = (Get-VCFWorkloadDomain | Where-Object {$_.type -eq "Management"}).nsxtCluster.id
        $edgeClusterName = (Get-VCFEdgeCluster | Where-Object {$_.nsxtCluster.id -eq $mgmtNsxtClusterID}).Name
        
        #Retrieve Segment, WSA, VRA and vROPS Details from SDDC Manager A
        Request-VCFToken -fqdn $sddcManagerAFqdn -Username $sddcManagerAUser -Password $sddcManagerAPassword | Out-Null
        $xintSegmentDetails = Get-VCFApplicationVirtualNetwork | Where-Object {$_.regionType -eq "X_REGION"}
        $wsaDetailsObject = Get-WSAServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword
        $vraDetailsObject = Get-vRAServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword
        $vropsDetailsObject = Get-vROPsServerDetail -fqdn $sddcManagerAFqdn -username $sddcManagerAUser -password $sddcManagerAPassword

        #Add Cert to NSX
        $nsxManager = Get-NsxtServerDetail -fqdn $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPassword -domainType MANAGEMENT
        Request-NsxToken -fqdn $nsxManager.fqdn -username $nsxManager.adminUser -password $nsxManager.adminPass | Out-Null

        #Get xint segment ID from NSX LM on recovery site
        $segmentID = Get-NsxtGlobalSegmentID -segmentName $xintSegmentDetails.name
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
    
    Try {
        if ((!$edgeClusterName) -OR (!$xintSegmentDetails) -OR (!$wsaDetailsObject) -OR ((!$vraDetailsObject) -AND (!$vropsDetailsObject))) {
            Write-Output "Requirements for Copying Load Balancer not Met".
            if (!$wsaDetailsObject) {Write-Output "Clustered Workspace ONE Access was not discovered in the source SDDC Manager instance"}
            if ((!$vraDetailsObject) -AND (!$vropsDetailsObject)) {Write-Output "Neither vRealize Automation nor vRealize Operations Manager was discovered in the source SDDC Manager instance"}
            if (!$xintSegmentDetails) {Write-Output "Cross-Region Segment was discovered in the target SDDC Manager instance"}
            if (!$edgeClusterName) {Write-Output "Management Edge Cluster was not discovered in the target SDDC Manager instance"}
        }
        else {    
            #Create a Load Balancer Spec
            if (!$vraDetailsObject) {
                $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vropsDetailsObject $vropsDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID
            }
            elseif (!$vropsDetailsObject) {
                $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vraDetailsObject $vraDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID
            }
            else {
                $lbCustomObject = New-vRealizeLoadBalancerSpec -xintSegmentDetails $xintSegmentDetails -serviceInterfaceIp $serviceInterfaceIp -wsaDetailsObject $wsaDetailsObject -vraDetailsObject $vraDetailsObject -vropsDetailsObject $vropsDetailsObject -wsaCertName $wsaCertName -t1Name $t1Name -lbName $lbName -siName $siName -segmentID $segmentID
            }

            $wsaCertPresent = Add-CertToNsxCertificateStore -certName $wsaCertName
        
            if ($wsaCertPresent -eq $true) {
                $ConfigJson = $lbCustomObject.t1_spec.gw | ConvertTo-Json
                New-NsxtTier1 -tier1Gateway $t1Name -json $ConfigJson
                $edgeClusterID = (Get-NsxtEdgeCluster -name $edgeClusterName).id
                $ConfigJson = '{"edge_cluster_path": "/infra/sites/default/enforcement-points/default/edge-clusters/' + $edgeClusterID + '"}'
                Set-NsxtTier1 -tier1Gateway $t1name -json $ConfigJson
                $ConfigJson = '{
                    "segment_path": "'
+ $lbCustomObject.t1_spec.service_interface.segment_path + '",
                    "subnets": [
                    {
                        "ip_addresses": [ "'
+ $lbCustomObject.t1_spec.service_interface.subnets.ip_addresses + '" ],
                        "prefix_len": "'
+ $lbCustomObject.t1_spec.service_interface.subnets.prefix_len + '"
                    }
                    ]
                    }'

                New-NsxtTier1ServiceInterface -tier1Gateway $t1name -interfaceId $lbCustomObject.t1_spec.service_interface.id -json $ConfigJson
                $ConfigJson = '{
                    "network": "'
+ $lbCustomObject.t1_spec.static_routes.network + '",
                    "next_hops": [
                        {
                            "ip_address": "'
+ $lbCustomObject.t1_spec.static_routes.next_hops.ip_address + '",
                            "admin_distance": '
+ $lbCustomObject.t1_spec.static_routes.next_hops.admin_distance + ',
                            "scope": [
                                "'
+ $lbCustomObject.t1_spec.static_routes.next_hops.scope +'"
                            ]
                        }
                    ],
                    "display_name": "'
+ $lbCustomObject.t1_spec.static_routes.display_name + '"
                    }'

                New-NsxtTier1StaticRoute -tier1Gateway $t1name -segment $xintSegmentDetails.name -json $ConfigJson
                $ConfigJson = $lbCustomObject.lb_spec.lb_service | ConvertTo-Json
                New-NsxtLoadBalancer -lbName $lbName -json $ConfigJson
                Foreach ($monitor in $lbCustomObject.lb_spec.service_monitors) {
                    Try {
                        $ConfigJson = $monitor | ConvertTo-Json -Depth 10
                        New-NsxtLBServiceMonitor -monitorName $monitor.display_name -json $ConfigJson
                    }
                    Catch {
                        Debug-ExceptionWriter -object $_
                    }
                }
                Foreach ($profile in $lbCustomObject.lb_spec.app_profiles) {
                    Try {
                        $ConfigJson = $profile | ConvertTo-Json
                        New-NsxtLBAppProfile -appProfileName $profile.display_name -json $ConfigJson
                    }
                    Catch {
                        Debug-ExceptionWriter -object $_
                    }
                }
                Foreach ($profile in $lbCustomObject.lb_spec.persistence_profiles) {
                    Try {
                        $ConfigJson = $profile | ConvertTo-Json
                        New-NsxtLBPersistenceAppProfile -appProfileName $profile.display_name -json $ConfigJson
                    }
                    Catch {
                        Debug-ExceptionWriter -object $_
                    }
                }
                Foreach ($pool in $lbCustomObject.lb_spec.pools) {
                    Try {
                        $ConfigJson = $pool | ConvertTo-Json
                        New-NsxtLBPool -poolName $pool.display_name -json $ConfigJson
                    }
                    Catch {
                        Debug-ExceptionWriter -object $_
                    }
                }
                Foreach ($virtualServer in $lbCustomObject.lb_spec.virtual_Servers) {
                    Try {
                        $ConfigJson = $virtualServer | ConvertTo-Json -Depth 10
                        New-NsxtLBVirtualServer -virtualServerName $virtualServer.display_name -json $ConfigJson
                    }
                    Catch {
                        Debug-ExceptionWriter -object $_
                    }
                }
            }
            else {
                Write-Error "Aborting remainder of NSX-T Load Balancer configuration until certificate files present"
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Copy-vRealizeLoadBalancer

Function New-vRealizeLoadBalancerSpec {
    Param (
        [Parameter (Mandatory = $true)] [Array]$xintSegmentDetails,
        [Parameter (Mandatory = $true)] [Array]$serviceInterfaceIp,
        [Parameter (Mandatory = $true)] [Array]$wsaDetailsObject,
        [Parameter (Mandatory = $false)] [Array]$vraDetailsObject,
        [Parameter (Mandatory = $false)] [Array]$vropsDetailsObject,
        [Parameter (Mandatory = $true)] [String]$wsaCertName,
        [Parameter (Mandatory = $true)] [String]$t1Name,
        [Parameter (Mandatory = $true)] [String]$lbName,
        [Parameter (Mandatory = $true)] [String]$siName,
        [Parameter (Mandatory = $true)] [String]$segmentID
    )

    $xintSegmentName = $xintSegmentDetails.name
    $xintSegmentServiceInterfacePrefixLength = cidrMaskLookup -source mask -value $xintSegmentDetails.subnetMask
    $xintSegmentNextHopIP = $xintSegmentDetails.gateway

    $xintWsaVip = $wsaDetailsObject.loadBalancerIpAddress
    $xintWsaNode1Ip = $wsaDetailsObject.node1IpAddress
    $xintWsaNode2Ip = $wsaDetailsObject.node2IpAddress
    $xintWsaNode3Ip = $wsaDetailsObject.node3IpAddress
    $xintWsaNode1Name = $wsaDetailsObject.fqdn[0].split(".")[0]
    $xintWsaNode2Name = $wsaDetailsObject.fqdn[1].split(".")[0]
    $xintWsaNode3Name = $wsaDetailsObject.fqdn[2].split(".")[0]

    If ($vropsDetailsObject)
    {
        $xintVropsVip = $vropsDetailsObject.loadBalancerIpAddress
        $xintVropsNode1Ip = $vropsDetailsObject.node1IpAddress
        $xintVropsNode2Ip = $vropsDetailsObject.node2IpAddress
        $xintVropsNode3Ip = $vropsDetailsObject.node3IpAddress
        $xintVropsNode1Name = $vropsDetailsObject.fqdn[0].split(".")[0]
        $xintVropsNode2Name = $vropsDetailsObject.fqdn[1].split(".")[0]
        $xintVropsNode3Name = $vropsDetailsObject.fqdn[2].split(".")[0]    
    }

    If ($vraDetailsObject)
    {
        $xintVraVip = $vraDetailsObject.loadBalancerIpAddress
        $xintVraNode1Ip = $vraDetailsObject.node1IpAddress
        $xintVraNode2Ip = $vraDetailsObject.node2IpAddress
        $xintVraNode3Ip = $vraDetailsObject.node3IpAddress
        $xintVraNode1Name = $vraDetailsObject.fqdn[0].split(".")[0]
        $xintVraNode2Name = $vraDetailsObject.fqdn[1].split(".")[0]
        $xintVraNode3Name = $vraDetailsObject.fqdn[2].split(".")[0]   
    }

    $lbJson += '{'
    $lbJson += '"t1_spec":{'
        $lbJson += '"gw":{'
            $lbJson += '"resource_type": "Tier1",'
            $lbJson += '"id": "<!--REPLACE WITH T1NAME-->",'
            $lbJson += '"force_whitelisting": false,'
            $lbJson += '"tier0_path": ""'
        $lbJson += '},'
        $lbJson += '"service_interface":{'
            $lbJson += '"segment_path": "/global-infra/segments/<!--REPLACE WITH SEGMENTID-->",'
            $lbJson += '"id": "<!--REPLACE WITH siName-->",'
            $lbJson += '"overridden": false,'
            $lbJson += '"subnets": ['
            $lbJson += '{'
            $lbJson += '"ip_addresses": ['
            $lbJson += '"<!--REPLACE WITH SI IP-->"'
            $lbJson += '],'
            $lbJson += '"prefix_len": <!--REPLACE WITH SI PREFIX-->'
            $lbJson += '}'
            $lbJson += ']'
        $lbJson += '},'
        $lbJson += '"static_routes":{'
            $lbJson += '"network": "0.0.0.0/0",'
            $lbJson += '"next_hops": ['
                $lbJson += '{'
                    $lbJson += '"ip_address": "<!--REPLACE WITH NEXT HOP IP-->",'
                    $lbJson += '"admin_distance": 1,'
                    $lbJson += '"scope": ['
                        $lbJson += '"/infra/tier-1s/<!--REPLACE WITH T1NAME-->/locale-services/default/interfaces/<!--REPLACE WITH siName-->"'
                    $lbJson += '] '
                $lbJson += '}'
            $lbJson += '],'
            $lbJson += '"display_name": "default"'
        $lbJson += '}'
    $lbJson += '},'
        $lbJson += '"lb_spec": {'
            $lbJson += '"lb_service": ['
                $lbJson += '{'
                    $lbJson += '"display_name": "<!--REPLACE WITH LB NAME-->",'
                    $lbJson += '"resource_type": "LBService",'
                    $lbJson += '"enabled": true,'
                    $lbJson += '"size": "SMALL",'
                    $lbJson += '"connectivity_path":""'
                $lbJson += '}'
            $lbJson += '],'
            $lbJson += '"service_monitors": ['
            If ($vropsDetailsObject)
                {
                    $lbJson += '{'
                        $lbJson += '"display_name": "vrops-https-monitor",'
                        $lbJson += '"description": "vRealize Operations Manager HTTPS Monitor",'
                        $lbJson += '"resource_type": "LBHttpsMonitorProfile",'
                        $lbJson += '"monitor_port": "443",'
                        $lbJson += '"interval": "5",'
                        $lbJson += '"fall_count": "3",'
                        $lbJson += '"rise_count": "3",'
                        $lbJson += '"timeout": "16",'
                        $lbJson += '"request_method": "GET",'
                        $lbJson += '"request_url": "/suite-api/api/deployment/node/status?services=api&services=adminui&services=ui",'
                        $lbJson += '"request_version": "HTTP_VERSION_1_1",'
                        $lbJson += '"response_status_codes": ['
                            $lbJson += '"200","204","301"'
                        $lbJson += '],'
                        $lbJson += '"response_body": "ONLINE",'
                        $lbJson += '"server_ssl_profile_binding": {'
                            $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"'
                        $lbJson += '}'
                    $lbJson += '},'
                }
                If ($vraDetailsObject)
                {
                    $lbJson += '{'
                        $lbJson += '"display_name": "vra-http-monitor",'
                        $lbJson += '"description": "vRealize Automation HTTP Monitor",'
                        $lbJson += '"resource_type": "LBHttpMonitorProfile",'
                        $lbJson += '"monitor_port": "8008",'
                        $lbJson += '"interval": "3",'
                        $lbJson += '"fall_count": "3",'
                        $lbJson += '"rise_count": "3",'
                        $lbJson += '"timeout": "10",'
                        $lbJson += '"request_method": "GET",'
                        $lbJson += '"request_url": "/health",'
                        $lbJson += '"request_version": "HTTP_VERSION_1_1",'
                        $lbJson += '"response_status_codes": ['
                            $lbJson += '"200"'
                        $lbJson += '],'
                        $lbJson += '"response_body": ""'
                    $lbJson += '},'
                }
                $lbJson += '{'
                    $lbJson += '"display_name": "wsa-https-monitor",'
                    $lbJson += '"description": "Clustered Workspace ONE Access HTTPS Monitor",'
                    $lbJson += '"resource_type": "LBHttpsMonitorProfile",'
                    $lbJson += '"monitor_port": "443",'
                    $lbJson += '"interval": "3",'
                    $lbJson += '"fall_count": "3",'
                    $lbJson += '"rise_count": "3",'
                    $lbJson += '"timeout": "10",'
                    $lbJson += '"request_method": "GET",'
                    $lbJson += '"request_url": "/SAAS/API/1.0/REST/system/health/heartbeat",'
                    $lbJson += '"request_version": "HTTP_VERSION_1_1",'
                    $lbJson += '"response_status_codes": ['
                        $lbJson += '"200","201"'
                    $lbJson += '],'
                    $lbJson += '"response_body": "ok",'
                    $lbJson += '"server_ssl_profile_binding": {'
                        $lbJson += '"client_certificate_path": "/infra/certificates/<!--REPLACE WITH XREG WSA CERT-->",'
                        $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"'
                    $lbJson += '}'
                $lbJson += '}'
            $lbJson += '],'
            $lbJson += '"app_profiles": ['
            If ($vropsDetailsObject)
            {
                $lbJson += '{'
                    $lbJson += '"display_name": "vrops-http-app-profile-redirect",'
                    $lbJson += '"description": "Cross-Instance vRealize Operations Manager redirect HTTP to HTTPs",'
                    $lbJson += '"resource_type": "LBHttpProfile",'
                    $lbJson += '"idle_timeout": "1800",'
                    $lbJson += '"request_header_size": "1024",'
                    $lbJson += '"response_header_size": "4096",'
                    $lbJson += '"http_redirect_to_https": "True",'
                    $lbJson += '"response_timeout": "60",'
                    $lbJson += '"ntlm": "False"'
                $lbJson += '},'
                $lbJson += '{'
                    $lbJson += '"display_name": "vrops-tcp-app-profile",'
                    $lbJson += '"description": "vRealize Operations Manager TCP App Profile",'
                    $lbJson += '"resource_type": "LBFastTcpProfile",'
                    $lbJson += '"idle_timeout": "1800",'
                    $lbJson += '"ha_flow_mirroring_enabled": "False",'
                    $lbJson += '"close_timeout": "8"'
                $lbJson += '},'
            }
            If ($vraDetailsObject)
            {
                $lbJson += '{'
                    $lbJson += '"display_name": "vra-tcp-app-profile",'
                    $lbJson += '"description": "vRealize Automation TCP App Profile",'
                    $lbJson += '"resource_type": "LBFastTcpProfile",'
                    $lbJson += '"idle_timeout": "1800",'
                    $lbJson += '"ha_flow_mirroring_enabled": "False",'
                    $lbJson += '"close_timeout": "8"'
                $lbJson += '},'
                $lbJson += '{'
                    $lbJson += '"display_name": "vra-http-app-profile-redirect",'
                    $lbJson += '"description": "vRealize Automation Profile to redirect HTTP to HTTPs",'
                    $lbJson += '"resource_type": "LBHttpProfile",'
                    $lbJson += '"idle_timeout": "1800",'
                    $lbJson += '"request_header_size": "1024",'
                    $lbJson += '"response_header_size": "4096",'
                    $lbJson += '"http_redirect_to_https": "True",'
                    $lbJson += '"response_timeout": "60",'
                    $lbJson += '"ntlm": "False"'
                $lbJson += '},'
            }
                $lbJson += '{'
                    $lbJson += '"display_name": "wsa-http-app-profile",'
                    $lbJson += '"description": "Clustered Workspace ONE Access HTTP Redirect",'
                    $lbJson += '"resource_type": "LBHttpProfile",'
                    $lbJson += '"idle_timeout": "3600",'
                    $lbJson += '"x_forwarded_for": "INSERT",'
                    $lbJson += '"request_header_size": "1024",'
                    $lbJson += '"response_header_size": "4096",'
                    $lbJson += '"http_redirect_to_https": "False",'
                    $lbJson += '"response_timeout": "60",'
                    $lbJson += '"ntlm": "False"'
                $lbJson += '},'
                $lbJson += '{'
                    $lbJson += '"display_name": "wsa-http-app-profile-redirect",'
                    $lbJson += '"description": "Clustered Workspace ONE Access redirect HTTP to HTTPs",'
                    $lbJson += '"resource_type": "LBHttpProfile",'
                    $lbJson += '"idle_timeout": "3600",'
                    $lbJson += '"request_header_size": "1024",'
                    $lbJson += '"response_header_size": "4096",'
                    $lbJson += '"http_redirect_to_https": "True",'
                    $lbJson += '"response_timeout": "60",'
                    $lbJson += '"ntlm": "False"'
                $lbJson += '}'
            $lbJson += '],'
            $lbJson += '"persistence_profiles": ['
            If ($vropsDetailsObject)
            {
                $lbJson += '{'
                    $lbJson += '"display_name": "vrops-source-ip-persistence-profile",'
                    $lbJson += '"description": "vRealize Operations Manager Analytics Cluster Source IP Persistence Profile",'
                    $lbJson += '"resource_type": "LBSourceIpPersistenceProfile",'
                    $lbJson += '"persistence_shared": "False",'
                    $lbJson += '"purge": "FULL",'
                    $lbJson += '"ha_persistence_mirroring_enabled": "False"'
                $lbJson += '},'
            }
                $lbJson += '{'
                    $lbJson += '"display_name": "wsa-cookie-persistence-profile",'
                    $lbJson += '"description": "Cookie Persistence Profile",'
                    $lbJson += '"resource_type": "LBCookiePersistenceProfile",'
                    $lbJson += '"persistence_shared": "False",'
                    $lbJson += '"cookie_mode": "REWRITE",'
                    $lbJson += '"cookie_name": "JSESSIONID",'
                    $lbJson += '"cookie_fallback": "True",'
                    $lbJson += '"cookie_garble": "True"'
                $lbJson += '}'
            $lbJson += '],'
            $lbJson += '"pools": ['
            If ($vropsDetailsObject)
            {
                $lbJson += '{'
                    $lbJson += '"display_name": "vrops-server-pool",'
                    $lbJson += '"description": "vRealize Operations Manager Analytics Cluster Server Pool",'
                    $lbJson += '"algorithm": "LEAST_CONNECTION",'
                    $lbJson += '"active_monitor_paths": ['
                        $lbJson += '"/infra/lb-monitor-profiles/vrops-https-monitor"'
                    $lbJson += '],'
                    $lbJson += '"snat_translation": {'
                        $lbJson += '"type": "LBSnatAutoMap"'
                    $lbJson += '},'
                    $lbJson += '"members": ['
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH VROPS NODE 1 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH VROPS NODE 1 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '},'
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH VROPS NODE 2 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH VROPS NODE 2 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '},'
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH VROPS NODE 3 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH VROPS NODE 3 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '}'
                    $lbJson += ']'
                $lbJson += '},'
            }
            If ($vraDetailsObject)
            {    
                $lbJson += '{'
                    $lbJson += '"display_name": "vra-server-pool",'
                    $lbJson += '"description": "vRealize Automation Cluster Pool",'
                    $lbJson += '"algorithm": "LEAST_CONNECTION",'
                    $lbJson += '"active_monitor_paths": ['
                        $lbJson += '"/infra/lb-monitor-profiles/vra-http-monitor"'
                        $lbJson += '],'
                    $lbJson += '"snat_translation": {'
                        $lbJson += '"type": "LBSnatAutoMap"'
                    $lbJson += '},'
                    $lbJson += '"members": ['
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH VRA NODE 1 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH VRA NODE 1 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '},'
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH VRA NODE 2 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH VRA NODE 2 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '},'
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH VRA NODE 3 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH VRA NODE 3 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '}'
                    $lbJson += ']'
                $lbJson += '},'
            }
                $lbJson += '{'
                    $lbJson += '"display_name": "wsa-server-pool",'
                    $lbJson += '"description": "Clustered Workspace ONE Access Server Pool",'
                    $lbJson += '"algorithm": "LEAST_CONNECTION",'
                    $lbJson += '"active_monitor_paths": ['
                        $lbJson += '"/infra/lb-monitor-profiles/wsa-https-monitor"'
                    $lbJson += '],'
                    $lbJson += '"snat_translation": {'
                        $lbJson += '"type": "LBSnatAutoMap"'
                    $lbJson += '},'
                    $lbJson += '"members": ['
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH WSA NODE 1 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH WSA NODE 1 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '},'
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH WSA NODE 2 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH WSA NODE 2 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '},'
                        $lbJson += '{'
                            $lbJson += '"display_name": "<!--REPLACE WITH WSA NODE 3 NAME-->",'
                            $lbJson += '"backup_member": "false",'
                            $lbJson += '"weight": 1,'
                            $lbJson += '"admin_state": "ENABLED",'
                            $lbJson += '"ip_address": "<!--REPLACE WITH WSA NODE 3 IP-->",'
                            $lbJson += '"port": "443"'
                        $lbJson += '}'
                    $lbJson += ']'
                $lbJson += '}'
            $lbJson += '],'
            $lbJson += '"virtual_servers": ['
            If ($vropsDetailsObject)
            {
                $lbJson += '{'
                    $lbJson += '"display_name": "vrops-https",'
                    $lbJson += '"description": "vRealize Operations Manager Analytics Cluster UI",'
                    $lbJson += '"resource_type": "LBVirtualServer",'
                    $lbJson += '"enabled": "true",'
                    $lbJson += '"lb_persistence_profile_path": "/infra/lb-persistence-profiles/vrops-source-ip-persistence-profile",'
                    $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vrops-tcp-app-profile",'
                    $lbJson += '"pool_path": "/infra/lb-pools/vrops-server-pool",'
                    $lbJson += '"lb_service_path": "/infra/lb-services/<!--REPLACE WITH LB NAME-->",'
                    $lbJson += '"ip_address": "<!--REPLACE WITH VROPS VIP-->",'
                    $lbJson += '"ports": ['
                        $lbJson += '"443"'
                    $lbJson += ']'
                $lbJson += '},'
                $lbJson += '{'
                    $lbJson += '"display_name": "vrops-http-redirect",'
                    $lbJson += '"description": "vRealize Operations Manager Analytics Cluster HTTP to HTTPS Redirect",'
                    $lbJson += '"resource_type": "LBVirtualServer",'
                    $lbJson += '"enabled": "true",'
                    $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vrops-http-app-profile-redirect",'
                    $lbJson += '"lb_service_path": "/infra/lb-services/<!--REPLACE WITH LB NAME-->",'
                    $lbJson += '"ip_address": "<!--REPLACE WITH VROPS VIP-->",'
                    $lbJson += '"ports": ['
                        $lbJson += '"80"'
                    $lbJson += ']'
                $lbJson += '},'
            }
            If ($vraDetailsObject)
            {
                $lbJson += '{'
                    $lbJson += '"display_name": "vra-https",'
                    $lbJson += '"description": "vRealize Automation Cluster UI",'
                    $lbJson += '"resource_type": "LBVirtualServer",'
                    $lbJson += '"enabled": "true",'
                    $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vra-tcp-app-profile",'
                    $lbJson += '"pool_path": "/infra/lb-pools/vra-server-pool",'
                    $lbJson += '"lb_service_path": "/infra/lb-services/<!--REPLACE WITH LB NAME-->",'
                    $lbJson += '"ip_address": "<!--REPLACE WITH VRA VIP-->",'
                    $lbJson += '"ports": ['
                        $lbJson += '"443"'
                    $lbJson += ']'
                $lbJson += '},'
                $lbJson += '{'
                    $lbJson += '"display_name": "vra-http-redirect",'
                    $lbJson += '"description": "vRealize Automation HTTP to HTTPS Redirect",'
                    $lbJson += '"resource_type": "LBVirtualServer",'
                    $lbJson += '"enabled": "true",'
                    $lbJson += '"application_profile_path": "/infra/lb-app-profiles/vra-http-app-profile-redirect",'
                    $lbJson += '"lb_service_path": "/infra/lb-services/<!--REPLACE WITH LB NAME-->",'
                    $lbJson += '"ip_address": "<!--REPLACE WITH VRA VIP-->",'
                    $lbJson += '"ports": ['
                        $lbJson += '"80"'
                    $lbJson += ']'
                $lbJson += '},'
            }
                $lbJson += '{'
                    $lbJson += '"display_name": "wsa-https",'
                    $lbJson += '"description": "Clustered Workspace ONE Access Cluster UI",'
                    $lbJson += '"resource_type": "LBVirtualServer",'
                    $lbJson += '"enabled": "true",'
                    $lbJson += '"lb_persistence_profile_path": "/infra/lb-persistence-profiles/wsa-cookie-persistence-profile",'
                    $lbJson += '"application_profile_path": "/infra/lb-app-profiles/wsa-http-app-profile",'
                    $lbJson += '"pool_path": "/infra/lb-pools/wsa-server-pool",'
                    $lbJson += '"lb_service_path": "/infra/lb-services/<!--REPLACE WITH LB NAME-->",'
                    $lbJson += '"ip_address": "<!--REPLACE WITH WSA VIP-->",'
                    $lbJson += '"ports": ['
                        $lbJson += '"443"'
                    $lbJson += '],'
                    $lbJson += '"client_ssl_profile_binding": {'
                        $lbJson += '"default_certificate_path": "/infra/certificates/<!--REPLACE WITH XREG WSA CERT-->",'
                        $lbJson += '"ssl_profile_path": "/infra/lb-client-ssl-profiles/default-balanced-client-ssl-profile"'
                    $lbJson += '},'
                    $lbJson += '"server_ssl_profile_binding": {'
                        $lbJson += '"client_certificate_path": "/infra/certificates/<!--REPLACE WITH XREG WSA CERT-->",'
                        $lbJson += '"ssl_profile_path": "/infra/lb-server-ssl-profiles/default-balanced-server-ssl-profile"'
                    $lbJson += '},'
                    $lbJson += '"rules": ['
                        $lbJson += '{'
                            $lbJson += '"match_strategy": "ALL",'
                            $lbJson += '"phase": "HTTP_REQUEST_REWRITE",'
                            $lbJson += '"actions": ['
                                $lbJson += '{'
                                    $lbJson += '"type": "LBHttpRequestHeaderRewriteAction",'
                                    $lbJson += '"header_name": "Remoteport",'
                                    $lbJson += '"header_value": "$_remote_port"'
                                $lbJson += '}'
                            $lbJson += ']'
                        $lbJson += '}'
                    $lbJson += ']'
                $lbJson += '},'
                $lbJson += '{'
                    $lbJson += '"display_name": "wsa-http-redirect",'
                    $lbJson += '"description": "Clustered Workspace ONE Access Cluster HTTP to HTTPS Redirect",'
                    $lbJson += '"resource_type": "LBVirtualServer",'
                    $lbJson += '"enabled": "true",'
                    $lbJson += '"application_profile_path": "/infra/lb-app-profiles/wsa-http-app-profile-redirect",'
                    $lbJson += '"lb_service_path": "/infra/lb-services/<!--REPLACE WITH LB NAME-->",'
                    $lbJson += '"ip_address": "<!--REPLACE WITH WSA VIP-->",'
                    $lbJson += '"ports": ['
                        $lbJson += '"80"'
                    $lbJson += ']'
                $lbJson += '}'
            $lbJson += ']'
        $lbJson += '}'
    $lbJson += '}'

    $lbJson = $lbJson | ForEach-Object { $_ `
            -replace '<!--REPLACE WITH T1NAME-->', $t1Name `
            -replace '<!--REPLACE WITH xintSegmentName-->', $xintSegmentName `
            -replace '<!--REPLACE WITH SEGMENTID-->', $segmentID `
            -replace '<!--REPLACE WITH siName-->', $siName `
            -replace '<!--REPLACE WITH SI IP-->', $serviceInterfaceIp `
            -replace '<!--REPLACE WITH XREGION CIDR-->', $xintionVXLAN `
            -replace '<!--REPLACE WITH NEXT HOP IP-->', $xintSegmentNextHopIP `
            -replace '<!--REPLACE WITH SI PREFIX-->', $xintSegmentServiceInterfacePrefixLength `
            -replace '<!--REPLACE WITH LB NAME-->', $lbName `
            -replace '<!--REPLACE WITH XREG WSA CERT-->', $wsaCertName `
            -replace '<!--REPLACE WITH WSA NODE 1 NAME-->', $xintWsaNode1Name `
            -replace '<!--REPLACE WITH WSA NODE 2 NAME-->', $xintWsaNode2Name `
            -replace '<!--REPLACE WITH WSA NODE 3 NAME-->', $xintWsaNode3Name `
            -replace '<!--REPLACE WITH WSA NODE 1 IP-->', $xintWsaNode1IP `
            -replace '<!--REPLACE WITH WSA NODE 2 IP-->', $xintWsaNode2IP `
            -replace '<!--REPLACE WITH WSA NODE 3 IP-->', $xintWsaNode3IP `
            -replace '<!--REPLACE WITH VROPS NODE 1 NAME-->', $xintVropsNode1Name `
            -replace '<!--REPLACE WITH VROPS NODE 2 NAME-->', $xintVropsNode2Name `
            -replace '<!--REPLACE WITH VROPS NODE 3 NAME-->', $xintVropsNode3Name `
            -replace '<!--REPLACE WITH VROPS NODE 1 IP-->', $xintVropsNode1Ip `
            -replace '<!--REPLACE WITH VROPS NODE 2 IP-->', $xintVropsNode2Ip `
            -replace '<!--REPLACE WITH VROPS NODE 3 IP-->', $xintVropsNode3Ip `
            -replace '<!--REPLACE WITH VRA NODE 1 NAME-->', $xintVraNode1Name `
            -replace '<!--REPLACE WITH VRA NODE 2 NAME-->', $xintVraNode2Name `
            -replace '<!--REPLACE WITH VRA NODE 3 NAME-->', $xintVraNode3Name `
            -replace '<!--REPLACE WITH VRA NODE 1 IP-->', $xintVraNode1Ip `
            -replace '<!--REPLACE WITH VRA NODE 2 IP-->', $xintVraNode2Ip `
            -replace '<!--REPLACE WITH VRA NODE 3 IP-->', $xintVraNode3Ip `
            -replace '<!--REPLACE WITH WSA VIP-->', $xintWsaVip `
            -replace '<!--REPLACE WITH VROPS VIP-->', $xintVropsVip `
            -replace '<!--REPLACE WITH VRA VIP-->', $xintVraVip `
    }
    $lbCustomObject = $lbJson | ConvertFrom-Json
    Return $lbCustomObject
}
Export-ModuleMember -Function New-vRealizeLoadBalancerSpec

Function Get-NsxtGlobalSegmentID {
    Param (
        [Parameter (Mandatory=$true)]
            [String]$segmentName
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/global-infra/segments/"

        $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
        $segmentObjectId = ($response.results | where-object {$_.display_name -eq $segmentName}).id
    }
    Catch {
        Write-Error $_.Exception.Message
    }
    Return $segmentObjectId
}
Export-ModuleMember -Function Get-NsxtGlobalSegmentID

Function Add-CertToNsxCertificateStore {
    Param (
        [Parameter (Mandatory = $true)] [String]$certName 
    )

    Try {
        $pemFile = Get-ExternalFileName -title "Select the Certificate Chain PEM File for Clustered WSA (.pem)" -fileType "pem" -location "default"
    }
    Catch {
        Write-Error $_.Exception.Message
    }
    Try {
        $keyFile = Get-ExternalFileName -title "Select the Key File for Clustered WSA (.key)" -fileType "key" -location "default"
    }
    Catch {
        Write-Error $_.Exception.Message
    }
    
    $certAlreadyImported = ""
    
    #check for existing certificate
    Try {
        $certAlreadyImported = Get-NsxtCertificate -certificateName $certName -ErrorAction SilentlyContinue
    }
    Catch {
        $certAlreadyImported = $false
    }
    
    # report on existing cert or install new cert
    if ($certAlreadyImported) {
        $wsaCertPresent = $true
    }
    else {
            $pemContent = (Get-Content $pemFile) -join "\n"
            $keyContent = (Get-Content $keyFile) -join "\n"
            $body = 
            '{
              "pem_encoded": "<!--REPLACE WITH PEM DATA-->",
              "private_key": "<!--REPLACE WITH KEY DATA-->"
            }
            '

            $body = $body | ForEach-Object { $_ `
                    -replace '<!--REPLACE WITH PEM DATA-->', $pemContent `
                    -replace '<!--REPLACE WITH KEY DATA-->', $keyContent `
            }
            Try {
                Set-NsxtCertificate -certificateName $certName -json $body
                $wsaCertPresent = $true
            }
            Catch {
                Debug-ExceptionWriter -object $_
            }   
    }
    Return $wsaCertPresent
}
Export-ModuleMember -Function Add-CertToNsxCertificateStore

Function Get-NsxtEdgeCluster {
    <#
        .SYNOPSIS
        Gets NSX-T Edge Cluster Id
    
        .DESCRIPTION
        The Get-NsxtEdgeCluster cmdlet gets the Edge Cluster Id
    
        .EXAMPLE
        Get-NsxtEdgeCluster
        This example creates a new Route Map on a Tier 0 Gateway
    #>


    Try {
        $uri = "https://$nsxtmanager/api/v1/edge-clusters"
        $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtEdgeCluster

Function New-NsxtTier1 {
    <#
        .SYNOPSIS
        Creates a Tier 1 Gateway
    
        .DESCRIPTION
        The New-NsxtTier1 cmdlet creates a Teir 1 Gateway
    
        .EXAMPLE
        New-NsxtTier1 -tier1Gateway sfo-w01-ec01-t0-lb01 -json $ConfigJson
        This example creates a new Tier 1 Gateway
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtTier1

Function Set-NsxtTier1 {
    <#
        .SYNOPSIS
        Configures Tier 1 Gateway
    
        .DESCRIPTION
        The Set-NsxtTier1 cmdlet configures a Tier 1 Gateway
    
        .EXAMPLE
        Set-NsxtTier1 -tier1Gateway -json
        This example sets the configuration on a Tier 1 Gateway
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/locale-services/default"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtTier1

Function New-NsxtTier1ServiceInterface {
    <#
        .SYNOPSIS
        Creates Service Interface on Tier 1 Gateway
    
        .DESCRIPTION
        The New-NsxtTier1ServiceInterface cmdlet configures a Service Interface on Tier 1 Gateway
    
        .EXAMPLE
        New-NsxtTier1ServiceInterface -tier1Gateway -interfaceId -json
        This example configures a Service Interface on a Tier 1 Gateway
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$interfaceId,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/locale-services/default/interfaces/$($interfaceId)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtTier1ServiceInterface

Function New-NsxtTier1StaticRoute {
    <#
        .SYNOPSIS
        Creates Static Route on Tier 1 Gateway
    
        .DESCRIPTION
        The New-New-NsxtTier1StaticRoute cmdlet creates a static route on Tier 1 Gateway
    
        .EXAMPLE
        New-NsxtTier1StaticRoute -tier1Gateway -segment -json
        This example configures a Service Interface on a Tier 1 Gateway
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$tier1Gateway,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$segment,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-1s/$($tier1Gateway)/static-routes/$($segment)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtTier1StaticRoute

Function New-NsxtLoadBalancer {
    <#
        .SYNOPSIS
        Creates a Load Balancer
    
        .DESCRIPTION
        The New-NsxtLoadBalancer cmdlet creates a load balancer
    
        .EXAMPLE
        New-NsxtLoadBalancer -lbName -json
        This example creates a load balancer
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$lbName,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-services/$($lbName)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtLoadBalancer

Function New-NsxtLBServiceMonitor { 
    <#
        .SYNOPSIS
        Creates a Load Balancer Service Monitor
    
        .DESCRIPTION
        The New-NsxtLBServiceMonitor cmdlet creates a Load Balancer Service Monitor
    
        .EXAMPLE
        New-NsxtLBServiceMonitor -monitorName -json
        This example creates a Load Balancer Serviec Monitor
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$monitorName,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-monitor-profiles/$($monitorName)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtLBServiceMonitor

Function New-NsxtLBAppProfile {
    <#
        .SYNOPSIS
        Creates a Load Balancer Application Profile
    
        .DESCRIPTION
        The New-NsxtLBAppProfile cmdlet creates a Load Balancer Application Profile
    
        .EXAMPLE
        New-NsxtLBAppProfile -appProfileName -json
        This example creates a Load Balancer Application Profile
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$appProfileName,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )
    
    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-app-profiles/$($appProfileName)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtLBAppProfile

Function New-NsxtLBPersistenceAppProfile {
    <#
        .SYNOPSIS
        Creates a Load Balancer Persistence Application Profile
    
        .DESCRIPTION
        The New-NsxtLBPersistenceAppProfile cmdlet creates a Load Balancer Persistence Application Profile
    
        .EXAMPLE
        New-NsxtLBPersistenceAppProfile -appProfileName -json
        This example creates a Load Balancer Persistence Application Profile
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$appProfileName,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )
    
    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-persistence-profiles/$($appProfileName)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtLBPersistenceAppProfile

Function New-NsxtLBPool {
    <#
        .SYNOPSIS
        Creates a Load Balancer Pool
    
        .DESCRIPTION
        The New-NsxtLBPool cmdlet creates a Load Balancer Pool
    
        .EXAMPLE
        New-NsxtLBPool -poolName -json
        This example creates a Load Balancer Pool
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$poolName,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-pools/$($poolName)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtLBPool

Function New-NsxtLBVirtualServer {
    <#
        .SYNOPSIS
        Creates a Load Balancer Virtual Server
    
        .DESCRIPTION
        The New-NsxtLBVirtualServer cmdlet creates a Load Balancer Virtual Server
    
        .EXAMPLE
        New-NsxtLBVirtualServer -virtualServerName -json
        This example creates a Load Balancer Virtual Server
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$virtualServerName,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    ) 

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/lb-virtual-servers/$($virtualServerName)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-NsxtLBVirtualServer

Function Get-NsxtCertificate {
    <#
        .SYNOPSIS
        Gets NSX-T Certificates
    
        .DESCRIPTION
        The Get-NsxtCertificates cmdlet gets certificates installed in NSX-T
    
        .EXAMPLE
        PS C:\> Get-NsxtCertificates
        This example gets the certificates installed in NSX-T
    #>


    Param (
        [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [String]$certificateName
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("certificateName")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response.results
        }
        elseif ($PsBoundParameters.ContainsKey("certificateName")) {
            $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)"
            $response = Invoke-RestMethod -Method GET -URI $uri -ContentType application/json -headers $nsxtHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtCertificate

Function Set-NsxtCertificate {
    <#
        .SYNOPSIS
        Installs a Certificate in NSX-T
    
        .DESCRIPTION
        The Set-NsxtCertificates cmdlet installs certificates in NSX-T
    
        .EXAMPLE
        Set-NsxtCertificates
        This example installs the certificates in NSX-T
    #>


    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$certificateName,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/certificates/$($certificateName)"
        $response = Invoke-RestMethod -Method PATCH -URI $uri -ContentType application/json -headers $nsxtHeaders -body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtCertificate

Function Get-NsxtNodeProfile {
    <#
        .SYNOPSIS
        Get the NSX node profiles.

        .DESCRIPTION
        The Get-NsxtNodeProfile cmdlet returns the node profiles from the NSX Manager

        .EXAMPLE
        Get-NsxtNodeProfile
        This example returns all the node profiles from the NSX Manager.

        .EXAMPLE
        Get-NsxtNodeProfile -id $id
        This example returns the node profiles from the NSX Manager using the id.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {

        if ($PsBoundParameters.ContainsKey('id')) {
            $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders
            $response
        }
        else {
            $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders
            $response.results
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Get-NsxtNodeProfile

Function Set-NsxtNodeProfileSyslogExporter {
    <#
        .SYNOPSIS
        Sets a node profile syslog exporter.

        .DESCRIPTION
        The Set-NsxtNodeProfileSyslogExporter cmdlet adds a syslog exporter to an NSX node profie for configuration
        of NSX components included in the node profile.

        .EXAMPLE
        Set-NsxtNodeProfileSyslogExporter -id "00000000-0000-0000-0000-000000000001" -server "sfo-vrli01.sfo.rainpole.io" -port 514 -protocol TCP -logLevel INFO
        This example add a single syslog exporter to the NSX node profile the id of the profile.

        Note: This function only supports a single syslog exporter.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [int]$port,
        [Parameter (Mandatory = $true)] [ValidateSet('TCP', 'UDP', 'LI')] [ValidateNotNullOrEmpty()] [String]$protocol,
        [Parameter (Mandatory = $true)] [ValidateSet('EMERG', 'ALERT', 'CRIT', 'ERR', 'WARNING', 'NOTICE', 'INFO', 'DEBUG')] [ValidateNotNullOrEmpty()] [String]$logLevel
    )

    Try {
        $revision = (Get-NsxtNodeProfile -id $id)._revision
        $body = '{
                    "syslog" : {
                        "exporters" : [ {
                        "server" : "'
 + $server + '",
                        "port" : '
 + $port + ',
                        "protocol" : "'
 + $protocol + '",
                        "max_log_level" : "'
 + $logLevel + '"
                        } ]
                    },
                    "_revision" : '
 + $revision + '
                }'

        $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id"
        $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $nsxtHeaders -Body $body
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Set-NsxtNodeProfileSyslogExporter

Function Remove-NsxtNodeProfileSyslogExporter {
    <#
        .SYNOPSIS
        Removes all node profile syslog exporters.

        .DESCRIPTION
        The Remove-NsxtNodeProfileSyslogExporter cmdlet removes all syslog exporters from an NSX node profie for configuration
        of NSX components included in the node profile.

        .EXAMPLE
        Remove-NsxtNodeProfileSyslogExporter -id "00000000-0000-0000-0000-000000000001"
        This example add a single syslog exporter to the NSX node profile the id of the profile.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $revision = (Get-NsxtNodeProfile -id $id)._revision
        $body = '{
                    "syslog" : {
                        "exporters" : []
                    },
                    "_revision" : '
 + $revision + '
                }'

        $uri = "https://$nsxtManager/api/v1/configs/central-config/node-config-profiles/$id"
        $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $nsxtHeaders -Body $body
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-NsxtNodeProfileSyslogExporter

Function Get-NsxtBackupConfiguration {
    <#
        .SYNOPSIS
        Return the backup configuration for an NSX Manager cluster.

        .DESCRIPTION
        The Get-NsxtBackupConfiguration cmdlet returns the backup configuration for an NSX Manager cluster

        .EXAMPLE
        Get-NsxtBackupConfiguration -fqdn sfo-w01-nsx01.sfo.rainpole.io
        This example returns the backup configuration for the NSX Manager cluster named 'sfo-w01-nsx01.sfo.rainpole.io'.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn
    )

    Try {
        $uri = "https://$fqdn/api/v1/cluster/backups/config"
        # Note: NSX-T v3.2.0 and later use `/policy/api/v1/cluster/backups/config` or `/api/v1/cluster/backups/config`
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtBackupConfiguration

Function Get-NsxtBackupHistory {
    <#
        .SYNOPSIS
        Return the backup history for an NSX Manager cluster.

        .DESCRIPTION
        The Get-NsxtBackupHistory cmdlet returns the backup history for an NSX Manager cluster

        .EXAMPLE
        Get-NsxtBackupHistory -fqdn sfo-w01-nsx01.sfo.rainpole.io
        This example returns the backup history for the NSX Manager cluster named 'sfo-w01-nsx01.sfo.rainpole.io'.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/cluster/backups/history"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtBackupHistory

Function Get-NsxtAlarm {
    <#
        .SYNOPSIS
        Return the triggered alarms for an NSX Manager cluster.

        .DESCRIPTION
        The Get-NsxtAlarm cmdlet returns all triggered alarms for an NSX Manager cluster.

        .EXAMPLE
        Get-NsxtAlarm -fqdn sfo-w01-nsx01.sfo.rainpole.io
        This example returns all triggered alarms for an NSX Manager cluster named sfo-w01-nsx01.sfo.rainpole.io.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/alarms"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtAlarm

Function Get-NsxtEvent {
    <#
        .SYNOPSIS
        Return the events for an NSX Manager cluster.

        .DESCRIPTION
        The Get-NsxtEvent cmdlet returns the events for an NSX Manager cluster.

        .EXAMPLE
        Get-NsxtEvent -fqdn sfo-w01-nsx01.sfo.rainpole.io
        This example returns events for an NSX Manager cluster named sfo-w01-nsx01.sfo.rainpole.io.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/events"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtEvent

Function Get-NsxtTier0BgpStatus {
    <#
        .SYNOPSIS
        Returns the status of the BGP routing for NSX Tier-0 gateways.

        .DESCRIPTION
        The Get-NsxtTier0BgpStatus cmdlet returns the status of the BGP routing for NSX Tier-0 gateways.

        .EXAMPLE
        Get-NsxtTier0BgpStatus -id <guid>
        This example returns the status of the BGP routing for NSX Tier-0 gateway.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$nsxtManager/policy/api/v1/infra/tier-0s/$id/locale-services/default/bgp/neighbors/status"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTier0BgpStatus

Function Get-NsxtEdgeNode {
    <#
        .SYNOPSIS
        Get details for NSX Edge.

        .DESCRIPTION
        The Get-NsxtEdgeNode cmdlet returns the details of an NSX Edge node

        .EXAMPLE
        Get-NsxtEdgeNode -transportNodeId 7740f2da-83b5-40de-bc4c-665ea779bbd0
        This example returns the details of an NSX Edge node
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$transportNodeId
    )

    Try {
        $uri = "https://$nsxtmanager/api/v1/transport-nodes/$transportNodeId"
        Invoke-RestMethod -Method GET -URI $uri -headers $nsxtHeaders
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtEdgeNode

Function Get-NsxtTier0LocaleServiceBgp {
    <#
        .SYNOPSIS
        Get details for BGP in the locale services.

        .DESCRIPTION
        The Get-NsxtTier0LocaleServiceBgp cmdlet returns the details for BGP in the locale services.

        .EXAMPLE
        Get-NsxtTier0LocaleServiceBgp -id <guid>
        This example returns the details for BGP in the locale services.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$nsxtmanager/policy/api/v1/infra/tier-0s/$id/locale-services/default/bgp"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTier0LocaleServiceBgp

Function Get-NsxtVidmStatus {
    <#
        .SYNOPSIS
        Get the status of the Identity Manager integration.

        .DESCRIPTION
        The Get-NsxtVidmStatus cmdlet returns the status of the Identity Manager integration.

        .EXAMPLE
        Get-NsxtVidmStatus
        This example returns the status of the Identity Manager integration.
    #>


    Try {
        $uri = "https://$nsxtManager/api/v1/node/aaa/providers/vidm/status"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtVidmStatus

Function Get-NsxtTransportNode {
    <#
        .SYNOPSIS
        Returns information about all transport nodes with host or edge details.

        .DESCRIPTION
        The Get-NsxtTransportNode cmdlet returns information about all transport nodes with host or edge details.

        .EXAMPLE
        Get-NsxtTransportNode
        This example returns information about all transport nodes with host or edge details.

        .EXAMPLE
        Get-NsxtTransportNode -type edge
        This example returns information about all edge transport nodes with details.

        .EXAMPLE
        Get-NsxtTransportNode -type host
        This example returns information about all host transport nodes with details.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateSet('host', 'edge')][ValidateNotNullOrEmpty()] [String]$type
    )

    Try {
        if ($PsBoundParameters.ContainsKey('type')) {
            if ($type -eq 'host') {
                $uri = "https://$nsxtManager/api/v1/transport-nodes?node_types=HostNode"
            } else {
                $uri = "https://$nsxtManager/api/v1/transport-nodes?node_types=EdgeNode"
            }
        } else {
            $uri = "https://$nsxtManager/api/v1/transport-nodes"
        }
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTransportNode

Function Get-NsxtTransportNodeStatus {
    <#
        .SYNOPSIS
        Get the status of the NSX transport nodes.

        .DESCRIPTION
        The Get-NsxtTransportNodeStatus cmdlet returns the status of the transport nodes.

        .EXAMPLE
        Get-NsxtTransportNodeStatus
        This example returns the status of all transport nodes.

        .EXAMPLE
        Get-NsxtTransportNodeStatus -type edge
        This example returns the status of the edge transport nodes.

        .EXAMPLE
        Get-NsxtTransportNodeStatus -type host
        This example returns the status of the host transport nodes.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateSet('host', 'edge')][ValidateNotNullOrEmpty()] [String]$type
    )

    Try {
        if ($PsBoundParameters.ContainsKey('type')) {
            $uri = "https://$nsxtManager/api/v1/transport-nodes/status?node_type=$($type.ToUpper())"
        } else {
            $uri = "https://$nsxtManager/api/v1/transport-nodes/status"
        }
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTransportNodeStatus

Function Get-NsxtTransportNodeTunnel {
    <#
        .SYNOPSIS
        Returns a list of tunnel connections to transport node.

        .DESCRIPTION
        The Get-NsxtTransportNodeTunnel cmdlet returns a list of tunnel connections to transport node.

        .EXAMPLE
        Get-NsxtTransportNodeTunnel -id <guid>
        This example returns a list of tunnel connections to transport node.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/tunnels"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTransportNodeTunnel

Function Get-NsxtTransportNodeTunnelStatus {
    <#
        .SYNOPSIS
        Returns the status of all transport nodes with tunnel connections to transport node.

        .DESCRIPTION
        The Get-NsxtTransportNodeTunnelStatus cmdlet returns the status of all transport nodes with tunnel connections to transport node.

        .EXAMPLE
        Get-NsxtTransportNodeTunnelStatus -id <guid>
        This example returns the status of all transport nodes with tunnel connections to transport node.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/transport-nodes/$id/remote-transport-node-status"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtTransportNodeTunnelStatus

Function Get-NsxtComputeManagerStatus {
    <#
        .SYNOPSIS
        Get the status of a compute manager registered to the NSX Manager cluster.

        .DESCRIPTION
        The Get-NsxtComputeManagerStatus cmdlet returns the status of a compute manager registered to the NSX Manager cluster.

        .EXAMPLE
        Get-NsxtComputeManagerStatus -id <guid>
        This example returns the status of a compute manager registered to the NSX Manager cluster.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$nsxtManager/api/v1/fabric/compute-managers/$id/status"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtComputeManagerStatus

Function Get-NsxtApplianceUser {
    <#
        .SYNOPSIS
        Returns the list of users configued to log in to the NSX appliance.

        .DESCRIPTION
        The Get-NsxtApplianceUser cmdlet returns the list of users configued to log in to the NSX appliance.

        .EXAMPLE
        Get-NsxtApplianceUser
        This example returns a all users configued to log in to the NSX appliance.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$transportNodeId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clusterNodeId
    )

    Try {
        if ($PsBoundParameters.ContainsKey("transportNodeId")) {
            $uri = "https://$nsxtmanager/api/v1/transport-nodes/$transportNodeId/node/users"
        } elseif ($PsBoundParameters.ContainsKey("clusterNodeId")) {
            $uri = "https://$nsxtmanager/api/v1/cluster/$clusterNodeId/node/users"
        } else {
            $uri = "https://$nsxtmanager/api/v1/node/users"
        }
        (Invoke-RestMethod $uri -Method 'GET' -Headers $nsxtHeaders).results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-NsxtApplianceUser

Function Set-NsxtApplianceUserExpirationPolicy {
    <#
        .SYNOPSIS
        Updates the password expiration policy for NSX appliance user.

        .DESCRIPTION
        The Set-NsxtApplianceUserExpirationPolicy cmdlet updates the password expiration policy for an NSX appliance user.

        .EXAMPLE
        Set-NsxtApplianceUserExpirationPolicy -userId 0 -days 9999
        This example updates the password expiration policy for the userId 0 (root) to 9999 days.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateRange(0,9999)] [Int]$days,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$transportNodeId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clusterNodeId
    )

    Try {
        $json = '{"password_change_frequency": ' + $days + ' }'
        if ($PsBoundParameters.ContainsKey("transportNodeId")) {
            $uri = "https://$nsxtmanager/api/v1/transport-nodes/$transportNodeId/node/users/$userId"
        } elseif ($PsBoundParameters.ContainsKey("clusterNodeId")) {
            $uri = "https://$nsxtmanager/api/v1/cluster/$clusterNodeId/node/users/$userId"
        } else {
            $uri = "https://$nsxtmanager/api/v1/node/users/$userId"
        }
        (Invoke-RestMethod $uri -Method 'PUT' -Headers $nsxtHeaders -Body $json).results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtApplianceUserExpirationPolicy

Function Set-NsxtApplianceUserPassword {
    <#
        .SYNOPSIS
        Updates the password for NSX appliance user.

        .DESCRIPTION
        The Set-NsxtApplianceUserPassword cmdlet updates the password for an NSX appliance user.

        .EXAMPLE
        Set-NsxtApplianceUserPassword -userId 0 -password VMw@re1!VMw@re1!
        This example updates the password for the userId 0 (root).
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()]  [String]$password,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$transportNodeId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$clusterNodeId
    )

    Try {
        $json = '{"password": "' + $password + '" }'
        if ($PsBoundParameters.ContainsKey("transportNodeId")) {
            $uri = "https://$nsxtmanager/api/v1/transport-nodes/$transportNodeId/node/users/$userId`?action=reset_password"
        } elseif ($PsBoundParameters.ContainsKey("clusterNodeId")) {
            $uri = "https://$nsxtmanager/api/v1/cluster/$clusterNodeId/node/users/$userId`?action=reset_password"
        } else {
            $uri = "https://$nsxtmanager/api/v1/node/users/$userId`?action=reset_password"
        }
        (Invoke-RestMethod $uri -Method 'POST' -Headers $nsxtHeaders -Body $json).results
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-NsxtApplianceUserPassword

#EndRegion End NSX-T Functions ######
#####################################################################

#####################################################################
#Region Begin vSphere with Tanzu Functions ######

Function Enable-WMRegistry {
    <#
        .SYNOPSIS
        Enable the embedded Harbor Registry on a Supervisor Cluster

        .DESCRIPTION
        The Enable-WMRegistry cmdlet enables the embedded Harbor Registry on a Supervisor Cluster

        .EXAMPLE
        Enable-WMRegistry -cluster sfo-w01-cl01 -ctoragePolicy vsphere-with-tanzu-policy
        This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01

        .EXAMPLE
        Get-WMCluster -cluster sfo-w01-cl01 | Enable-WMRegistry
        This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster with the default image storage policy for the Supervisor Cluster
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$storagePolicy,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [psObject]$inputObject
    )

    if ($inputObject) {
        $cluster = $inputObject.Name
    }

    Try {
        if ($vCenterApi -le 701) {
            $getHarborInstalled = (Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -Headers $vcApiHeaders).value
        }
        elseif ($vCenterApi -ge 702) {
            $getHarborInstalled = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -Headers $vcApiHeaders
        }
    }
    Catch {
        Write-Error = $_.Exception
    }

    if (!$getHarborInstalled) {
        Try {
            $wmClusterId = (Invoke-RestMethod -Method GET -URI  https://$vcApiServer/api/vcenter/namespace-management/clusters -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster
        }
        Catch {
            Write-Error $_.Exception.Message
        }

        if (!$StoragePolicy) {
            Try {
                $storagePolicyId = (Invoke-RestMethod -Method GET -URI  https://$vcApiServer/api/vcenter/namespace-management/clusters/$wmClusterId -Headers $vcApiHeaders).image_storage.storage_policy
            }
            Catch {
                Write-Error $_.Exception.Message
            }
        }
        elseif ($StoragePolicy) {
            Try {
                if ($vCenterApi -ge 702) {
                    $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vcApiServer/api/vcenter/storage/policies -Headers $vcApiHeaders  -UseBasicParsing | ConvertFrom-Json) | Where-Object { $_.name -eq $StoragePolicy }).policy
                    $json = @"
{
    "cluster" : "$wmClusterId",
    "storage" :
    [
        {
            "policy" : "$storagePolicyId"
        }
    ]
}
"@

                }
                elseif ($vCenterApi -le 701) {
                    $storagePolicyId = ((Invoke-WebRequest -Method GET -URI https://$vcApiServer/rest/vcenter/storage/policies -Headers $vcApiHeaders -UseBasicParsing | ConvertFrom-Json).value | Where-Object { $_.name -eq $StoragePolicy }).policy
                    $json = @"
{
    "spec" :
    {
        "cluster" : "$wmClusterId",
        "storage" :
        [
            {
                "policy" : "$storagePolicyId"
            }
        ]
    }
}
"@

                }
            }
            Catch {
                Write-Error $_.Exception.Message
            }
        }
    }
    # Send a REST API call to vCenter Server to instantiate the new Harbor registry
        if ($vCenterApi -le 701) {
            Try {
                $installHarbor = Invoke-RestMethod -Method POST -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -Headers $vcApiHeaders -Body $json -ContentType application/json
            }
            Catch {
                Write-Error $_.Exception.Message
            }

            if ($installHarbor) {
                $installHarborValue = $installHarbor.value
                Write-Output "Embedded registry $installHarborValue deployment successfully started on Supervisor Cluster $cluster"
            }
        }
        elseif ($vCenterApi -ge 702) {
            Try {
                $installHarbor = Invoke-RestMethod -Method POST -URI https://$vcApiServer/api/vcenter/content/registries/harbor -Headers $vcApiHeaders -Body $json -ContentType application/json
            }
            Catch {
                Write-Error $_.Exception.Message
            }

            if ($installHarbor) {
                Write-Output "Embedded registry $installHarbor deployment successfully started on Supervisor Cluster $cluster"
            }
        }
}
Export-ModuleMember -Function Enable-WMRegistry

Function Get-WMRegistry {
    <#
        .SYNOPSIS
        Retrieves the embedded Harbor Registry on a Supervisor Cluster

        .DESCRIPTION
        The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry on a Supervisor Cluster

        .EXAMPLE
        Get-WMRegistry
        This example retrieves all embedded Harbor Registries in vCenter Server inventory

        .EXAMPLE
        Get-WMRegistry -Cluster sfo-w01-cl01
        This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01"

        .EXAMPLE
        Get-WMCluster -Cluster sfo-w01-cl01 | Get-WMRegistry
        This example enables the embedded Harbor Registry on Supervisor Cluster "sfo-w01-cl01" via pipeline from Get-WMCluster
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject
    )

    if ($inputObject) {
        $cluster = $inputObject.Name
    }

    if ($Cluster) {
        Try {
            $wmClusterId = (Invoke-RestMethod -Method GET -URI  https://$vcApiServer/api/vcenter/namespace-management/clusters -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $Cluster }).cluster
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }

    Try {
        if (!$PsBoundParameters.ContainsKey("Cluster")) {
            if ($vCenterApi -le 701) {
                $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders
                $response.value
            }
            elseif ($vCenterApi -ge 702) {
                $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders
                $response
            }
        }
        elseif ($PsBoundParameters.ContainsKey("Cluster")) {
            if ($vCenterApi -le 701) {
                $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/rest/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders
                $response.value | Where-Object { $_.cluster -eq $wmClusterId }
            }
            elseif ($vCenterApi -ge 702) {
                $response = Invoke-RestMethod -Method GET -URI https://$vcApiServer/api/vcenter/content/registries/harbor -ContentType application/json -headers $vcApiHeaders
                $response | Where-Object { $_.cluster -eq $wmClusterId }
            }
        }
    }
    Catch {
        Write-Error = $_.Exception
    }
}
Export-ModuleMember -Function Get-WMRegistry

Function Remove-WMRegistry {
    <#
        .SYNOPSIS
        Disable the embedded Harbor Registry on a Supervisor Cluster

        .DESCRIPTION
        The Remove-WMRegistry cmdlet disables the embedded Harbor Registry on a Supervisor Cluster

        .EXAMPLE
        Get-WMRegistry -cluster sfo-w01-cl01 | Remove-WMRegistry
        This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster

        .EXAMPLE
        Remove-WMRegistry -cluster sfo-w01-cl01
        This example disables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject
    )

    Try {
        if ($inputObject) {
            $harborRegistryId = $inputObject.registry
        }
        else {
            $harborRegistryId = (Get-WMRegistry -cluster $cluster).registry
        }

        if ($vCenterApi -le 701) {
            $uri = "https://$vcApiServer/rest/vcenter/content/registries/harbor/$harborRegistryId"
        }
        elseif ($vCenterApi -ge 702) {
            $uri = "https://$vcApiServer/api/vcenter/content/registries/harbor/$harborRegistryId"
        }
        $response = Invoke-WebRequest -Method DELETE -URI $uri -ContentType application/json -headers $vcApiHeaders -UseBasicParsing
        if ($response.StatusCode -eq 200 -or $response.StatusCode -eq 204) {
            Write-Output "Disable embedded Harbor Registry successfully started for Supervisor Cluster $cluster"
        }
    }
    Catch {
        Write-Error = $_.Exception
    }
}
Export-ModuleMember -Function Remove-WMRegistry

Function Get-WMRegistryHealth {
    <#
        .SYNOPSIS
        Retrieves the embedded Harbor Registry Health

        .DESCRIPTION
        The Get-WMRegistry cmdlet retrieves the embedded Harbor Registry Health

        .EXAMPLE
        Get-WMRegistryHealth -registry <regestry_id>
        This example gets the health status of the embedded Harbor Registry

        .EXAMPLE
        Get-WMRegistry -cluster sfo-w01-cl01 | Get-WMRegistryHealth
        This example enables the embedded Harbor Registry on Supervisor Cluster sfo-w01-cl01 via pipeline from Get-WMCluster
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$registry,
        [Parameter (ValueFromPipeline, Mandatory = $false)] [ValidateNotNullOrEmpty()] [psObject]$inputObject
    )

    Try {
        if ($inputObject) {
            $registry = $inputObject.registry
        }
        $uri = "https://$vcApiServer/rest/vcenter/content/registries/$registry/health"
        $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders -ContentType application/json
        $response.value.status
    }
    Catch {
        Write-Error = $_.Exception
    }
}
Export-ModuleMember -Function Get-WMRegistryHealth

Function Connect-WMCluster {
    <#
        .SYNOPSIS
        Connect to the Supervisor Cluster

        .DESCRIPTION
        The Connect-WMCluster cmdlet connect to the Supervisor Cluster

        .EXAMPLE
        Connect-WMCluster -cluster sfo-w01-cl01 -user administrator@vsphere.local -pass VMw@re1!
        This example connects with the vSphere SSO user administrator@vsphere.local to the Supervisor Cluster sfo-w01-cl01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        $server = (Get-WMCluster -Cluster $cluster).KubernetesHostname
        $env:KUBECTL_VSPHERE_PASSWORD = $pass
        Invoke-Expression "kubectl vsphere login --server $server --vsphere-username $user --insecure-skip-tls-verify" | Out-Null
        if (Invoke-Expression "kubectl get nodes") {
            Write-Output "Successfully connected to Supervisor Cluster: $server"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Connect-WMCluster

Function Disconnect-WMCluster {
    <#
        .SYNOPSIS
        Disconnect from o the Supervisor Cluster

        .DESCRIPTION
        The Disconnect-WMCluster cmdlet disconnects from the Supervisor Cluster

        .EXAMPLE
        Disconnect-WMCluster
        This example disconnects from the Supervisor Cluster
    #>


    Try {
        Invoke-Expression "kubectl vsphere logout" | Out-Null
        $env:KUBECTL_VSPHERE_PASSWORD = $null
        Write-Output "Successfully disconnected from Supervisor Cluster"
    }
    Catch {
        Write-Error = $_.Exception
    }
}
Export-ModuleMember -Function Disconnect-WMCluster

Function New-TanzuKubernetesCluster {
    <#
        .SYNOPSIS
        Adds a Tanzu Kubernetes Cluster based on the specified YAML file.

        .DESCRIPTION
        The New-TanzuKubernetesCluster cmdlet adds a Tanzu Kubernetes Cluster based on the specified YAML file.

        .EXAMPLE
        New-TanzuKubernetesCluster -YAML .\SampleYaml\sfo-w01-tkc01-cluster.yaml
        This example creates a Tanzu Kubernetes Cluster based on the yaml file
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$YAML
    )

    Try {
        Invoke-Expression "kubectl apply -f $YAML"
    }
    Catch {
        Write-Error = $_.Exception
    }
}
Export-ModuleMember -Function New-TanzuKubernetesCluster

Function Get-TanzuKubernetesCluster {
    <#
        .SYNOPSIS
        Retrieves a Tanzu Kubernetes Cluster

        .DESCRIPTION
        The Get-TanzuKuberntesCluster cmdlet retrieves a Tanzu Kubernetes Cluster

        .EXAMPLE
        Get-TanzuKubernetesCluster
        This example retrieves all Tanzu Kubernetes Clusters from all Namespaces

        .EXAMPLE
        Get-TanzuKubernetesCluster -namespace sfo-w01-tkc01 -tkc sfo-w01-tkc01
        This example retrieves a Tanzu Kubernetes Cluster named "sfo-w01-tkc01" from the Namespace specified "sfo-w01-tkc01"
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tkc,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$detail
    )

    Try {
        if ($PsBoundParameters.ContainsKey("detail")) {
            if (!$tkc -and !$namespace) {
                Invoke-Expression "kubectl describe tkc --all-namespaces"
            }
            elseif (!$tkc -and $namespace) {
                Invoke-Expression "kubectl describe tkc -n $namespace"
            }
            elseif ($tkc -and !$namespace) {
                Write-Error "A resource cannot be retrieved by tkc name across all namespaces"
            }
            elseif ($tkc -and $namespace) {
                Invoke-Expression "kubectl describe tkc $tkc -n $namespace"
            }
        }
        else {
            if (!$tkc -and !$namespace) {
                Invoke-Expression "kubectl get tkc --all-namespaces"
            }
            elseif (!$tkc -and $namespace) {
                Invoke-Expression "kubectl get tkc -n $namespace"
            }
            elseif ($tkc -and !$namespace) {
                Write-Error "A resource cannot be retrieved by name across all namespaces"
            }
            elseif ($tkc -and $namespace) {
                Invoke-Expression "kubectl get tkc $tkc -n $namespace"
            }
        }
    }
    Catch {
        Write-Error = $_.Exception
    }
}
Export-ModuleMember -Function Get-TanzuKubernetesCluster

Function Remove-TanzuKubernetesCluster {
    <#
        .SYNOPSIS
        Remove a Tanzu Kubernetes cluster

        .DESCRIPTION
        The Remove-TanzuKubernetesCluster cmdlet removes a Tanzu Kubernetes cluster

        .EXAMPLE
        Remove-TanzuKubernetesCluster -cluster sfo-w01-tkc01 -namespace sfo-w01-tkc01
        This example removes the Tanzu Kubernetes cluster
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$namespace
    )

    Try {
        Invoke-Expression "kubectl delete tkc $cluster -n $namespace"
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-TanzuKubernetesCluster

Function Get-VMClass {
    <#
        .SYNOPSIS
        Retrieves information on a Virtual Machine class

        .DESCRIPTION
        The Get-VMClass cmdlet retrieves information on a Virtual Machine class

        .EXAMPLE
        Get-VMClass
        This example retrieves all Virtual Machine classes

        .EXAMPLE
        Get-VMClass -vmClass guaranteed-small
        This example retrieves information on the Virtual Machine Class guaranteed-small

        .EXAMPLE
        Get-VMClass -namespace sfo-w01-tkc01
        This example retrieves Virtual Machine Classes assigned to the namespace sfo-w01-tkc01
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace
    )

    Try {
        if ($PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$vcApiServer/api/vcenter/namespace-management/virtual-machine-classes/$vmClass"
            $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("namespace")) {
            $uri = "https://$vcApiServer/api/vcenter/namespaces/instances/$namespace"
            $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders
            $response.vm_service_spec.vm_classes
        }
        else {
            $uri = " https://$vcApiServer/api/vcenter/namespace-management/virtual-machine-classes"
            $response = Invoke-RestMethod -Method 'GET' -URI $uri -Headers $vcApiHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-VMClass

Function Add-VMClass {
    <#
        .SYNOPSIS
        Retrieves information on a Virtual Machine class

        .DESCRIPTION
        The Add-VMClass cmdlet retrieves information on a Virtual Machine class

        .EXAMPLE
        Add-VMClass -namespace sfo-w01-tkc01 -vmClass guaranteed-small
        This example retrieves all Virtual Machine classes
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$namespace,
        [Parameter (Mandatory = $false)] [ValidateSet("guaranteed-medium","guaranteed-large","guaranteed-xlarge","best-effort-4xlarge","guaranteed-small","best-effort-medium","best-effort-2xlarge","guaranteed-2xlarge","best-effort-large","guaranteed-4xlarge","best-effort-8xlarge","best-effort-xsmall","guaranteed-xsmall","best-effort-xlarge","guaranteed-8xlarge","best-effort-small")] [String]$vmClass
    )

    Try {
        $existingVmClass = Get-VMClass -namespace $namespace -ErrorAction Ignore
        if ($existingVmClass) {
            $newVmClass = New-Object System.Collections.Generic.List[System.Object]
            foreach ($assignedVMclass in $existingVmClass) {
                if (!($assignedVMclass -eq $vmClass)) {
                    $newVmClass += $assignedVMclass
                }
            }
            $newVmClass += $vmClass
            $jsonFormat = ConvertTo-Json $newVmClass

            $body = '{"vm_service_spec": { "vm_classes": '+ $jsonFormat +'}}'
        }
        else {
            $body = '{ "vm_service_spec": { "vm_classes": [ "' + $vmClass + '" ] }}'
        }

        $uri = "https://$vcApiServer/api/vcenter/namespaces/instances/$namespace"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vcApiHeaders -body $body 
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-VMClass

Function Get-WMLicenseStatus {
    <#
        .SYNOPSIS
        Get Workload Management license status

        .DESCRIPTION
        The Get-WMLicenseStatus cmdlet gets the license status from vCenter Server for Workload Management

        .EXAMPLE
        Get-WMLicenseStatus
        This example gets the vSphere with Tanzu licenses status from vCenter Server for Workload Management
    #>


    # Param (
    # [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
    # [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain
    # )

    Try {
        $uri = "https://$vcApiServer/api/vcenter/namespace-management/capability"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vcApiHeaders
        $response

    }
    Catch {
        Debug-ExceptionWriter -object $_ 
    }
}
Export-ModuleMember -Function Get-WMLicenseStatus

Function Request-WMClusterCSR {
    <#
        .SYNOPSIS
        Request Certificate Signing Request filr

        .DESCRIPTION
        The Request-WMClusterCSR cmdlet requests a Certificate Signing Request file for the Supervisor Cluster
        .EXAMPLE
        Request-WMClusterCSR -cluster sfo-w01-cl01 -commonName sfo-w01-cl01.sfo.rainpole.io -organization Rainpole -organizationalUnit Rainpole -country US -stateOrProvince California -locality "Palo Alto" -adminEmailAddress admin@rainpole.io -keySize 2048 -filePath ".\SupervisorCluster.csr"
        This example requetes a Certificate Signing Request file for the Supervisor Cluster sfo-w01-cl01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$commonName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organization,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$organizationalUnit,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$country,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$stateOrProvince,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$locality,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmailAddress,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$keySize,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath
    )

    Try {
        $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters"
        $clusterId = (Invoke-RestMethod -Method GET -URI $uri -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $cluster }).cluster
        
        $output = New-Object -TypeName PSCustomObject
        $output | Add-Member -notepropertyname 'common_name' -notepropertyvalue $commonName
        $output | Add-Member -notepropertyname 'organization_name' -notepropertyvalue $organization
        $output | Add-Member -notepropertyname 'organization_unit_name' -notepropertyvalue $organizationalUnit
        $output | Add-Member -notepropertyname 'country' -notepropertyvalue $country
        $output | Add-Member -notepropertyname 'state_or_province' -notepropertyvalue $stateOrProvince
        $output | Add-Member -notepropertyname 'locality' -notepropertyvalue $locality
        $output | Add-Member -notepropertyname 'email_address' -notepropertyvalue $adminEmailAddress
        if ($PsBoundParameters.ContainsKey("keySize")){
            $output | Add-Member -notepropertyname 'keySize' -notepropertyvalue $keySize
        }
        $body = $output | ConvertTo-Json
        $uri = "https://$vcApiServer/api/$clusterId/csr/tls-endpoint/"
        $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $vcApiHeaders -body $body
        $response | Out-File -FilePath $filePath
        Write-Output "Certificate Signing Request (.csr) file for ($commonName) has been successfully saved to file ($filePath)"
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-WMClusterCSR

Function Install-WMClusterCertificate {
    <#
        .SYNOPSIS
        Installs a signed TLS certificate for the defined Supervisor Cluster

        .DESCRIPTION
        The Install-WMClusterCertificate cmdlet installs a signed TLS certificate for the defined Supervisor Cluster

        .EXAMPLE
        Install-WMClusterCertificate -cluster sfo-w01-cl01 -filePath ".\SupervisorCluster.cer"
        This example installs the signed TLS certificate to Supervisor Cluster sfo-w01-cl01 in Workload domain sfo-w01
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filePath
    )

    Try {
        if ($PsBoundParameters.ContainsKey("filepath")) {
            if (!(Test-Path $filepath)) {
                Throw "Certificate File Not Found"
            }
            else {
                $certificate = Get-Content -Path $filePath -Raw -ErrorAction SilentlyContinue
                $inputFileName = Split-Path -Path $filePath -Leaf -ErrorAction SilentlyContinue
            }
        }
        if ($isMacOS -eq $true -or $isLinux -eq $true) {
            $certificateFormatted = $Certificate -Replace "`n","\n"
        }
        elseif ($isWindows -eq $true -or $PSEdition -eq "Desktop") {
            $certificateFormatted = $Certificate -Replace "`r`n","\n"
        }
        else {
            Write-Error "Unsupported Operating System"
            Break
        }
        if (($certificateFormatted | Measure-object -Line).Count -ne 1) {
            Write-Error "Error parsing TLS certificate"
            Break
        }
        $body = '{ "tls_endpoint_certificate": "'+ $certificateFormatted +'" }' 
        $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters"
        $clusterId = (Invoke-RestMethod -Method GET -URI $uri -Headers $vcApiHeaders | Where-Object { $_.cluster_name -eq $cluster }).cluster
        $uri = "https://$vcApiServer/api/vcenter/namespace-management/clusters/$clusterId/"
        if ($PSEdition -eq 'Core') {
            $response = Invoke-WebRequest -Method PATCH -Uri $uri -Headers $vcApiHeaders -body $body -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented
        }
        else {
            $response = Invoke-WebRequest -Method PATCH -Uri $uri -Headers $vcApiHeaders -body $body -UseBasicParsing
        }
        if ($response.StatusCode -lt 300) {
            if ($inputFileName) {
                Write-Output "Signed Certificate ($inputFileName) has been successfully applied to Supervisor Cluster ($cluster)"
            }
            else {
                Write-Output "Signed Certificate has been successfully applied to Supervisor Cluster ($cluster)"
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-WMClusterCertificate

Function Watch-WmClusterConfigStatus {
    <#
        .SYNOPSIS
        Poll request

        .DESCRIPTION
        The Watch-WmClusterConfigStatus cmdlet polls the status of wmCluster

        .EXAMPLE
        Watch-WmClusterConfigStatus -wmClusterName <wmCluster name>
        This example polls the status of wmCluster
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$wmClusterName,
        [Parameter (Mandatory = $false)]  [int]$retriesCount = 10,
        [Parameter (Mandatory = $false)]  [int]$sleepTime = 30
    )


    Try {
        $try = 1
        Do {
            $wmCluster = (Get-WMCluster -Cluster $wmClusterName -ErrorAction SilentlyContinue)
            Start-Sleep $sleepTime
            $try++
        } 
        Until (($wmCluster.ConfigStatus -ne "Configuring") -or ($try -gt $retriesCount))
        if ($try -gt $retriesCount) {
            Write-Error "Retries exeeded max count $retriesCount : CONFIGURATION_FAILED"
        }
        if ($wmCluster.ConfigStatus -ne "Running") {
            Write-Error "Workload management on cluster: $wmClusterName status: $($wmCluster.ConfigStatus)"
            write-Error "Workload management on cluster: $wmClusterName status messages: $($wmCluster.StatusMessages.Messages)"
        }
        else {
            Write-Output "Workload Management on cluster: $wmClusterName completed with status: $($wmCluster.ConfigStatus)"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Watch-WmClusterConfigStatus

#EndRegion End vSphere with Tanzu Functions ######
#####################################################################

#####################################################################
#Region Start vRealize Suite Lifecycle Manager Functions ######

Function Request-vRSLCMToken {
    <#
        .SYNOPSIS
        Connects to the specified vRealize Suite Lifecycle Manager and obtains authorization token

        .DESCRIPTION
        The Request-vRSLCMToken cmdlet connects to the specified vRealize Suite Lifecycle Manager and
        obtains an authorization token. It is required once per session before running all other cmdlets.

        .EXAMPLE
        Request-vRSLCMToken -fqdn xreg-vrslcm.rainpole.io -username admin@local -password VMware1!
        This example shows how to connect to the vRealize Suite Lifecycle Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password
    )

    if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) {
        $creds = Get-Credential # Request Credentials
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }

    $Global:vrslcmHeaders = createBasicAuthHeader $username $password
    $Global:vrslcmAppliance = $fqdn

    Try {
        # Validate credentials by executing an API call
        $uri = "https://$vrslcmAppliance/lcmversion"
        if ($PSEdition -eq 'Core') {
            $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        }
        else {
            $vrslcmResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $vrslcmHeaders -UseBasicParsing
        }
        if ($vrslcmResponse.StatusCode -eq 200) {
            Write-Output "Successfully connected to the vRealize Suite Lifecycle Manager Appliance: $vrslcmAppliance"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-vRSLCMToken

Function Get-vRSLCMHealth {
    <#
        .SYNOPSIS
        Check vRealize Suite Lifecycle Manager Health Status

        .DESCRIPTION
        The Get-vRSLCMHealth cmdlet checks vRealize Suite Lifecycle Manager Health Status

        .EXAMPLE
        Get-vRSLCMHealth
        This example checks vRealize Suite Lifecycle Manager Health Status
    #>


    Try {
        $uri = "https://$vrslcmAppliance/lcm/health/api/v2/status"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMHealth

Function Get-vRSLCMLockerPassword {
    <#
        .SYNOPSIS
        Get paginated list of Passwords available in the Store

        .DESCRIPTION
        The Get-vRSLCMLockerPassword cmdlet gets a paginated list of passwords available in the Locker

        .EXAMPLE
        Get-vRSLCMLockerPassword
        This example gets all passwords in the Locker

        .EXAMPLE
        Get-vRSLCMLockerPassword -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009
        This example gets the details of a password based on the vmid

        .EXAMPLE
        Get-vRSLCMLockerPassword -alias xint-env-admin
        This example gets the details of a password based on the alias
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias
    )

    Try {
        if ($PsBoundParameters.ContainsKey("vmid")) {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("alias")){
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords?aliasQuery=$alias"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response.passwords
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords?size=19"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response.passwords
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMLockerPassword

Function Add-vRSLCMLockerPassword {
    <#
        .SYNOPSIS
        Creates a new Password in a Locker

        .DESCRIPTION
        The Add-vRSLCMLockerPassword cmdlet add as new passwords to the Locker

        .EXAMPLE
        Add-vRSLCMLockerPassword -userName admin -alias xint-admin -password VMw@re1! -description "Password for Cross-Instance Admin"
        This example adda a password to the locker
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords"

        if ($PsBoundParameters.ContainsKey("description")) {
            $body = '{
                "alias": "'
+ $alias +'",
                "password": "'
+ $password +'",
                "passwordDescription": "'
+ $description +'",
                "userName": "'
+ $userName +'"
            }'

        }
        else {
            $body = '{
                "alias": "'
+ $alias +'",
                "password": "'
+ $password +'",
                "userName": "'
+ $userName +'"
            }'
           
        }

        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMLockerPassword

Function Remove-vRSLCMLockerPassword {
    <#
        .SYNOPSIS
        Delete a Password based on vmid

        .DESCRIPTION
        The Remove-vRSLCMLockerPassword cmdlet deletes a password from the Locker

        .EXAMPLE
        Remove-vRSLCMLockerPassword -vmid
        This example delets the password with the vmid
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/passwords/$vmid"
        $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRSLCMLockerPassword

Function Get-vRSLCMLockerCertificate {
    <#
        .SYNOPSIS
        Get paginated list of Certificates available in the Store

        .DESCRIPTION
        The Get-vRSLCMLockerCertificate cmdlet gets a paginated list of certificates available in the Locker

        .EXAMPLE
        Get-vRSLCMLockerCertificate
        This example gets all certificates in the Locker

        .EXAMPLE
        Get-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009
        This example gets the details of a certificate based on the vmid

        .EXAMPLE
        Get-vRSLCMLockerCertificate -alias xint-vrops01
        This example gets the details of a certificate based on the vmid
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias
    )

    Try {
        if ($PsBoundParameters.ContainsKey("vmid")) {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates/$vmid"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("alias")) {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response.certificates | Where-Object {$_.alias -eq $alias}
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response.certificates
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMLockerCertificate

Function Add-vRSLCMLockerCertificate {
    <#
        .SYNOPSIS
        Add a certificate to the vRSLCM locker

        .DESCRIPTION
        The Add-vRSLCMLockerCertificate cmdlet adds a certificate to the vRSLCM locker

        .EXAMPLE
        Add-vRSLCMLockerCertificate
        This example gets all certificates in the Locker

        .EXAMPLE
        Add-vRSLCMLockerCertificate -vmid 83abd0fd-c92d-4d8f-a5e8-9a1fc4fa6009
        This example gets the details of a certificate based on the vmid
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrslcmFQDN,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certificateAlias,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certificatePassphrase,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certChainPath
    )

    Try {
        $newPEMString
        foreach ($line in Get-Content $certChainPath) {
            $stringToAdd = $line + '\n'
            $newPEMString += $stringToAdd
        }
    $chain = [regex]::split($newPEMString, "-----BEGIN RSA PRIVATE KEY-----")[0] -replace ".{2}$"
    $key = [regex]::split($newPEMString, "-----END CERTIFICATE-----")[-1].substring(2)
    if (!$PsBoundParameters.ContainsKey("certificatePassphrase")) {
        $body = '{
            "alias": "'
+$certificateAlias+'",
            "certificateChain": "'
+$chain+'",
            "privateKey": "'
+$key+'"
        }'

    }
    else {
        $body = '{
            "alias": "'
+$certificateAlias+'",
            "certificateChain": "'
+$chain+'",
            "certificatePassphrase": "'
+$certificatePassphrase+'",
            "privateKey": "'
+$key+'"
        }'

        }

        $uri = "https://$vrslcmFQDN/lcm/locker/api/v2/certificates/import"
        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -ContentType application/json -body $body
        $response.certInfo
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMLockerCertificate

Function Remove-vRSLCMLockerCertificate {
    <#
        .SYNOPSIS
        Delete a certificate based on vmid

        .DESCRIPTION
        The Remove-vRSLCMLockerCertificate cmdlet deletes a certificate from the Locker

        .EXAMPLE
        Remove-vRSLCMLockerCertificate -vmid
        This example delets the certificate with the vmid
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/certificates/$vmid"
        $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRSLCMLockerCertificate

Function Get-vRSLCMLockerLicense {
    <#
        .SYNOPSIS
        Get paginated list of License available in the Store

        .DESCRIPTION
        The Get-vRSLCMLockerLicense cmdlet gets a paginated list of license available in the Locker

        .EXAMPLE
        Get-vRSLCMLockerLicense
        This example gets all license in the Locker

        .EXAMPLE
        Get-vRSLCMLockerLicense -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297
        This example gets the details of a license based on the vmid

        .EXAMPLE
        Get-vRSLCMLockerLicense -alias "vRealize Operations Manager"
        This example gets the details of a license based on the alias name
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$alias
    )

    Try {
        if ($PsBoundParameters.ContainsKey("vmid")) {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses/detail/$vmid"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("alias")) {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses/alias/$alias"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/licenses"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMLockerLicense

Function Add-vRSLCMLockerLicense {
    <#
        .SYNOPSIS
        Creates a new License in a Locker

        .DESCRIPTION
        The Add-vRSLCMLockerLicense cmdlet adds as new license to the Locker

        .EXAMPLE
        Add-vRSLCMLockerLicense -alias "vRealise Operations Manager" -license "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
        This example adds a license to the Locker
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alias,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$license
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/locker/api/v2/license/validate-and-add"
        $body = '{
            "alias": "'
+ $alias +'",
            "serialKey": "'
+ $license +'"
        }'
           

        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMLockerLicense

Function Remove-vRSLCMLockerLicense {
    <#
        .SYNOPSIS
        Delete a License based on vmid

        .DESCRIPTION
        The Remove-vRSLCMLockerLicense cmdlet deletes a license from the Locker

        .EXAMPLE
        Remove-vRSLCMLockerLicense -vmid
        This example delets the license with the vmid
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmid
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/locker/api/licenses/$vmid"
        $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRSLCMLockerLicense

Function Get-vRSLCMDatacenter {
    <#
        .SYNOPSIS
        Get paginated list of datacenters in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Get-vRSLCMDatacenter cmdlet gets a paginated list of datacenters in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Get-vRSLCMDatacenter
        This example gets all datacenters in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Get-vRSLCMDatacenter -vmid 2b54b028-9eba-4d2f-b6ee-66428ea2b297
        This example gets the details of a datacenter based on the vmid

        .EXAMPLE
        Get-vRSLCMDatacenter -name sfo-m01-dc01
        This example gets the details of a datacenter based on the name
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$datacenterName
    )

    Try {
        if ($PsBoundParameters.ContainsKey("vmid")) {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$vmid"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("datacenterName")) {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterName"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMDatacenter

Function Add-vRSLCMDatacenter {
    <#
        .SYNOPSIS
        Add a datacenter in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Add-vRSLCMDatacenter cmdlet adds a datacenter in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Add-vRSLCMDatacenter -datacenterName xint-m01-dc01 -location "San Francisco;California;US;37.77493;-122.41942"
        This example adds a datacenter in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$location
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters"
        $body = '{
            "dataCenterName": "'
+ $datacenterName +'",
            "primaryLocation": "'
+ $location +'"
        }'
  
        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body
        $response
}
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMDatacenter

Function Remove-vRSLCMDatacenter {
    <#
        .SYNOPSIS
        Remove a datacenter from vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Remove-vRSLCMDatacenter cmdlet removes a datacenter from vRealize Suite Lifecycle Manager

        .EXAMPLE
        Remove-vRSLCMDatacenter -datacenterVmid <datacenter_vmid>
        This example removes a datacenter from vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid"
        $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders
        $response
}
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRSLCMDatacenter

Function Get-vRSLCMDatacenterVcenter {
    <#
        .SYNOPSIS
        Get paginated list of vCenter Servers in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Get-vRSLCMDatacenterVcenter cmdlet gets a paginated list of vCenter Servers in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Get-vRSLCMDatacenterVcenter -datacenterVmid <datacenter_vmid>
        This example gets all vCenter Servers for a Datacenter

        .EXAMPLE
        Get-vRSLCMDatacenterVcenter -datacenterVmid <datacenter_vmid> -vcenterName sfo-m01-vc01
        This example gets a named vCenter Server for a datacenter

        .EXAMPLE
        Get-vRSLCMDatacenterVcenter -datacenterVmid <datacenter_vmid> -vcenterName sfo-m01-vc01 -environments
        This example gets all vCenter Servers for a Datacenter that is assigned to an Environemnt
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vcenterName,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$environments
    )

    Try {
        if ($PsBoundParameters.ContainsKey("datacenterVmid") -and $PsBoundParameters.ContainsKey("vcenterName")) {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters/$vcenterName"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("datacenterVmid") -and $PsBoundParameters.ContainsKey("vcenterName") -and $PsBoundParameters.ContainsKey("environments")) {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters/$vcenterName/environments"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMDatacenterVcenter

Function Add-vRSLCMDatacenterVcenter {
    <#
        .SYNOPSIS
        Add a vCenter Server to a Datacenter in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Add-vRSLCMDatacenterVcenter cmdlet adds a vCenter Servers to a Datacenter in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Add-vRSLCMDatacenterVcenter -datacenterVmid <datacenter_vmid> -vcenterFqdn <vcenter_fqdn> -userLockerAlias <user_alias>
        This example adds a vCenter Server to a Datacenter
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$datacenterVmid,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userLockerAlias
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/datacenters/$datacenterVmid/vcenters"
        $body = '{
            "vCenterHost": "'
 + $vcenterFqdn + '",
            "vCenterName": "'
 + ($vcenterFqdn.Split("."))[0] + '",
            "vcPassword": "locker:password:'
 + (Get-vRSLCMLockerPassword -alias $userLockerAlias).vmid + ':' + $userLockerAlias + '",
            "vcUsedAs": "MANAGEMENT",
            "vcUsername": "'
 + (Get-vRSLCMLockerPassword -alias $userLockerAlias).userName +'"
        }'

        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMDatacenterVcenter

Function Get-vRSLCMEnvironment {
    <#
        .SYNOPSIS
        Get paginated list of environments in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Get-vRSLCMEnvironment cmdlet gets a paginated list of environments in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Get-vRSLCMEnvironment
        This example gets all environments in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid
    )

    Try {
        if ($PsBoundParameters.ContainsKey("vmid")) {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$vmid"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMEnvironment

Function Add-vRSLCMEnvironment {
    <#
        .SYNOPSIS
        Create an environment in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Add-vRSLCMEnvironment cmdlet to create an environment in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Add-vRSLCMEnvironment -json (Get-Content -Raw .\vrli.json)
        This example creates an environment in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Add-vRSLCMEnvironment -json (Get-Content -Raw .\vrli.json) -vmid c907c25b-1c61-465b-b7cb-4100ac1ce331 -addProduct
        This example adds a new product to an existing environment in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json,
        [Parameter (Mandatory = $false, ParameterSetName = 'growth')] [ValidateNotNullOrEmpty()] [String]$environmentId,
        [Parameter (Mandatory = $false, ParameterSetName = 'growth')] [ValidateNotNullOrEmpty()] [Switch]$addProduct
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json") -and ($PsBoundParameters.ContainsKey("addProduct")) -and ($PsBoundParameters.ContainsKey("environmentId"))) {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId/products"
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $json
            $response
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments"
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $json
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMEnvironment

Function Remove-vRSLCMEnvironment {
    <#
        .SYNOPSIS
        Remove an environment from vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Remove-vRSLCMEnvironment cmdlet removes an environment from vRealize Suite Lifecycle Manager

        .EXAMPLE
        Remove-vRSLCMEnvironment -environmentId <environmentId>
        This example removes an environment from vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentId
    )

    Try {
        $body = '{ "deleteFromInventory": true, "deleteFromVcenter": true, "deleteLbFromSddc": true, "deleteWindowsVMs": true }'
        $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId"
        $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRSLCMEnvironment

Function Get-vRSLCMRequest {
    <#
        .SYNOPSIS
        Get all Requests

        .DESCRIPTION
        The Get-vRSLCMRequest cmdlet gets all requests in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Get-vRSLCMRequest
        This example gets all requests vRealize Suite Lifecycle Manager
        
        .EXAMPLE
        Get-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398
        This example gets the request by id from vRealize Suite Lifecycle Manager
        
        .EXAMPLE
        Get-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398 -errorCauses
        This example gets the errors for a request by id from vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$errorCauses
    )

    Try {
        if ($PsBoundParameters.ContainsKey("requestId")) {
            $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("errorCauses")) {
            $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId/error-causes"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response | Select-Object -Property vmid, state, requestReason, requestType
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMRequest

Function Remove-vRSLCMRequest {
    <#
        .SYNOPSIS
        Delete a Request

        .DESCRIPTION
        The Remove-vRSLCMRequest cmdlet removes a request from vRealize Suite Lifecycle Manager

        .EXAMPLE
        Remove-vRSLCMRequest -requestId <id>
        This example removes a request from vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$requestId    )

    Try {

            $uri = "https://$vrslcmAppliance/lcm/request/requests/$requestId"
            $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders
            $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRSLCMRequest

Function Watch-vRSLCMRequest {
    <#
        .SYNOPSIS
        Poll request

        .DESCRIPTION
        The Watch-vRSLCMRequest cmdlet polls a request in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Watch-vRSLCMRequest -vmid <vmid>
        This example polls the request in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$vmid
    )

    Try {
        Do {
            $requestStatus = (Get-vRSLCMRequest | Where-Object {$_.vmid -eq $vmid}).state
        } 
        Until ($requestStatus -ne "INPROGRESS")
        Write-Output "vRealize Suite Lifecycle Manager request: $vmid completed with the following state: $requestStatus"
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Watch-vRSLCMRequest

Function Resume-vRSLCMRequest {
    <#
        .SYNOPSIS
        Retry a request

        .DESCRIPTION
        The Resume-vRSLCMRequest cmdlet reties a request

        .EXAMPLE
        Resume-vRSLCMRequest -requestId 0ee1a4a0-203a-4c87-a40e-65d9a450e398
        This example reties the request based on the request ID provided
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$requestId
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/request/api/v2/requests/$requestId/retry"
        $response = Invoke-RestMethod $uri -Method 'PATCH' -Headers $vrslcmHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Resume-vRSLCMRequest

Function Export-WsaJsonSpec {
    <#
        .SYNOPSIS
        Create Clustered Workspace ONE Access JSON specification

        .DESCRIPTION
        The Export-WsaJsonSpec cmdlet creates the JSON specification file using the Planning and Preparation workbook
        to deploy Clustered Workspace ONE Access using vRealize Suite Lifecycle Manager:
        - Validates that the Planning and Preparation is available
        - Validates that network connectivity is available to vRealize Suite Lifecycle Manager
        - Makes a connection to the vRealize Suite Lifecycle Manager instance and validates that authentication possible
        - Generates the JSON specification file using the Planning and Preparation workbook and details from vRealize Suite Lifecycle Manager

        .EXAMPLE
        Export-WsaJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example creates a JSON deployment specification of Clustered Workspace ONE Access using the Planning and Preparation Workbook

        .EXAMPLE
        Export-WsaJsonSpec -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx -standard
        This example creates a JSON deployment specification of Standard Workspace ONE Access using the Planning and Preparation Workbook
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$standard
    )

    Try {

        if (!$PsBoundParameters.ContainsKey("workbook")) {
            $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
        }
        else {
            if (!(Test-Path -Path $workbook)) {
                Write-Error  "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found"
                Break
            }
        }

        if ($PsBoundParameters.ContainsKey("standard")) { $deploymentType = "Standard (Single Node)" } else { $deploymentType = "Clustered"}

        $pnpWorkbook = Open-ExcelPackage -Path $workbook

        ### Obtain Configuration Information from vRealize Suite Lifecycle Manager
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    $vcfVersion = ((Get-VCFManager).version -Split ('\.\d{1}\-\d{8}')) -split '\s+' -match '\S'
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {   
                            if ($wsaCertificate = Get-vRSLCMLockerCertificate | Where-Object {$_.alias -eq $pnpWorkbook.Workbook.Names["xreg_wsa_cert_name"].Value}) {
                                if ($defaultPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["global_env_admin_password_alias"].Value) { 
                                    if ($configAdminPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["local_configadmin_password_alias"].Value) { 
                                        if ($wsaPassword = Get-vRSLCMLockerPassword -alias $pnpWorkbook.Workbook.Names["local_admin_password_alias"].Value) {
                                            if ($vcfVersion -eq "4.5.0") {
                                                $vcCredentials = Get-vRSLCMLockerPassword | Where-Object {$_.userName -match (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "@vsphere.local")}
                                            } else {
                                                $vcCredentials = Get-vRSLCMLockerPassword -alias (($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0] + "-" + $pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value)
                                            }
                                            if ($datacenterName = Get-vRSLCMDatacenter | Where-Object {$_.dataCenterName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value}) {
                                                $xintEnvironment = Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $pnpWorkbook.Workbook.Names["vrslcm_xreg_env"].Value}
                                                $infrastructurePropertiesObject = @()
                                                $infrastructurePropertiesObject += [pscustomobject]@{
                                                    'acceptEULA'            = "true"
                                                    'enableTelemetry'        = "true"
                                                    'regionName'            = "default"
                                                    'zoneName'                = "default"
                                                    'dataCenterVmid'        = $datacenterName.dataCenterVmid
                                                    'vCenterName'            = ($pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value).Split(".")[0]
                                                    'vCenterHost'            = $pnpWorkbook.Workbook.Names["mgmt_vc_fqdn"].Value
                                                    'vcUsername'            = $vcCredentials.userName
                                                    'vcPassword'            = ("locker:password:" + $($vcCredentials.vmid) + ":" + $($vcCredentials.alias))
                                                    'defaultPassword'        = ("locker:password:" + $($defaultPassword.vmid) + ":" + $($defaultPassword.alias))
                                                    'certificate'            = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias))
                                                    'cluster'                = ($pnpWorkbook.Workbook.Names["mgmt_datacenter"].Value + "#" + $pnpWorkbook.Workbook.Names["mgmt_cluster"].Value)
                                                    'storage'                = $pnpWorkbook.Workbook.Names["mgmt_vsan_datastore"].Value
                                                    'diskMode'                = "thin"
                                                    'network'                = $pnpWorkbook.Workbook.Names["xreg_seg01_name"].Value
                                                    'masterVidmEnabled'        = "false"
                                                    'dns'                    = ($pnpWorkbook.Workbook.Names["region_dns1_ip"].Value + "," + $pnpWorkbook.Workbook.Names["region_dns2_ip"].Value)
                                                    'domain'                = $pnpWorkbook.Workbook.Names["region_ad_parent_fqdn"].Value
                                                    'gateway'                = $pnpWorkbook.Workbook.Names["xreg_seg01_gateway_ip"].Value
                                                    'netmask'                = $pnpWorkbook.Workbook.Names["xreg_seg01_mask"].Value
                                                    'searchpath'            = $pnpWorkbook.Workbook.Names["parent_dns_zone"].Value
                                                    'timeSyncMode'            = "ntp"
                                                    'ntp'                    = $pnpWorkbook.Workbook.Names["xregion_ntp1_server"].Value
                                                    'vcfProperties'            = '{"vcfEnabled":true,"sddcManagerDetails":[{"sddcManagerHostName":"' + $pnpWorkbook.Workbook.Names["sddc_mgr_fqdn"].Value + '","sddcManagerName":"default","sddcManagerVmid":"default"}]}'
                                                }

                                                $infrastructureObject = @()
                                                $infrastructureObject += [pscustomobject]@{
                                                    'properties'    = ($infrastructurePropertiesObject | Select-Object -Skip 0)
                                                }

                                                ### Generate the Properties Details
                                                $productPropertiesObject = @()
                                                $productPropertiesObject += [pscustomobject]@{
                                                    'vidmAdminPassword'             = ("locker:password:" + $($wsaPassword.vmid) + ":" + $($wsaPassword.alias))
                                                    'syncGroupMembers'              = $true
                                                    'nodeSize'                      = ($pnpWorkbook.Workbook.Names["xreg_wsa_node_size"].Value).ToLower()
                                                    'defaultConfigurationEmail'     = $pnpWorkbook.Workbook.Names["xreg_configadmin_email"].Value
                                                    'defaultConfigurationUsername'  = $pnpWorkbook.Workbook.Names["local_configadmin_username"].Value
                                                    'defaultConfigurationPassword'  = ("locker:password:" + $($configAdminPassword.vmid) + ":" + $($configAdminPassword.alias))
                                                    'defaultTenantAlias'            = ""
                                                    'vidmDomainName'                = ""
                                                    'certificate'                   = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias))
                                                    'contentLibraryItemId'          = ""
                                                    'fipsMode'                      = "false"
                                                }

                                                #### Generate Workspace ONE Access Details
                                                if (!$PsBoundParameters.ContainsKey("standard")) {
                                                    $clusterLbProperties = @()
                                                    $clusterLbProperties += [pscustomobject]@{
                                                        'hostName'                = $pnpWorkbook.Workbook.Names["xreg_wsa_virtual_fqdn"].Value
                                                        'lockerCertificate'     = ("locker:certificate:" + $($wsaCertificate.vmid) + ":" + $($wsaCertificate.alias))
                                                    }
                                                
                                                    $clusterDelegateObject = @()
                                                    $clusterDelegateObject += [pscustomobject]@{
                                                        'ip'            = $pnpWorkbook.Workbook.Names["xreg_wsa_delegate_ip"].Value
                                                    }

                                                    $clusterVipsObject = @()
                                                    $clusterVipsObject += [pscustomobject]@{
                                                        'type'            = "vidm-lb"
                                                        'properties'    = ($clusterLbProperties | Select-Object -Skip 0)
                                                    }
                                                    $clusterVipsObject += [pscustomobject]@{
                                                        'type'            = "vidm-delegate"
                                                        'properties'    = ($clusterDelegateObject | Select-Object -Skip 0)
                                                    }

                                                    $clusterObject = @()
                                                    $clusterObject += [pscustomobject]@{
                                                        'clusterVips'    = $clusterVipsObject
                                                    }
                                                } else {
                                                    $clusterObject = @()
                                                    $clusterObject += [pscustomobject]@{
                                                        'clusterVips'    = @()
                                                    }
                                                }

                                                #### Generate vRealize Log Insight Node Details
                                                $wsaPrimaryProperties = @()
                                                $wsaPrimaryProperties += [pscustomobject]@{
                                                    'hostName'          = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_fqdn"].Value
                                                    'vmName'            = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_hostname"].Value
                                                    'ip'                = $pnpWorkbook.Workbook.Names["xreg_wsa_nodea_ip"].Value
                                                }

                                                $wsaSecondary1Properties = @()
                                                $wsaSecondary1Properties += [pscustomobject]@{
                                                    'hostName'          = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_fqdn"].Value
                                                    'vmName'            = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_hostname"].Value
                                                    'ip'                = $pnpWorkbook.Workbook.Names["xreg_wsa_nodeb_ip"].Value
                                                }

                                                $wsaSecondary2Properties = @()
                                                $wsaSecondary2Properties += [pscustomobject]@{
                                                    'hostName'          = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_fqdn"].Value
                                                    'vmName'            = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_hostname"].Value
                                                    'ip'                = $pnpWorkbook.Workbook.Names["xreg_wsa_nodec_ip"].Value
                                                }

                                                $nodesObject = @()
                                                $nodesobject += [pscustomobject]@{
                                                    'type'            = "vidm-primary"
                                                    'properties'    = ($wsaPrimaryProperties | Select-Object -Skip 0)
                                                }
                                                if (!$PsBoundParameters.ContainsKey("standard")) {
                                                    $nodesobject += [pscustomobject]@{
                                                        'type'            = "vidm-secondary"
                                                        'properties'    = ($wsaSecondary1Properties | Select-Object -Skip 0)
                                                    }
                                                    $nodesobject += [pscustomobject]@{
                                                        'type'            = "vidm-secondary"
                                                        'properties'    = ($wsaSecondary2Properties | Select-Object -Skip 0)
                                                    }
                                                }

                                                #### Generate the Workspace ONE Properties Section
                                                if ($vcfVersion -eq "4.3.0") { $wsaVersion = "3.3.5"}
                                                if ($vcfVersion -eq "4.3.1") { $wsaVersion = "3.3.5"}
                                                if ($vcfVersion -eq "4.4.0") { $wsaVersion = "3.3.6"}
                                                if ($vcfVersion -eq "4.4.1") { $wsaVersion = "3.3.6"}
                                                if ($vcfVersion -eq "4.5.0") { $wsaVersion = "3.3.6"}
                                                $productsObject = @()
                                                $productsObject += [pscustomobject]@{
                                                    'id'             = "vidm"
                                                    'version'        = $wsaVersion
                                                    'properties'    = ($productPropertiesObject  | Select-Object -Skip 0)
                                                    'clusterVIP'    = ($clusterObject  | Select-Object -Skip 0)
                                                    'nodes'            = $nodesObject    
                                                }
                                                
                                                $wsaDeploymentObject = @()
                                                $wsaDeploymentObject += [pscustomobject]@{
                                                    'environmentId'         = "globalenvironment"
                                                    'environmentName'       = "globalenvironment"
                                                    'infrastructure'        = ($infrastructureObject  | Select-Object -Skip 0)
                                                    'products'              = $productsObject
                                                } 

                                                $wsaDeploymentObject | ConvertTo-Json -Depth 12 | Out-File -Encoding UTF8 -FilePath "wsaDeploymentSpec.json" 
                                                
                                                Write-Output "Creation of Deployment JSON Specification file for $deploymentType Workspace ONE Access: SUCCESSFUL"
                                            }
                                            else {
                                                Write-Error "Datacenter Provided in the Planning and Preparation Workbook '$($pnpWorkbook.Workbook.Names["vrslcm_xreg_dc"].Value)' does not exist, create and retry"
                                            }
                                        }
                                        else {
                                            Write-Error "Root Password with alias '$($pnpWorkbook.Workbook.Names["local_admin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                                        }
                                    }
                                    else {
                                        Write-Error "Admin Password with alias '$($pnpWorkbook.Workbook.Names["global_env_admin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                                    }
                                }
                                else {
                                    Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["local_configadmin_password_alias"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                                }
                            }
                            else {
                                Write-Error "Certificate with alias '$($pnpWorkbook.Workbook.Names["xreg_wsa_cert_name"].Value)' not found in the vRealize Suite Lifecycle Manager Locker, add and retry"
                            }
                        }
                    }
                }
            }
        }
        Close-ExcelPackage $pnpWorkbook -NoSave -ErrorAction SilentlyContinue
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Export-WsaJsonSpec

Function New-WSADeployment {
    <#
        .SYNOPSIS
        Deploy Clustered Workspace ONE Access to vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The New-WSADeployment cmdlet deploys Clustered Workspace ONE Access via vRealize Suite Lifecycle Manager. The
        cmdlet connects to SDDC Manager using the -server, -user, and -password values:
        - Validates that network connectivity is available to the SDDC Manager instance
        - Makes a connection to the SDDC Manager instance and validates that authentication possible
        - Validates that Clustered Workspace ONE Access has not been deployed in VMware Cloud Foundation aware mode
        - Requests a new deployment of Clustered Workspace ONE Access

        .EXAMPLE
        New-WSADeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx
        This example starts a deployment of Clustered Workspace ONE Access using the Planning and Preparation Workbook

        .EXAMPLE
        New-WSADeployment -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -workbook .\pnp-workbook.xlsx -standard
        This example starts a deployment of Standard Workspace ONE Access using the Planning and Preparation Workbook
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$workbook,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$monitor,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$standard
    )

    if (!$PsBoundParameters.ContainsKey("workbook")) {
        $workbook = Get-ExternalFileName -title "Select the Planning and Preparation Workbook (.xlsx)" -fileType "xlsx" -location "default"
    }
    else {
        if (!(Test-Path -Path $workbook)) {
            Write-Error  "Planning and Preparation Workbook (.xlsx) '$workbook' File Not Found"
            Break
        }
    }

    if ($PsBoundParameters.ContainsKey("standard")) { $deploymentType = "Standard (Single Node)" } else { $deploymentType = "Clustered"}

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (($vcfVrslcmDetails = Get-vRSLCMServerDetail -fqdn $server -username $user -password $pass)) {
                    if (Test-vRSLCMConnection -server $vcfVrslcmDetails.fqdn) {
                        if (Test-vRSLCMAuthentication -server $vcfVrslcmDetails.fqdn -user $vcfVrslcmDetails.adminUser -pass $vcfVrslcmDetails.adminPass) {
                            if (!$PsBoundParameters.ContainsKey("standard")) {
                                Export-WSAJsonSpec -server $server -user $user -pass $pass -workbook $workbook | Out-Null
                            } else {
                                Export-WSAJsonSpec -server $server -user $user -pass $pass -workbook $workbook -standard | Out-Null
                            }
                            $json = (Get-Content -Raw .\wsaDeploymentSpec.json)
                            $jsonSpec = $json | ConvertFrom-Json
                            if (!(Get-vRSLCMEnvironment | Where-Object {$_.environmentName -eq $jsonSpec.environmentName})) {
                                if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.vidmAdminPassword.Split(":")[3])) {
                                    if (Get-vRSLCMLockerPassword -alias $($jsonSpec.products.properties.defaultConfigurationPassword.Split(":")[3])) {
                                        if (Get-vRSLCMLockerCertificate | Where-Object {$_.alias -Match $($jsonSpec.products.properties.certificate.Split(":")[3])}) {
                                            $newRequest = Add-vRSLCMEnvironment -json $json
                                            if ($newRequest) {
                                                if ($PsBoundParameters.ContainsKey("monitor")) {
                                                    Start-Sleep 10
                                                    Watch-vRSLCMRequest -vmid $($newRequest.requestId)
                                                }
                                                else {
                                                    Write-Output "Deployment Rquest for $deploymentType Workspace ONE Access (Request Ref: $($newRequest.requestId))"
                                                }
                                            }
                                            else {
                                                Write-Error "Request to deploy $deploymentType Workspace ONE Access failed, check the vRealize Suite Lifecycle Manager UI"
                                            }
                                            
                                        }
                                        else {
                                            Write-Error "Certificate in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.certificate.Split(":")[3])), does not exist: FAILED"
                                        }
                                    }
                                    else {
                                        Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.defaultConfigurationPassword.Split(":")[3])), does not exist: FAILED"
                                    }
                                }
                                else {
                                    Write-Error "Password in vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)) Locker with alias ($($jsonSpec.products.properties.vidmAdminPassword.Split(":")[3])), does not exist: FAILED"
                                }
                            }
                            else {
                                Write-Warning "$deploymentType Workspace ONE Access in environment ($($jsonSpec.environmentName)) on vRealize Suite Lifecycle Manager ($($vcfVrslcmDetails.fqdn)), already exists: SKIPPED"
                            }
                        }
                    }
                } 
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-WSADeployment

Function Set-WorkspaceOneApplianceNtpConfig {
    <#
        .SYNOPSIS
        Configure Workspace ONE Access appliance NTP servers

        .DESCRIPTION
        The Set-WorkspaceOneApplianceNtpConfig cmdlet configures Workspace ONE Access appliance NTP servers

        .EXAMPLE
        Set-WorkspaceOneApplianceNtpConfig -vmName sfo-wsa01 -rootPass VMw@re1! -ntpServer "ntp.sfo.rainpole.io,ntp.lax.rainpole.io"
        This example sets the NTP servers for Workspace ONE Access node sfo-wsa01 to ntp.sfo.rainpole.io and ntp.lax.rainpole.io
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vmName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$rootPass,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer
    )

    try {
        $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --get'
        $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn
        if ($output.ScriptOutput -match "^server=$ntpServer$") {
            Write-Warning "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer), already performed: SKIPPED"
        }
        else {
            $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --set ' + $ntpServer
            $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn
            $scriptCommand = '/usr/local/horizon/scripts/ntpServer.hzn --get'
            $output = Invoke-VMScript -VM $vmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $rootPass -Server $vcfVcenterDetails.fqdn
            if ($output.ScriptOutput -match "^server=$ntpServer$") {
                Write-Output "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer): SUCCESSFUL"
            }
            else {
                Write-Error "Configuring NTP on Workspace ONE Access Instance ($vmName) to NTP Server ($ntpServer): POST_VALIDATION_FAILED"
            }
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-WorkspaceOneApplianceNtpConfig

Function New-vRSLCMAdapterOperation {
    <#
        .SYNOPSIS
        Add a vRealize Operations Adapter via vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The New-vRSLCMAdapterOperation cmdlet to create a vRealize Operations Manager Afapter in vRealize Suite Lifecycle Manager

        .EXAMPLE
        New-vRSLCMAdapterOperation -json .\addAdapter.json
        This example creates an adapter in vRealize Operations via vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentId
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json")) {
            if (!(Test-Path $json)) {
                Throw "JSON File Not Found"
            }
            else {
                $body = (Get-Content $json) # Read the json file contents into the $body variable
            }
        }

        $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId/vrops/adapterOperation"
        $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vrslcmHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRSLCMAdapterOperation

Function Get-vRSLCMProductNtpServer {
    <#
        .SYNOPSIS
        Get paginated list of product NTP servers in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Get-vRSLCMProductNtpServer cmdlet gets a paginated list of product NTP servers in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Get-vRSLCMProductNtpServer
        This example gets all product NTP servers in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer
    )

    Try {
        if ($PsBoundParameters.ContainsKey("ntpServer")) {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/ntp-servers"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response | Where-Object {$_.hostName -match $ntpServer}
        }
        else {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/ntp-servers"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMProductNtpServer

Function Remove-vRSLCMProductNtpServer {
    <#
        .SYNOPSIS
        Removes a specified NTP server from vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Remove-vRSLCMProductNtpServer cmdlet removes a specified NTP server from vRealize Suite Lifecycle Manager

        .EXAMPLE
        Remove-vRSLCMProductNtpServer -ntpServer ntp.lax.rainpole.io
        This example gets all product NTP servers in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$ntpServer
    )

    Try {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v3/settings/ntp-servers?ntpHostname=$ntpServer"
            $response = Invoke-RestMethod $uri -Method 'DELETE' -Headers $vrslcmHeaders
            $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRSLCMProductNtpServer

Function Get-vRSLCMApplianceNtpConfig {
    <#
        .SYNOPSIS
        Get appliance NTP configuration in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Get-vRSLCMApplianceNtpConfig cmdlet gets appliance NTP configuration in vRealize Suite Lifecycle Manager


        .EXAMPLE
        Get-vRSLCMApplianceNtpConfig
        This example gets the appliance NTP configuration in vRealize Suite Lifecycle Manager
    #>


    Try {

            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/system-details/time"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRSLCMApplianceNtpConfig

Function Add-vRSLCMProductNtpServer {
    <#
        .SYNOPSIS
        Add a server to product NTP configuration in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Add-vRSLCMProductNtpServer cmdlet adds a server tp product NTP configuration in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Add-vRSLCMProductNtpServer -ntpServer "ntp.lax.rainpole.io" -ntpServerDesc "VCF NTP Server 2"
        This adds the server ntp.lax.rainpole.io to the product NTP configuration in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServerDesc
    )

    $body = @"
{
    "hostName": "$ntpServer",
    "name": "$ntpServerDesc"
}
"@


    Try {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/settings/ntp-servers"
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body
            $response
        }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMProductNtpServer

Function Add-vRSLCMApplianceNtpConfig {
    <#
        .SYNOPSIS
        Add a server to appliance NTP configuration in vRealize Suite Lifecycle Manager

        .DESCRIPTION
        The Add-vRSLCMApplianceNtpConfig cmdlet adds a server to appliance NTP configuration in vRealize Suite Lifecycle Manager

        .EXAMPLE
        Add-vRSLCMApplianceNtpConfig -ntpServer ntp.lax.rainpole.io
        This adds the server ntp.lax.rainpole.io to the appliance NTP configuration in vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer
    )

    $existingNtpServers = (Get-vRSLCMApplianceNtpConfig).ntpServers

    $body = @"
{
    "syncWithHost": false,
    "ntpServerEnabled": true,
    "ntpServers": "$existingNtpServers,$ntpServer"
}
"@


    Try {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/settings/ntpsetting"
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body
            $response
        }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRSLCMApplianceNtpConfig

Function Set-vRSLCMApplianceNtpConfig {
    <#
        .SYNOPSIS
        Sets the appliance NTP configuration in vRealize Suite Lifecycle Manager to use only a specified NTP server

        .DESCRIPTION
        The Set-vRSLCMApplianceNtpConfig cmdlet sets the appliance NTP configuration in vRealize Suite Lifecycle Manager to use only a specified NTP server

        .EXAMPLE
        Add-vRSLCMApplianceNtpConfig -ntpServer ntp.sfo.rainpole.io
        This sets the appliance NTP configuration in vRealize Suite Lifecycle Manager to use only NTP server ntp.sfo.rainpole.io.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ntpServer
    )
    $body = @"
{
    "syncWithHost": false,
    "ntpServerEnabled": true,
    "ntpServers": "$ntpServer"
}
"@


    Try {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/settings/ntpsetting"
            $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders -Body $body
            $response
        }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRSLCMApplianceNtpConfig

Function Get-vRSLCMProductNode {
    <#
        .SYNOPSIS
        Gets the nodes in the vRealize Suite Lifecycle Manager inventory for a specified environment and product

        .DESCRIPTION
        The Get-vRSLCMProductNode cmdlet gets the nodes in the vRealize Suite Lifecycle Manager inventory for a specified environment and product

        .EXAMPLE
        Get-vRSLCMProductNode -environmentName globalenvironment -product vidm
        This returns a list of nodes in the Workspace ONE Access instance managed by vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environmentName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$product
    )

    $environmentId = (Get-vRSLCMEnvironment | Where-Object {$_.environmentName -match $environmentName}).environmentId

    Try {
            $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environmentId/products/$product/deployed-vms"
            $response = Invoke-RestMethod $uri -Method 'GET' -Headers $vrslcmHeaders
            $response
        }
    Catch [System.Net.WebException] {
        $PSCmdlet.ThrowTerminatingError($PSItem)
    }
}
Export-ModuleMember -Function Get-vRSLCMProductNode

Function Stop-vRSLCMProductNode {
    <#
        .SYNOPSIS
        Shuts down nodes in a vRealize Suite Lifecycle Manager-managed product

        .DESCRIPTION
        The Stop-vRSLCMProductNode cmdlet shuts down nodes in a vRealize Suite Lifecycle Manager-managed product

        .EXAMPLE
        Stop-vRSLCMProductNode -environment globalenvironment -product vidm
        This example shuts down all nodes in the Workspace ONE Access instance managed by vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environment,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$product
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environment/products/$product/power-off"
        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Stop-vRSLCMProductNode

Function Start-vRSLCMProductNode {
    <#
        .SYNOPSIS
        Starts nodes in a vRealize Suite Lifecycle Manager-managed product

        .DESCRIPTION
        The Start-vRSLCMProductNode cmdlet starts nodes in a vRealize Suite Lifecycle Manager-managed product

        .EXAMPLE
        Start-vRSLCMProductNode -environment globalenvironment -product vidm
        This example starts all nodes in the Workspace ONE Access instance managed by vRealize Suite Lifecycle Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$environment,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$product
    )

    Try {
        $uri = "https://$vrslcmAppliance/lcm/lcops/api/v2/environments/$environment/products/$product/power-on"
        $response = Invoke-RestMethod $uri -Method 'POST' -Headers $vrslcmHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Start-vRSLCMProductNode

#EndRegion End vRealize Suite Lifecycle Manager Functions ######
#####################################################################

#####################################################################
#Region Start vRealize Automation Functions ######

Function Request-vRAToken {
    <#
        .SYNOPSIS
        Connects to the specified vRealize Automation and obtains authorization token

        .DESCRIPTION
        The Request-vRAToken cmdlet connects to the specified vRealize Automation and obtains an authorization token.
        It is required once per session before running all other cmdlets.

        .EXAMPLE
        Request-vRAToken -fqdn xreg-vra01.rainpole.io -username configadmin -password VMware1!
        This example shows how to connect to the vRealize Automation appliance

        .EXAMPLE
        Request-vRAToken -fqdn xreg-vra01.rainpole.io -username configadmin -password VMware1! -displayToken
        This example shows how to connect to the vRealize Automation appliance and display the token needed for Terraform
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tenant,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$displayToken
    )

    if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) {
        $creds = Get-Credential # Request Credentials
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }

    $vraBasicHeaders = createBasicAuthHeader $username $password
    $Global:vraAppliance = $fqdn

    Try {
        # Validate credentials by executing an API call
        $uri = "https://$vraAppliance/csp/gateway/am/api/login?access_token"
        if ($PsBoundParameters.ContainsKey("tenant")) {
            $body = "{ ""username"":""$username"",""password"":""$password"",""domain"":""$tenant""}"
        }
        else {
            $body = "{ ""username"":""$username"",""password"":""$password""}"
        }

        if ($PSEdition -eq 'Core') {
            $vraResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vraBasicHeaders -Body $body -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        }
        else {
            $vraResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vraBasicHeaders -Body $body -UseBasicParsing
        }

        if ($vraResponse.StatusCode -eq 200) {
            $Global:vraHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
            $vraHeaders.Add("Accept", "application/json")
            $vraHeaders.Add("Content-Type", "application/json")
            $vraHeaders.Add("Authorization", "Bearer " + $vraResponse.Headers.'Csp-Auth-Token')
            Write-Output "Successfully connected to vRealize Automation: $vraAppliance"
            if ($PsBoundParameters.ContainsKey("displayToken")) {
                Write-Output "`n---------Refresh Token---------"
                ((Select-String -InputObject $vraResponse -Pattern '"refresh_token":') -Split ('"'))[3]
                Write-Output "-------------------------------`n"
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-vRAToken

Function Get-vRAOrganizationId {
    <#
        .SYNOPSIS
        Get the organization ID for the logged in user

        .DESCRIPTION
        The Get-vRAOrganizationId cmdlet gets the organization Id for the logged in user

        .EXAMPLE
        Get-vRAOrganizationId
        This example gets organization Id for the logged in user
    #>


    Try {
        $uri = "https://$vraAppliance/csp/gateway/am/api/loggedin/user/orgs"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response.refLinks
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRAOrganizationId

Function Get-vRAOrganizationDisplayName {
    <#
        .SYNOPSIS
        Get the organization display name

        .DESCRIPTION
        The Get-vRAOrganizationDisplayName cmdlet gets the organization display name

        .EXAMPLE
        Get-vRAOrganizationDisplayName -orgId <orgid>
        This example gets organization display name for the organization Id provided
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId
    )

    Try {
        $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRAOrganizationDisplayName

Function Set-vRAOrganizationDisplayName {
    <#
        .SYNOPSIS
        Configures the organization display name

        .DESCRIPTION
        The Set-vRAOrganizationDisplayName cmdlet sets the organization display name

        .EXAMPLE
        Set-vRAOrganizationDisplayName -orgId <orgid> -displayName
        This example configures the organization display name for the organization Id provided
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName
    )

    Try {
        $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId"
        $json = '{ "displayName": "'+ $displayName +'" }'
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $json
        $response.refLink
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRAOrganizationDisplayName

Function Get-vRACloudAccount {
    <#
        .SYNOPSIS
        Get cloud accounts

        .DESCRIPTION
        The Get-vRACloudAccount cmdlet all cloud accounts within the current organization

        .EXAMPLE
        Get-vRACloudAccount
        This example gets all cloud accounts within the current organization

        .EXAMPLE
        Get-vRACloudAccount -type vsphere
        This example gets all vsphere cloud accounts within the current organization, supports vsphere, vmw, gcp, nsx-v, nsx-t, aws and azure
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateSet("vsphere","vmc","gcp","nsx-v","nsx-t","aws","azure")] [ValidateNotNullOrEmpty()] [String]$type
    )

    Try {
        if ($PsBoundParameters.ContainsKey("type")) {
            if ($type -eq "vsphere") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vsphere"}
            if ($type -eq "vmc") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vmc"}
            if ($type -eq "gcp") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-gcp"}
            if ($type -eq "nsx-v") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-v"}
            if ($type -eq "nsx-t") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-t"}
            if ($type -eq "aws") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-aws"}
            if ($type -eq "azure") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-azure"}
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
            $response.content
        }
        else {
            $uri = "https://$vraAppliance/iaas/api/cloud-accounts"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
            $response.content
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRACloudAccount

Function Add-vRACloudAccount {
    <#
        .SYNOPSIS
        Add a cloud account

        .DESCRIPTION
        The Add-vRACloudAccount cmdlet adds a cloud accounts within the current organization

        .EXAMPLE
        Add-vRACloudAccount -type vsphere -json (Get-Content -raw .\vsphereCloudAccount.json)
        This example adds a vsphere cloud account within the current organization

        .EXAMPLE
        Add-vRACloudAccount -type nsx-t -json (Get-Content -raw .\nsxtCloudAccount.json)
        This example adds a nsx-t cloud account within the current organization
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vsphere","vmc","gcp","nsx-v","nsx-t","aws","azure")] [ValidateNotNullOrEmpty()] [String]$type,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        if ($type -eq "vsphere") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vsphere"}
        if ($type -eq "vmc") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-vmc"}
        if ($type -eq "gcp") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-gcp"}
        if ($type -eq "nsx-v") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-v"}
        if ($type -eq "nsx-t") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-nsx-t"}
        if ($type -eq "aws") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-aws"}
        if ($type -eq "azure") {$uri = "https://$vraAppliance/iaas/api/cloud-accounts-azure"}
        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRACloudAccount

Function Remove-vRACloudAccount {
    <#
        .SYNOPSIS
        Remove a cloud account

        .DESCRIPTION
        The Remove-vRACloudAccount cmdlet removes a cloud account within the current organization

        .EXAMPLE
        Remove-vRACloudAccount -id <id>
        This example removes the cloud account with the ID within the current organization
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vraAppliance/iaas/api/cloud-accounts/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRACloudAccount

Function Get-vRANotification {
    <#
        .SYNOPSIS
        Get notification configuration

        .DESCRIPTION
        The Get-vRANotification cmdlet gets the notification configuation from vRealize Automation

        .EXAMPLE
        Get-vRANotification
        This example gets the current notification configuration from vRealize Automation
    #>


    Try {
        $uri = "https://$vraAppliance/notification/api/email-config"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRANotification

Function New-vRANotification {
    <#
        .SYNOPSIS
        Add notification configuration

        .DESCRIPTION
        The New-vRANotification cmdlet adds the notification configuation in vRealize Automation

        .EXAMPLE
        New-vRANotification -name smtp.rainpole.io -serverName smtp.rainpole.io -emailAddress vra-no-reply@rainpole.io -sender administrator -trustCert true -connection NONE -authentication false
        This example adds the notification configuration in vRealize Automation without authentication

        .EXAMPLE
        New-vRANotification -name smtp.rainpole.io -serverName smtp.rainpole.io -emailAddress vra-no-reply@rainpole.io -sender administrator -trustCert true -connection NONE -authentication true -username administrator -password VMw@re1!
        This example adds the notification configuration in vRealize Automation with authentication
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serverName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender,
        [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$trustCert,
        [Parameter (Mandatory = $true)] [ValidateSet("SSL","STARTTLS","NONE")] [ValidateNotNullOrEmpty()] [String]$connection,
        [Parameter (Mandatory = $true)] [ValidateSet("true","false")] [ValidateNotNullOrEmpty()] [String]$authentication,
        [Parameter (ParameterSetName = "auth", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$userName,
        [Parameter (ParameterSetName = "auth", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password
        
    )

    Try {
        if ($connection -eq "SSL") {$port = "465"} elseif ($connection -eq "STARTTLS") {$port = "587"} else {$port = "25"}
        $uri = "https://$vraAppliance/notification/api/email-config"
        $body = '{
            "name": "'
 + $name + '",
            "host": "'
 + $serverName + '",
            "port": '
 + $port +',
            "sender": "'
 + $emailAddress + '",
            "senderName": "'
 + $sender + '",
            "connectionSecurity": "'
 + $connection + '",
            "authenticationRequired": '
 + $authentication + ',
            "userName": "'
 + $userName +'",
            "password": "'
 + $password +'",
            "trustHost": '
 + $trustCert + '
        }'

        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRANotification

Function Remove-vRANotification {
    <#
        .SYNOPSIS
        Remove notification configuration

        .DESCRIPTION
        The Remove-vRANotification cmdlet removes the notification configuation from vRealize Automation

        .EXAMPLE
        Remove-vRANotification
        This example removes the current notification configuration from vRealize Automation
    #>


    Try {
        $uri = "https://$vraAppliance/notification/api/email-config"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRANotification

Function Get-vRAResourceCompute {
    <#
        .SYNOPSIS
        Get compute resources

        .DESCRIPTION
        The Get-vRAResourceCompute cmdlet gets a list of known compute resources from vRealize Automation

        .EXAMPLE
        Get-vRAResourceCompute
        This example gets all known compute resources from vRealize Automation

        .EXAMPLE
        Get-vRAResourceCompute -id <compute_resource_id>
        This example gets a compute resource from vRealize Automation by id
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vraAppliance/iaas/api/fabric-computes/$id"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
            $response
        }
        else {
            $uri = "https://$vraAppliance/iaas/api/fabric-computes"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
            $response.content
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRAResourceCompute

Function Add-vRAResourceComputeTag {
    <#
        .SYNOPSIS
        Add a compute resource tag

        .DESCRIPTION
        The Add-vRAResourceComputeTag cmdlet adds a tag to a compute resources in vRealize Automation

        .EXAMPLE
        Add-vRAResourceComputeTag -id <compute_resource_id> -tagKey enabled -tagValue true
        This example adds a new tag to a compute resourcein vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagKey,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagValue
    )

    Try {
        $existingTags = (Get-vRAResourceCompute -id $id | Select-Object tags).tags
        $tagObject = @()
        foreach ($tag in $existingTags) {
            if ($tag.key -ne $tagKey) {
                $tagObject += [pscustomobject]@{
                    'key'= $tag.key
                    'value' = $tag.value
                }
            }
            elseif ($tag.key -eq $tagKey) {
                $tagObject += [pscustomobject]@{
                    'key'= $tagkey
                    'value' = $tagvalue
                }
            }
        }
        if (!($tagObject.key -eq $tagKey)) {
            $tagObject += [pscustomobject]@{
                    'key'= $tagkey
                    'value' = $tagvalue
                }
        }
        $allTagsObject = @()
        $allTagsObject += [pscustomobject]@{
            'tags'         = $tagObject
        }
        $json = $allTagsObject | ConvertTo-Json -Depth 3
        $uri = "https://$vraAppliance/iaas/api/fabric-computes/$id"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRAResourceComputeTag

Function Get-vRACloudZone {
    <#
        .SYNOPSIS
        Get Cloud Zones

        .DESCRIPTION
        The Get-vRACloudZone cmdlet gets a list of known Cloud Zones from vRealize Automation

        .EXAMPLE
        Get-vRACloudZone
        This example gets all known Cloud Zones from vRealize Automation

        .EXAMPLE
        Get-vRACloudZone -id <cloud_zone_id>
        This example gets a Cloud Zone from vRealize Automation by id

        .EXAMPLE
        Get-vRACloudZone -id <cloud_zone_id> -compute
        This example gets a Cloud Zone Compute details from vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$compute
    )

    Try {
        if ($PsBoundParameters.ContainsKey("id") -and $PsBoundParameters.ContainsKey("compute")) {
            $uri = "https://$vraAppliance/iaas/api/zones/$id/computes"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
            $response.content
        }
        elseif ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vraAppliance/iaas/api/zones/$id"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
            $response
        }
        else {
            $uri = "https://$vraAppliance/iaas/api/zones"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
            $response.content
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRACloudZone

Function Get-vRAAPIVersion {
    <#
        .SYNOPSIS
        Retrieve the vRealize Automation version information
        
        .DESCRIPTION
        The Get-vRAAPIVersion cmdlet returns the latest version of the API

        .EXAMPLE
        Get-vRAAPIVersion
    #>

    Try {
        $uri = "https://$vraAppliance/iaas/api/about"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response.latestApiVersion         
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRAAPIVersion

Function Get-vRAIntegrationDetail {
    <#
        .SYNOPSIS
        Get an integration detail of an item from vRealize Automation

        .DESCRIPTION
        The Get-vRAIntegrationDetail cmdlet returns an integration details of an item from vRealize Automation

        .EXAMPLE
        Get-vRAIntegrationDetail -integrationType "vrops" -getVCID
        This example returns the ids of the vCenter Server instances managed by the vRealize Operations Manager

        Get-vRAIntegrationDetail -integrationType "vrops" -integrationName "vRealize Operations Manager" -getIntegrationID
        This example returns the integration id of vRealize Operations Manager which is integrated with the vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vrops")] [ValidateNotNullOrEmpty()] [String]$integrationType,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$integrationName,
        [switch]$getVCID,
        [switch]$getIntegrationID
    )
    Try {
        $vraapiVersion = "apiVersion=" + (Get-vRAAPIVersion)
        $uri = "https://$vraAppliance/iaas/api/integrations?$vraapiVersion"        
        $response = Invoke-RestMethod -Method Get -Uri $uri -Headers $vraHeaders
        if ($getVCID) {
            ($response.content | Where-Object integrationType -Match $integrationType).customProperties.vcIds
        }
        if ($getIntegrationID) {
            if (($PsBoundParameters.ContainsKey("integrationType")) -and ($PsBoundParameters.ContainsKey("integrationName"))) {
                (($response.content | Where-Object integrationType -Match $integrationType) | Where-Object name -Match "\b$integrationName\b").id        
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRAIntegrationDetail

Function Update-vRACloudZone {
    <#
        .SYNOPSIS
        Update a Cloud Zones

        .DESCRIPTION
        The Update-vRACloudZone cmdlet updates a Cloud Zones in vRealize Automation

        .EXAMPLE
        Update-vRACloudZone -id <cloud_zone_id> -folder sfo-w01-fd-workload
        This example adds a folder to theCloud Zone in vRealize Automation by id

        .EXAMPLE
        Update-vRACloudZone -id <cloud_zone_id> -tagKey enabled -tagValue true
        This example adds tags that should be used to dynamically obtain resources for a Cloud Zone in vRealize Automation by id

        .EXAMPLE
        Update-vRACloudZone -id <cloud_zone_id> placementPolicy ADVANCED
        This example updates the placement policy for Cloud Zones to ADVANCED in vRealize Automation by id
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (ParameterSetName = "folder", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$folder,
        [Parameter (ParameterSetName = "tag", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagKey,
        [Parameter (ParameterSetName = "tag", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$tagValue,
        [Parameter (ParameterSetName = "placementPolicy", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$placementPolicy
   
    )
    Try {
        $cloudZoneDetails = Get-VRACloudZone -id $id
        if ($PsBoundParameters.ContainsKey("id") -and $PsBoundParameters.ContainsKey("folder")) {
            $json = '{ "name": "' + $($cloudZoneDetails.name) + '", "folder": "' + $folder +'" }'
        }
        if ($PsBoundParameters.ContainsKey("id") -and $PsBoundParameters.ContainsKey("tagKey") -and $PsBoundParameters.ContainsKey("tagValue")) {
            $json = '{ "name": "' + $($cloudZoneDetails.name) + '", "tagsToMatch": [ { "key": "' + $tagKey + '", "value": "' + $tagValue + '" } ] }'
        }
        if ($PsBoundParameters.ContainsKey("id") -and $PsBoundParameters.ContainsKey("placementPolicy")) {
            if ($placementPolicy -eq "ADVANCED") {
                if (((Get-vRAIntegrationDetail -integrationType vrops -getVCID).split(',')).contains(((Get-vRACloudAccount -type vsphere).customProperties.vcUuid))) {
                    $cloudZoneDetails.placementPolicy = $placementPolicy
                    $cloudZoneDetails.customProperties | Add-Member -Type NoteProperty  -Name "__ignoreAdvancedPolicyFailure" -Value "true" -Force
                    $json = $cloudZoneDetails | ConvertTo-Json -Depth 4
                }
                else {
                    Write-Error "vRealize Operations Manager is not integrated with vRealize Automation for the vCenter Server configured in CloudZone(id :$id) , check the integration: PRE_VALIDATION_FAILED"
                    break
                }
            }
            else {   
                $cloudZoneDetails.placementPolicy = $placementPolicy
                $cloudZoneDetails.customProperties.PSObject.Properties.Remove('__ignoreAdvancedPolicyFailure')
                $json = $cloudZoneDetails | ConvertTo-Json -Depth 4
            }
        }
        $uri = "https://$vraAppliance/iaas/api/zones/$id"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Update-vRACloudZone

Function Remove-vRACloudZone {
    <#
        .SYNOPSIS
        Remove Cloud Zones

        .DESCRIPTION
        The Remove-vRACloudZone cmdlet deletes a Cloud Zones from vRealize Automation

        .EXAMPLE
        Remove-vRACloudZone -id <cloud_zone_id>
        This example deletes a Cloud Zone from vRealize Automation by id
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vraAppliance/iaas/api/zones/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRACloudZone

Function Get-vRAServices {
    <#
        .SYNOPSIS
        Get the services.

        .DESCRIPTION
        The Get-vRAServices cmdlet returns the services information from an organization in vRealize Automation.

        .EXAMPLE
        Get-vRAServices
        This example returns the services information from vRealize Automation by orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId
    )

    Try {
        $uri = "https://$vraAppliance/csp/gateway/slc/api/v2/orgs/$orgId/services"
        $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $vraHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Get-vRAServices

Function Get-vRAUser {
    <#
        .SYNOPSIS
        Get the user in an organization.

        .DESCRIPTION
        The Get-vRAUser cmdlet returns the user information from an organization in vRealize Automation.

        .EXAMPLE
        Get-vRAUser -orgId $orgId -email jdoe@rainpole.io
        This example returns the user information for an organization in vRealize Automation by orgId and email.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$email
    )

    Try {
        $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId/users/search?userSearchTerm=$email"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Get-vRAUser

Function New-vRAUser {
    <#
        .SYNOPSIS
        Adds a user in an organization.

        .DESCRIPTION
        The New-vRAUser cmdlet adds a user in vRealize Automation.

        .EXAMPLE
        New-vRAUser -userId $userId -orgId $serviceRole -serviceDefinitionId $serviceDefinitionId -orgRole $orgRole> -serviceRole $serviceRole>
        This example adds a user to vRealize Automation by userId and orgId and assisgnes the required orgRole and serviceRole.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole,
        [Parameter (Mandatory = $false)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
    )

    Try {
        $body = '{
                    "organizationRoles": {
                        "roleNamesToAdd": [
                        "'
 + $orgRole + '"
                        ],
                        "roleNamesToRemove": []
                    },
                    "serviceRoles": [
                        {
                        "serviceDefinitionId": "'
 + $serviceDefinitionId + '",
                        "roleNamesToAdd": [
                            "'
 + $serviceRole + '"
                        ],
                        "roleNamesToRemove": []
                        }
                    ]
                }'

        $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function New-vRAUser

Function Get-vRAGroup {
    <#
        .SYNOPSIS
        Get the group in an organization.

        .DESCRIPTION
        The Get-vRAGroup cmdlet returns the group information from an organization in vRealize Automation.

        .EXAMPLE
        Get-vRAGroup -orgId $orgId -displayName gg-vra-cloud-assemhly-admins@rainpole.io
        This example returns the group information from vRealize Automation by orgId and displayName.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$displayName
    )

    Try {
        $uri = "https://$vraAppliance/csp/gateway/am/api/orgs/$orgId/groups-search?groupSearchTerm=$displayName"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response.results
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Get-vRAGroup

Function New-vRAGroup {
    <#
        .SYNOPSIS
        Adds a group in an organization.

        .DESCRIPTION
        The New-vRAGroup cmdlet adds a group in vRealize Automation.

        .EXAMPLE
        New-vRAGroup -groupId $groupId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -orgRole $orgRole-serviceRole $serviceRole
        This example adds a group in vRealize Automation by groupId and orgId and assisgnes both the required orgRole and serviceRole.

        .EXAMPLE
        New-vRAGroup -groupId $orgId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -orgRole $orgRole -serviceRole $serviceRole
        This example adds a group in vRealize Automation by groupId and orgId and assisgnes the required orgRole only.

        Note: This cmdlet currently only supports a single serviceRole.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole,
        [Parameter (ParameterSetName = "serviceRole", Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId,
        [Parameter (ParameterSetName = "serviceRole", Mandatory = $false)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
        )

    Try {
        if ($PsBoundParameters.ContainsKey("serviceRole") -and $PsBoundParameters.ContainsKey("serviceDefinitionId")) {
            $body = '{
                    "ids":[
                        "'
 + $groupId +'"
                        ],
                    "organizationRoleNames":[
                        "'
 + $orgRole +'"
                        ],
                    "serviceRoles":[
                        {
                            "serviceDefinitionId":"'
 + $serviceDefinitionId + '",
                            "serviceRoleNames":[
                                "'
 + $serviceRole + '"
                            ]
                        }
                        ]
                    }'

            $uri = "https://$vraAppliance/csp/gateway/portal/api/orgs/$orgId/groups"
            $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $body
        }
        elseif ($PsBoundParameters.ContainsKey("serviceRole") -or $PsBoundParameters.ContainsKey("serviceDefinitionId")) {
            Write-Error "Only one of serviceRole and serviceDefinitionId provided."
        }  
        else {
            $body = '{
                    "ids":[
                        "'
 + $groupId +'"
                        ],
                    "organizationRoleNames":[
                        "'
 + $orgRole +'"
                        ]
                    }'

            $uri = "https://$vraAppliance/csp/gateway/portal/api/orgs/$orgId/groups"
            $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $body
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function New-vRAGroup

Function Get-vRAUserRoles {
    <#
        .SYNOPSIS
        Get the user roles.

        .DESCRIPTION
        The Get-vRAUser Roles cmdlet returns a user's roles in vRealize Automation.

        .EXAMPLE
        Get-vRAUserRoles -userId $userId -orgId $orgId
        This example returns a user's roles from vRealize Automation by userId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId
    )

    Try {
        $uri = "https://$vraAppliance/csp/gateway/am/api/users/$userid/orgs/$orgId/access"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Get-vRAUserRoles

Function Get-vRAGroupRoles {
    <#
        .SYNOPSIS
        Get the group roles.

        .DESCRIPTION
        The Get-vRAGroupRoles cmdlet returns a group's roles in vRealize Automation.

        .EXAMPLE
        Get-vRAGroupRoles -groupId $groupId -orgId $orgId
        This example returns a group's roles from vRealize Automation by groupId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId
    )

    Try {
        $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vraHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Get-vRAGroupRoles

Function Remove-vRAGroupRoles {
    <#
        .SYNOPSIS
        Remove the group roles.

        .DESCRIPTION
        The Remove-vRAGroupRoles cmdlet removes a group's roles in vRealize Automation.

        .EXAMPLE
        Remove-vRAGroupRoles -groupId $groupId -orgId $orgId
        This example removes a group's roles from vRealize Automation by groupId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId
    )

    Try {
        $body = '{
                    "ids": [
                        "'
 + $groupId + '"
                    ]
                }'

        $uri = "https://$vraAppliance/csp/gateway/portal/api/orgs/$orgId/groups"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Remove-vRAGroupRoles

Function Set-vRAGroupOrgRole {
    <#
        .SYNOPSIS
        Set the group organization role.

        .DESCRIPTION
        The Set-vRAGroupOrgRole cmdlet sets a group's organization roles in vRealize Automation.

        .EXAMPLE
        Set-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_owner
        This example sets the group as an organization owner in vRealize Automation by groupId and orgId.

        .EXAMPLE
        Set-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_member
        This example sets the group as an organization member in vRealize Automation by groupId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole
    )

    Try {
        $body = '{
                    "organizationRoles": {
                        "roleNamesToAdd": [
                            "'
 + $orgRole + '"
                        ],
                        "roleNamesToRemove": []
                    }
                }'

        $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Set-vRAGroupOrgRole

Function Remove-vRAGroupOrgRole {
    <#
        .SYNOPSIS
        Remove the group organization role.

        .DESCRIPTION
        The Remove-vRAGroupOrgRole cmdlet a removes a group's organization role in vRealize Automation.

        .EXAMPLE
        Remove-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_owner
        This example removes the group as an organization owner in vRealize Automation by groupId and orgId.

        .EXAMPLE
        Remove-vRAGroupOrgRole -groupId $groupId -orgId $orgId -orgRole org_member
        This example removes the group as an organization member in vRealize Automation by groupId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole
    )

    Try {
        $body = '{
                    "organizationRoles": {
                        "roleNamesToAdd": [],
                        "roleNamesToRemove": [
                            "'
 + $orgRole + '"
                        ]
                    }
                }'

        $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRAGroupOrgRole

Function Set-vRAGroupServiceRole {
    <#
        .SYNOPSIS
        Set the group service role.

        .DESCRIPTION
        The Set-vRAGroupServiceRole cmdlet adds a group's service role in vRealize Automation.

        .EXAMPLE
        Set-vRAGroupServiceRole -groupId $groupId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole
        This example adds the group to a service role in vRealize Automation by groupId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId,
        [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
    )

    Try {
        $body = '{
                    "serviceRoles": [
                        {
                            "serviceDefinitionId": "'
 + $serviceDefinitionId + '",
                            "roleNamesToAdd": [
                                "'
 + $serviceRole + '"
                            ],
                            "roleNamesToRemove": []
                        }
                    ],
                    "organizationRoles": {
                        "roleNamesToAdd": [],
                        "roleNamesToRemove": []
                    }
                }'

        $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Set-vRAGroupServiceRole

Function Remove-vRAGroupServiceRole {
    <#
        .SYNOPSIS
        Remove the group service role.

        .DESCRIPTION
        The Remove-vRAGroupServiceRole cmdlet removes a group's service role in vRealize Automation.

        .EXAMPLE
        Remove-vRAGroupServiceRole -groupId $groupId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole
        This example removes the group from a service role in vRealize Automation by groupId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId,
        [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
    )

    Try {
        $body = '{
                    "serviceRoles": [
                        {
                            "serviceDefinitionId": "'
 + $serviceDefinitionId + '",
                            "roleNamesToAdd": [],
                            "roleNamesToRemove": [
                                "'
 + $serviceRole + '"
                            ]
                        }
                    ],
                    "organizationRoles": {
                        "roleNamesToAdd": [],
                        "roleNamesToRemove": []
                    }
                }'

        $uri = "https://$vraAppliance/csp/gateway/portal/api/groups/$groupId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Remove-vRAGroupServiceRole

Function Set-vRAUserOrgRole {
    <#
        .SYNOPSIS
        Set the user organization role.

        .DESCRIPTION
        The Set-vRAUserOrgRole cmdlet sets a user's organization role in vRealize Automation.

        .EXAMPLE
        Set-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_owner
        This example sets the user as an organization owner in vRealize Automation by userId and orgId.

        .EXAMPLE
        Set-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_member
        This example sets the user as an organization member in vRealize Automation by userId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole
    )

    Try {
        $body = '{
            "organizationRoles": {
                "roleNamesToAdd": [
                "'
 + $orgRole + '"
                ],
                "roleNamesToRemove": []
            }
        }'

        $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Set-vRAUserOrgRole

Function Remove-vRAUserOrgRole {
    <#
        .SYNOPSIS
        Remove the user organization role.

        .DESCRIPTION
        The Remove-vRAUserOrgRole cmdlet a user's organization role in vRealize Automation.

        .EXAMPLE
        Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_owner
        This example removes the user as an organization owner in vRealize Automation by userId and orgId.

        .EXAMPLE
        Remove-vRAUserOrgRole -userId $userId -orgId $orgId -orgRole org_member
        This example removes the user as an organization member in vRealize Automation by userId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateSet("org_owner","org_member")] [ValidateNotNullOrEmpty()] [String]$orgRole
    )

    Try {
        $body = '{
            "organizationRoles": {
                "roleNamesToAdd": [],
                "roleNamesToRemove": [
                "'
 + $orgRole + '"
                ]
            }
        }'

        $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Remove-vRAUserOrgRole

Function Set-vRAUserServiceRole {
    <#
        .SYNOPSIS
        Set the user service role.

        .DESCRIPTION
        The Set-vRAUserServiceRole cmdlet adds a user's service role in vRealize Automation.

        .EXAMPLE
        Set-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole
        This example adds the user to a service role in vRealize Automation by userId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId,
        [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
    )

    Try {
        $body = '{
                    "serviceRoles": [
                        {
                        "serviceDefinitionId": "'
 + $serviceDefinitionId + '",
                        "roleNamesToAdd": [
                            "'
 + $serviceRole + '"
                        ],
                        "roleNamesToRemove": []
                        }
                    ]
                }'

        $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Set-vRAUserServiceRole

Function Remove-vRAUserServiceRole {
    <#
        .SYNOPSIS
        Remove the user service role.

        .DESCRIPTION
        The Remove-vRAUserServiceRole cmdlet removes a user's service role in vRealize Automation.

        .EXAMPLE
        Remove-vRAUserServiceRole -userId $userId -orgId $orgId -serviceDefinitionId $serviceDefinitionId -serviceRole $serviceRole
        This example removes the user from a service role in vRealize Automation by userId and orgId.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$orgId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceDefinitionId,
        [Parameter (Mandatory = $true)] [ValidateSet('automationservice:cloud_admin','automationservice:user','automationservice:viewer','catalog:admin','catalog:user','catalog:viewer','CodeStream:administrator','CodeStream:developer','CodeStream:executor','CodeStream:user','CodeStream:viewer','migration:admin','migration:viewer','orchestration:admin','orchestration:designer','orchestration:viewer','saltstack:admin')] [ValidateNotNullOrEmpty()] [String]$serviceRole
    )

    Try {
        $body = '{
                    "serviceRoles": [
                        {
                        "serviceDefinitionId": "'
 + $serviceDefinitionId + '",
                        "roleNamesToAdd": [],
                        "roleNamesToRemove": [
                            "'
 + $serviceRole + '"
                        ]
                        }
                    ]
                }'

        $uri = "https://$vraAppliance/csp/gateway/am/api/v3/users/$userId/orgs/$orgId/roles"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vraHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Remove-vRAUserServiceRole

Function Add-vRAIntegrationItem {
    <#
        .SYNOPSIS
        Add external systems to vRealize Automation

        .DESCRIPTION
        The Add-vRAIntegrationItem cmdlet adds external systems to vRealize Automation

        .EXAMPLE
        Add-vRAIntegrationItem -integrationType "vrops" -integrationName "vRealize Operations Manager" -integrationUser "svc-vra-vrops@sfo.rainpole.io@vIDMAuthSource" -integrationPassword "VMw@re1!"
        This example creates vRealize Operations Manager integration with name "vRealize Operations Manager" in vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vrops")] [ValidateNotNullOrEmpty()] [String]$integrationType,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$integrationName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$integrationUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$integrationPassword
    )
    
    Try {
        $json = Test-vRAIntegrationItem -integrationType $integrationType -integrationName $integrationName -integrationUser $integrationUser -integrationPassword $integrationPassword 
        $vraapiVersion = "apiVersion=" + (Get-vRAAPIVersion)
        $uri = "https://$vraAppliance/iaas/api/integrations?$vraapiVersion"
        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $json
        Start-Sleep 5
        $id = $response.selfLink
        $uri = "https://$vraAppliance$id"
        (Invoke-RestMethod -Method Get -Uri $uri -Headers $vraHeaders)
    } Catch {
        Write-Error $_.Exception.Message
    }

}
Export-ModuleMember -Function Add-vRAIntegrationItem

Function Test-vRAIntegrationItem {
    <#
        .SYNOPSIS
        Test an Integration Item in vRealize Automation

        .DESCRIPTION
        The Test-vRAIntegrationItem cmdlet validates the given credential and certificate of an intergarion item

        .EXAMPLE
        Test-vRAIntegrationItem -integrationType "vrops" -integrationName "vRealize Operations Manager" -integrationUser "svc-vra-vrops@sfo.rainpole.io@vIDMAuthSource" -integrationPassword "VMw@re1!"
        This example validates vRealize Operations Manager integration in vRealize Automation
    #>

    
    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vrops")] [ValidateNotNullOrEmpty()] [String]$integrationType,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$integrationName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$integrationUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$integrationPassword
    )
    
    if ($PsBoundParameters.ContainsKey("integrationType")) {
        if ($integrationType -eq "vrops") { $vropsuri = "https://$vropsAppliance/suite-api" } 
        $jsonObj = [PSCustomObject]@{
            integrationType       = $integrationType
            name                  = $integrationName
            privateKeyId          = $integrationUser
            privateKey            = $integrationPassword
            integrationProperties = @{hostName = $vropsuri }
        }
        $json = $jsonObj | ConvertTo-Json -Depth 2
        Try { 
            $vraapiVersion = "apiVersion=" + (Get-vRAAPIVersion)
            $uri = "https://$vraAppliance/iaas/api/integrations?validateOnly&$vraapiVersion"        
            $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vraHeaders -Body $json
            Start-Sleep 5
            $id = $response.selfLink
            $uri = "https://$vraAppliance$id"   
            $response = Invoke-RestMethod -Method Get -Uri $uri -Headers $vraHeaders
            if (($response.status -eq "FAILED") -and ($response.message -eq "unable to find valid certification")) {        
                $certid = $response.resources 
                $uri = "https://$vraAppliance$certid" + "?$vraapiVersion" 
                $response = Invoke-RestMethod -Method Get -Uri $uri -Headers $vraHeaders
                $certificatevalue = $response.certificate 
                Write-Host (($response.certificateErrorDetail) + ($response.properties | Out-String ))
                $certinput = Read-Host "Do you want to accept the above certificate (yes/no)"
                if (($certinput -eq "yes") -or ($certinput -eq "y")) {
                    $jsonObj.integrationProperties += @{certificate = $certificatevalue }
                    $json = $jsonObj | ConvertTo-Json -Depth 2 
                    return  $json    
                } else {
                    Write-Output "Exiting..." 
                    Break 
                }               
            } elseif ($response.status -eq "FINISHED") { 
                Write-Host "Certificate is already present in the system..."  
                $json = $jsonObj | ConvertTo-Json -Depth 2 
                return  $json     
            } else {
                Write-Error "Error "$response.message
                Break        
            }
        } Catch {
            Write-Error $_.Exception.Message
            Break  
        }
    }
}
Export-ModuleMember -Function Test-vRAIntegrationItem

Function Remove-vRAIntegrationItem {
    <#
        .SYNOPSIS
        Remove an Integration Item from vRealize Automation

        .DESCRIPTION
        The Remove-vRAIntegrationItem cmdlet removes the given Integration Item from vRealize Automation

        .EXAMPLE
        Remove-vRAIntegrationItem -integrationType vrops -integrationId "instacenID"
        This example removes vRealize Operations Manager integration from vRealize Automation
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vrops")] [ValidateNotNullOrEmpty()] [String]$integrationType,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$integrationId
    )
    
    Try {
        $vraapiVersion = "apiVersion=" + (Get-vRAAPIVersion)
        $uri = "https://$vraAppliance/iaas/api/integrations/$integrationId" + "?$vraapiVersion"     
        $response = Invoke-RestMethod -Method Delete -Uri $uri -Headers $vraHeaders
        Start-Sleep 5
        $id = $response.selfLink
        $uri = "https://$vraAppliance$id"
        $response = Invoke-RestMethod -Method Get -Uri $uri -Headers $vraHeaders
        if ( $response.status -eq "FAILED") {
            Write-Host "Error "$response.message
            Break        
        }
        if ( $response.status -eq "FINISHED") {
            $response.message
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRAIntegrationItem

#EndRegion End vRealize Automation Functions ######
#####################################################################

#####################################################################
#Region Start vRealize Orchestrator (Embedded) Functions ######

Function Invoke-vRORestMethod {
    <#
        .SYNOPSIS
        A wrapper for Invoke-RestMethod for use with vRealize Orchestrator

        .DESCRIPTION
        The Invoke-RestMethod cmdlet is a wrapper for Invoke-RestMethod use with vRealize Orchestrator
        
        .EXAMPLE
        Invoke-vRORestMethod -Method 'GET' -Uri '/vco/api/workflows'
        
        .EXAMPLE

        $method = "POST"
        $uri = "/vco/api/workflows/$($ID)/executions/"
        $body = @"
        {"parameters":
            [
                {
                    "value": {"string":{ "value": "bar"}},
                    "type": "string",
                    "name": "foo",
                    "scope": "local"
                },
                {
                    "value": {"number":{ "value": 2022}},
                    "type": "number",
                    "name": "bar",
                    "scope": "local"
                }
            ]
        }
        "@
        Invoke-vRORestMethod -method $method -uri $uri -body $body -webRequest

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding()][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("GET", "POST", "PUT", "DELETE")] [String]$method,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$uri,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] $body,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$outFile,
        [Parameter (Mandatory = $false)] [Switch]$webRequest
    )

    $fullUri = "https://$vraAppliance$uri"

    $Params = @{
        method  = $method
        headers = $vraHeaders
        uri     = $fullUri
    }

    if ($PSBoundParameters.ContainsKey("body")) {
        $Params.Add("body", $body)
        Write-Debug -message $body
    }
    elseif ($PSBoundParameters.ContainsKey("outFile")) {
        $Params.Add("outFile", $outFile)
    }

    Try {
        if ($PSEdition -eq 'Core') {
            if ($PSBoundParameters.ContainsKey("webRequest")) {
                Invoke-WebRequest @Params -SkipCertificateCheck -UseBasicParsing
            }
            else {
                Invoke-RestMethod @Params -SkipCertificateCheck -UseBasicParsing
            }
        }
        else {
            if ($PSBoundParameters.ContainsKey("webRequest")) {
                Invoke-WebRequest @Params -UseBasicParsing
            }
            else {
                Invoke-RestMethod @Params -UseBasicParsing
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Invoke-vRORestMethod

function Get-vROVersion {
    <#
        .SYNOPSIS
        Retrieve the vRealize Orchestrator version information
        
        .DESCRIPTION
        The Get-vROVersion cmdlest retrieves the vRealize Orchestrator version information

        .EXAMPLE
        Get-vROVersion

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding()][OutputType('System.Management.Automation.PSObject')]
    
    Param ()              
    Try {
        $uri = "/vco/api/about"
        $response = Invoke-vRORestMethod -method 'GET' -uri $uri
        $version = $response.version
        [pscustomobject] @{
            Version = $version
            BuildNumber = $response."build-number"
            BuildDate = $response."build-date"
            APIVersion = $response."api-version"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROVersion

function Get-vROWorkflow {
    <#
        .SYNOPSIS
        Get vRealize Orchestrator workflows

        .DESCRIPTION
        The Get-vROWorkflow cmdlet returns details for vRealize Orchestrator workflows

        .EXAMPLE
        Get-vROWorkflow

        .EXAMPLE
        Get-vROWorkflow -categoryName foo

        .EXAMPLE
        Get-vROWorkflow -categoryId 3f23f186158a4869b464b7271fc216ba

        .EXAMPLE
        Get-vROWorkflow -id '3f23f186-158a-4869-b464-b7271fc216ba'

        .EXAMPLE
        Get-vROWorkflow -name 'foo'

        .EXAMPLE
        Get-vROWorkflow -name 'Add' -wildcard

        .EXAMPLE
        Get-vROWorkflow -tag 'foo'

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding(DefaultParametersetName = "All")][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $false, ParameterSetName = "categoryName")] [Alias("Category")] [String]$categoryName,
        [Parameter (Mandatory = $false, ParameterSetName = "categoryId")] [String]$categoryId,
        [Parameter (Mandatory = $false, ParameterSetName = "id")] [String]$id,
        [Parameter (Mandatory = $false, ParameterSetName = "name")] [String]$name,
        [Parameter (Mandatory = $false, ParameterSetName = "name")] [Switch]$wildcard,
        [Parameter (Mandatory = $false, ParameterSetName = "all")]
        [Parameter (Mandatory = $false, ParameterSetName = "categoryName")]
        [Parameter (Mandatory = $false, ParameterSetName = "category")] [String[]]$tag
    )

    Try {
        Switch ($PsCmdlet.ParameterSetName) {
            "all" {
                $uri = "/vco/api/workflows"
                break
            }
            "categoryName" {
                $uri = "/vco/api/workflows/?conditions=categoryName=$($categoryName)"
                break
            }
            "categoryId" {
                $uri = "/vco/api/catalog/System/WorkflowCategory/$($categoryId)/workflows"
                break
            }
            "id" {
                $uri = "/vco/api/workflows/$($id)"
                break
            }
            "name" {
                if ($PSBoundParameters.ContainsKey('wildcard')) {
                    $uri = "/vco/api/workflows/?conditions=name~$($name)"
                }
                else {
                    $uri = "/vco/api/workflows/?conditions=name=$($name)"
                }
                break
            }
        }
        # Filter by tag, if needed
        if ($PSBoundParameters.ContainsKey('tag')) {
            $uri += if ($PSCmdlet.ParameterSetName -eq 'all') { '?' } else { '&' }
            $newParams = @()
            foreach ($tagAttr in $tag) {
                $newParams += "tags=$($tagAttr)"
            }
            $uri += $newParams -join '&'
        }
        Switch ($PsCmdlet.ParameterSetName) {
            "id" {
                $workflow = Invoke-vRORestMethod -method 'GET' -uri $uri -Verbose:$VerbosePreference
                [pscustomobject]@{
                    Name         = $workflow.name
                    ID           = $workflow.id
                    Description  = $workflow.description
                    ItemHref     = $workflow.href
                    Version      = $workflow.version
                    CategoryName = $null
                    CategoryHref = $null
                    CustomIcon   = $workflow.'customized-icon'
                    CanExecute   = $null
                    CanEdit      = $null
                }
            }
            "categoryId" {
                $workflows = Invoke-vRORestMethod -method 'GET' -uri $uri -Verbose:$VerbosePreference
                foreach ($workflow in $workflows.link) {
                    $returnObject = @{
                        Name         = ($workflow.attributes | Where-Object { $_.name -eq 'name' }).value
                        ID           = ($workflow.attributes | Where-Object { $_.name -eq 'id' }).value
                        Description  = ($workflow.attributes | Where-Object { $_.name -eq 'description' }).value
                        ItemHref     = $workflow.href
                        Version      = ($workflow.attributes | Where-Object { $_.name -eq 'version' }).value
                        CategoryName = ($workflow.attributes | Where-Object { $_.name -eq 'categoryName' }).value
                        CategoryHref = ($workflow.attributes | Where-Object { $_.name -eq 'categoryHref' }).value
                        CustomIcon   = ($workflow.attributes | Where-Object { $_.name -eq 'customIcon' }).value
                        CanExecute   = ($workflow.attributes | Where-Object { $_.name -eq 'canExecute' }).value
                        CanEdit      = ($workflow.attributes | Where-Object { $_.name -eq 'canEdit' }).value
                    }
                    # Add tags if needed
                    $tags = $workflow.attributes | Where-Object { $_.name -eq 'globalTags' } | Select-Object -ExpandProperty 'value'
                    if ($tags) {
                        $tagsArray = ($tags -replace ':__SYSTEM_TAG__|.$', '').Split(' ')
                        $returnObject.Add('tags', $tagsArray)
                    }
                    [PSCustomObject]$returnObject
                }
            }
            Default {
                $workflows = Invoke-vRORestMethod -method 'GET' -uri $uri -verbose:$VerbosePreference
                Foreach ($workflow in $workflows.link) {
                    $returnObject = @{
                        Name         = ($workflow.attributes | Where-Object { $_.name -eq 'name' }).value
                        ID           = ($workflow.attributes | Where-Object { $_.name -eq 'id' }).value
                        Description  = ($workflow.attributes | Where-Object { $_.name -eq 'description' }).value
                        ItemHref     = ($workflow.attributes | Where-Object { $_.name -eq 'itemHref' }).value
                        Version      = ($workflow.attributes | Where-Object { $_.name -eq 'version' }).value
                        CategoryName = ($workflow.attributes | Where-Object { $_.name -eq 'categoryName' }).value
                        CategoryHref = ($workflow.attributes | Where-Object { $_.name -eq 'categoryHref' }).value
                        CustomIcon   = ($workflow.attributes | Where-Object { $_.name -eq 'customIcon' }).value
                        CanExecute   = ($workflow.attributes | Where-Object { $_.name -eq 'canExecute' }).value
                        CanEdit      = ($workflow.attributes | Where-Object { $_.name -eq 'canEdit' }).value
                    }
                    # Add tags, if needed
                    $tags = $workflow.attributes | Where-Object { $_.name -eq 'globalTags' } | Select-Object -ExpandProperty 'value'
                    if ($tags) {
                        $tagsArray = ($tags -replace ':__SYSTEM_TAG__|.$', '').Split(' ')
                        $returnObject.Add('tags', $tagsArray)
                    }
                    [PSCustomObject]$returnObject
                }
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROWorkflow

function Invoke-vROWorkflow {
    <#
        .SYNOPSIS
        Invoke a vRealize Orchestrator workflow

        .DESCRIPTION
        The Invoke-vROWorkflow cmdlet starts a vRealize Orchestrator workflow

        .EXAMPLE
        Invoke-vROWorkflow -ID 3f23f186-158a-4869-b464-b7271fc216ba

        .EXAMPLE
        Invoke-vROWorkflow -ID 3f23f186-158a-4869-b464-b7271fc216ba -parameterName 'text' -parameterValue 'foo' -parameterType 'string'

        .EXAMPLE
        $Parameters = @"
        {"parameters":
            [
                {
                    "value": {"string":{ "value": "bar"}},
                    "type": "string",
                    "name": "foo",
                    "scope": "local"
                },
                {
                    "value": {"number":{ "value": 2022}},
                    "type": "number",
                    "name": "year",
                    "scope": "local"
                }
            ]
        }
        "@

        Invoke-vROWorkflow -id 3f23f186-158a-4869-b464-b7271fc216ba -parameters ($parameters | ConvertFrom-Json).parameters

        .EXAMPLE
        $param1 = New-vROParameterDefinition -name 'foo' -value 'bar' -type string -scope LOCAL
        Invoke-vROWorkflow -id 3f23f186-158a-4869-b464-b7271fc216ba -parameters $param1

        .EXAMPLE
        Get-vROWorkflow -name 'foo' | Invoke-vROWorkflow -parameterName 'foo' -parameterValue 'bar' -parameterType string

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding(DefaultParametersetName = "A")][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $true, ValueFromPipelinebyPropertyName = $true, ParameterSetName = "A")]
        [Parameter (Mandatory = $true, ParameterSetName = "B")] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [ValidateNotNullOrEmpty()] [String]$parameterName,
        [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [String]$parameterValue,
        [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [ValidateNotNullOrEmpty()] [String]$parameterType,
        [Parameter (Mandatory = $false, ParameterSetName = "B")] [Parameter (ParameterSetName = "D")] [ValidateNotNullOrEmpty()] [PSCustomObject[]]$parameters
    )

    Begin {}
    Process {
        Try {
            if ($PSBoundParameters.ContainsKey('parameterType')) {
                $parameterType = $parameterType.ToLower()
                $body = @"
{"parameters":
    [
        {
            "value": {"$($parameterType)":{ "value": "$($parameterValue)"}},
            "type": "$($parameterType)",
            "name": "$($parameterName)",
            "scope": "local"
        }
    ]
}
"@

            }
            elseif ($PSBoundParameters.ContainsKey('parameters')) {
                $object = [PSCustomObject]@{
                    parameters = @()
                }
                foreach ($parameter in $parameters) {
                    $object.parameters += $parameter
                }
                $body = $object | ConvertTo-Json -Depth 100
            }
            else {
                $body = @"
{"parameters":
[
]
}
"@

            }
            $uri = "/vco/api/workflows/$($id)/executions/"
            $response = Invoke-vRORestMethod -method 'POST' -uri $uri -body $body -webRequest -verbose:$VerbosePreference

            if ($PSEdition -eq 'Core') {
                [pscustomobject]@{
                    StatusCode        = $response.StatusCode
                    StatusDescription = $response.StatusDescription
                    Execution         = ([System.Uri]$response.Headers.Location[0]).LocalPath
                }
            }
            else {
                [pscustomobject]@{
                    StatusCode        = $response.StatusCode
                    StatusDescription = $response.StatusDescription
                    Execution         = ([System.Uri]$response.Headers.Location).LocalPath
                }
            }
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }
}
Export-ModuleMember -Function Invoke-vROWorkflow

function New-vROParameterDefinition {
    <#
        .SYNOPSIS
        Create a parameter definition for use with a vRealize Orchestrator workflow
        
        .DESCRIPTION
        The New-vROParameterDefinition cmdlet create a parameter definition for use with a vRealize Orchestrator workflow

        .EXAMPLE
        $param1 = New-vROParameterDefinition -name 'foo' -value 'bar' -type string -scope LOCAL

        Invoke-vROWorkflow -id 697c8755-15c0-44fc-b409-5c562cf2984e -parameters $param1

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "Low")][OutputType('System.Management.Automation.PSObject')]

    Param (
    [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
    [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$value,
    [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$type,   
    [Parameter (Mandatory = $false)] [ValidateSet("LOCAL", "TOKEN")] [String]$scope = "LOCAL"
    )  

    Begin {} 
    Process {
        Try {
            if ($PSCmdlet.ShouldProcess("WorkflowParameterDefinition")){
                $parameterDefinition = @"
{
    "name": "$($name)",
    "type": "$($type.ToLower())",
    "scope": "$($scope.ToLower())",
    "value": {
        "$($type.ToLower())":{ "value": "$($value)"}
    }
}
"@

                $parameterDefinition | ConvertFrom-Json
            }
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }
    End {    
    }
}
Export-ModuleMember -Function New-vROParameterDefinition

function Get-vROWorkflowExecution {
    <#
        .SYNOPSIS
        Get vRealize orchestrator Wwrkflow executions

        .DESCRIPTION
        The Get-vROWorkflowExecution cmdlet returns the execution runs for a vRealize Orchestrator workflow

        .EXAMPLE
        Get-vROWorkflowExecution -id 697c8755-15c0-44fc-b409-5c562cf2984e

        .EXAMPLE
        Get-vROWorkflowExecution -name 'foo'

        .EXAMPLE
        Get-vROWorkflow -name 'foo' | Get-vROWorkflowExecution

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding(DefaultParametersetName = "Name")][OutputType('System.Management.Automation.PSObject')]

    Param (   
        [Parameter (Mandatory = $true, ValueFromPipelinebyPropertyName = $true, ParameterSetName = "id")] [String]$id,
        [Parameter (Mandatory = $true, ParameterSetName = "name")] [String]$name
    )    

    Begin {}
    Process {
        Try {
            if ($PSCmdlet.ParameterSetName -eq "name") {
                $id = (Get-vROWorkflow -name $name).id
            }
            $uri = "/vco/api/workflows/$($id)/executions"
            $response = Invoke-vRORestMethod -method 'GET' -uri $uri -verbose:$VerbosePreference
            $data = $response.relations.link | Where-Object { $_.attributes }
            Foreach ($execution in $data) {
                [PSCustomObject]@{                                
                    Name      = ($execution.attributes | Where-Object { $_.name -eq 'name' }).value
                    ID        = ($execution.attributes | Where-Object { $_.name -eq 'id' }).value
                    Execution = "$uri/$(($execution.attributes | Where-Object {$_.name -eq 'id'}).value)/"
                    State     = ($execution.attributes | Where-Object { $_.name -eq 'state' }).value
                    StartedBy = ($execution.attributes | Where-Object { $_.name -eq 'startedBy' }).value
                    StartDate = ($execution.attributes | Where-Object { $_.name -eq 'StartDate' }).value
                    EndDate   = ($execution.attributes | Where-Object { $_.name -eq 'EndDate' }).value
                }
            }
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }
    End {
    }
}
Export-ModuleMember -Function Get-vROWorkflowExecution

function Get-vROWorkflowExecutionState {
    <#
        .SYNOPSIS
        Get vRealize Orchestrator workflow execution state

        .DESCRIPTION
        The Get-vROWorkflowExecutionState cmdlet returns the status of vRealize Orchestrator workflow execution runs

        .EXAMPLE
        Get-vROWorkflowExecutionState -executionStateRef '/vco/api/workflows/697c8755-15c0-44fc-b409-5c562cf2984e/executions/cda43353730b4f8ba1815979ef8a932a'

        .EXAMPLE
        Get-vROWorkflowExecution -id 697c8755-15c0-44fc-b409-5c562cf2984e | Select-Object -last 1 | Get-vROWorkflowExecutionState

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding()][OutputType('System.Management.Automation.PSObject')]

    Param (   
        [Parameter (Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)] [Alias("execution")] [ValidateNotNullOrEmpty()][String]$executionStateRef
    )

    Begin {}
    Process {
        Try {
            Foreach ($reference in $executionStateRef) {        
                $uri = $reference + "state"
                $response = Invoke-vRORestMethod -method 'GET' -uri $uri -webRequest -verbose:$VerbosePreference
                [pscustomobject]@{                                             
                    ExecutionStateRef = $reference         
                    StatusCode        = $response.StatusCode
                    StatusDescription = $response.StatusDescription
                    Execution         = ($response.Content | ConvertFrom-Json).Value
                }
            }
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }
    End {
    }
}
Export-ModuleMember -Function Get-vROWorkflowExecutionState

function Get-vROWorkflowExecutionResult {
    <#
        .SYNOPSIS
        Get vRealize Orchestrator workflow execution result

        .DESCRIPTION
        The Get-vROWorkflowExecutionResult cmdlet returns the results of vRealize Orchestrator workflow execution runs

        .EXAMPLE
        Get-vROWorkflowExecutionResult -executionRef '/vco/api/workflows/697c8755-15c0-44fc-b409-5c562cf2984e/executions/cda43353730b4f8ba1815979ef8a932a'

        .EXAMPLE
        Get-vROWorkflow -name 'foo' | Get-vROWorkflowExecution | Select-Object -last 1 | Get-vROWorkflowExecutionResult

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding()][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)] [Alias("execution")] [ValidateNotNullOrEmpty()] [String]$executionRef 
    )

    Begin {}
    Process {  
        Try {
            Foreach ($reference in $executionRef) {   
                $response = Invoke-vRORestMethod -method 'GET' -uri $reference -webRequest -verbose:$VerbosePreference
                $json = $response.Content | ConvertFrom-Json
                Foreach ($outputParameter in $json.'output-parameters') {
                    $type = $outputParameter.type
                    [pscustomobject]@{                                 
                        ExecutionRef = $reference      
                        Name         = $outputParameter.name
                        Scope        = $outputParameter.scope
                        Type         = $outputParameter.type
                        Value        = $outputParameter.value.$type.value
                    }
                } 
            }
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }
    End {
    }
}
Export-ModuleMember -Function Get-vROWorkflowExecutionResult

#EndRegion End vRealize Orchestrator (Embedded) Functions ######
#####################################################################

#####################################################################
#Region Start vRealize Operations Manager Functions ######

Function Request-vROPSToken {
    <#
        .SYNOPSIS
        Connects to the specified vRealize Operations Manager and obtains authorization token

        .DESCRIPTION
        The Request-vROPSToken cmdlet connects to the specified vRealize Operations Manager and obtains an authorization token.
        It is required once per session before running all other cmdlets.

        .EXAMPLE
        Request-vROPSToken -fqdn xint-vrops01.rainpole.io -username admin -password VMw@re1!
        This example shows how to connect to the vRealize Operations Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) {
        $creds = Get-Credential # Request Credentials
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }

    Try {
        $Global:vropsAppliance = $fqdn
        $Global:vropsHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $vropsHeaders.Add("Accept", "application/json")
        $vropsHeaders.Add("Content-Type", "application/json")
        $uri = "https://$vropsAppliance/suite-api/api/auth/token/acquire"

        $body = "{
        `n `"username`" : `"$username`",
        `n `"authSource`" : `"LOCAL`",
        `n `"password`" : `"$password`"
        `n}"

        
        if ($PSEdition -eq 'Core') {
            $vropsResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vropsHeaders -Body $body -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        }
        else {
            $vropsResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vropsHeaders -Body $body
        }

        if ($vropsResponse.token) {
            $vropsHeaders.Add("Authorization", "vRealizeOpsToken " + $vropsResponse.token)
            Write-Output "Successfully connected to vRealize Operations Manager: $vropsAppliance"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-vROPSToken

Function Get-vROPSVersion {
    <#
        .SYNOPSIS
        Get version informartion

        .DESCRIPTION
        The Get-vROPSVersion cmdlet gets version information for vRealize Operations Manager

        .EXAMPLE
        Get-vROPSVersion
        This example gets the current version of the service

        .EXAMPLE
        Get-vROPSVersion -all
        This example gets a list of all versions supported by the service
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$all
    )

    Try {
        if ($PsBoundParameters.ContainsKey("all")) {
            $uri = "https://$vropsAppliance/suite-api/api/versions"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.values
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/versions/current"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSVersion

Function Get-vROPSCollector {
    <#
        .SYNOPSIS
        Get list of collectors

        .DESCRIPTION
        The Get-vROPSCollector cmdlet gets a list of collectors in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSCollector
        This example gets a list of collectors

        .EXAMPLE
        Get-vROPSCollector -id <id>
        This example gets details of a collector by its ID
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vropsAppliance/suite-api/api/collectors/$id/adapters"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.adapterInstancesInfoDto
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/collectors"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.collector
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSCollector

Function Get-vROPSCollectorGroup {
    <#
        .SYNOPSIS
        Get list of collector groups

        .DESCRIPTION
        The Get-vROPSCollectorGroup cmdlet gets a list of collector groups in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSCollectorGroup
        This example gets a list of collector groups

        .EXAMPLE
        Get-vROPSCollectorGroup -id <id>
        This example gets details of a collector by its ID
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vropsAppliance/suite-api/api/collectorgroups/$id"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/collectorgroups"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.collectorGroups
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSCollectorGroup

Function Add-vROPSCollectorGroup {
    <#
        .SYNOPSIS
        Add a collector groups

        .DESCRIPTION
        The Add-vROPSCollectorGroup cmdlet adds a new collector groups in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSCollectorGroup -name sfo-remote-collectors -description "Remote Collector Group for SFO" -collectorIds "1,2"
        This example gets a list of collector groups
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$description,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$collectorIds
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/collectorgroups"
        if ($description) {
            $body = '{ "name" : "'+ $name +'", "description" : "'+ $description +'", "collectorId" : ['+ $collectorIds +'], "systemDefined" : false }'
        }
        else {
            $body = '{ "name" : "'+ $name +'", "collectorId" : ['+ $collectorIds +'], "systemDefined" : false }'
        }
        $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body

    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vROPSCollectorGroup

Function Remove-vROPSCollectorGroup {
    <#
        .SYNOPSIS
        Delete a collector group

        .DESCRIPTION
        The Remove-vROPSCollectorGroup cmdlet deletes a collector group in vRealize Operations Manager

        .EXAMPLE
        Remove-vROPSCollectorGroup -id
        This example deletes a gollector group
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/collectorgroups/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vropsHeaders
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vROPSCollectorGroup

Function Get-vROPSAdapter {
    <#
        .SYNOPSIS
        Get list of adapters

        .DESCRIPTION
        The Get-vROPSAdapter cmdlet gets a list of adapters in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSAdapter
        This example gets a list of all adapters

        .EXAMPLE
        Get-vROPSAdapter -id <id>
        This example gets details of an adapter by its ID
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vropsAppliance/suite-api/api/adapters/$id"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/adapters"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.adapterInstancesInfoDto
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSAdapter

Function Set-vROPSAdapter {
    <#
        .SYNOPSIS
        Update an adapter

        .DESCRIPTION
        The Set-vROPSAdapter cmdlet updates the adapters configuration in vRealize Operations Manager

        .EXAMPLE
        Set-vROPSAdapter -json .\adapterJson
        This example updates the details of an adapter
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$patch
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json")) {
            if (!(Test-Path $json)) {
                Throw "JSON File Not Found"
            }
            else {
                $body = (Get-Content $json) # Read the json file contents into the $body variable
            }
        }

        if ($PsBoundParameters.ContainsKey("patch")) {
            $uri = "https://$vropsAppliance/suite-api/api/adapters"
            Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vropsHeaders -Body $body
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/adapters"
            $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $vropsHeaders -Body $body
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vROPSAdapter

Function Add-vROPSAdapter {
    <#
        .SYNOPSIS
        Add an adapter

        .DESCRIPTION
        The Add-vROPSAdapter cmdlet adds an adapter to vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAdapter -json .\adapterJson
        This example adds an adapter useing the json specification file
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json")) {
            if (!(Test-Path $json)) {
                Throw "JSON File Not Found"
            }
            else {
                $body = (Get-Content $json) # Read the json file contents into the $body variable
            }
        }

        $uri = "https://$vropsAppliance/suite-api/api/adapters"
        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vROPSAdapter

Function Remove-vROPSAdapter {
    <#
        .SYNOPSIS
        Delete an adapters

        .DESCRIPTION
        The Remove-vROPSAdapter cmdlet deletes an adapters from vRealize Operations Manager

        .EXAMPLE
        Remove-vROPSAdapter -id <id>
        This example deletes the adapter based on its ID
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/adapters/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vROPSAdapter

Function Test-vROPSAdapterConnection {
    <#
        .SYNOPSIS
        Test adapter connection

        .DESCRIPTION
        The Test-vROPSAdapterConnection cmdlet tests the connection in vRealize Operations Manager

        .EXAMPLE
        Test-vROPSAdapterConnection -json <json>
        This example tests the connection based on the JSON file provided

        .EXAMPLE
        Test-vROPSAdapterConnection -json <json> -patch
        This example patches the adapter based on the response from the test in JSON format
    #>



    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$patch
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json")) {
            if (!(Test-Path $json)) {
                Throw "JSON File Not Found"
            }
            else {
                $body = (Get-Content $json) # Read the json file contents into the $body variable
            }
        }

        if ($PsBoundParameters.ContainsKey("patch")) {
            $uri = "https://$vropsAppliance/suite-api/api/adapters/testConnection"
            Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vropsHeaders -Body $body
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/adapters/testConnection"
            $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
            $response
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Test-vROPSAdapterConnection

Function Start-vROPSAdapter {
    <#
        .SYNOPSIS
        Starts collection of adapter

        .DESCRIPTION
        The Start-vROPSAdapter cmdlet starts the collection of an adapter in vRealize Operations Manager

        .EXAMPLE
        Start-vROPSAdapter -adpaterId <id>
        This example starts the adpater by id
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterId
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/adapters/$adapterId/monitoringstate/start"
        Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders # API has no response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Start-vROPSAdapter

Function Stop-vROPSAdapter {
    <#
        .SYNOPSIS
        Stops collection of adapter

        .DESCRIPTION
        The Stop-vROPSAdapter cmdlet starts the collection of an adapter in vRealize Operations Manager

        .EXAMPLE
        Stop-vROPSAdapter -adpaterId <id>
        This example starts the adpater by id
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapterId
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/adapters/$adapterId/monitoringstate/stop"
        $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Stop-vROPSAdapter

Function Get-vROPSAdapterKind {
    <#
        .SYNOPSIS
        Get list of adapter kinds

        .DESCRIPTION
        The Get-vROPSAdapterKind cmdlet gets a list of adapter kinds in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSAdapterKind
        This example gets a list of all adapter kinds

        .EXAMPLE
        Get-vROPSAdapterKind -kind VMWARE
        This example gets details of an resource kinds for the VMWARE adapter kind
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateSet("Container","EP Ops Adapter","Http Post","LogInsight","MicrosoftAzureAdapter","AmazonAWSAdapter","NSXTAdapter","PingAdapter","SDDCHealthAdapter","APPLICATIONDISCOVERY","VMWARE","VmcAdapter","IdentityManagerAdapter","APPOSUCP","VOAAdapter","CASAdapter","LogInsightAdapter","NETWORK_INSIGHT","vCenter Operations Adapter","vRealizeOpsMgrAPI","VirtualAndPhysicalSANAdapter")] [ValidateNotNullOrEmpty()] [String]$adapterKind
    )

    Try {
        if ($PsBoundParameters.ContainsKey("adapterKind")) {
            $uri = "https://$vropsAppliance/suite-api/api/adapterkinds/$adapterKind"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.resourceKinds
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/adapterkinds"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.'adapter-kind'
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSAdapterKind

Function Get-vROPSResourceDetail {
    <#
        .SYNOPSIS
        Get resource detail

        .DESCRIPTION
        The Get-vROPSResourceDetail cmdlet gets the details for a resource from vRealize Operations Manager

        .EXAMPLE
        Get-vROPSResourceDetail -adapter VMWARE -resource Datacenter -objectName sfo-m01-dc01
        This example gets the resource details
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adapter,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$resource,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$objectname
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/adapterkinds/$adapter/resourcekinds/$resource/resources?identifiers[VMEntityName]=$objectName"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
        $response.resourceList.resourceKey.resourceIdentifiers
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSResourceDetail

Function Get-vROPSCredential {
    <#
        .SYNOPSIS
        Get credentials

        .DESCRIPTION
        The Get-vROPSCredential cmdlet gets credentials from vRealize Operations Manager

        .EXAMPLE
        Get-vROPSCredential
        This example gets all credentials from vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$credentialId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$adapter,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$resource
    )

    Try {
        if ($PsBoundParameters.ContainsKey("credentialId") -and (-not $PsBoundParameters.ContainsKey("adapter") -and (-not $PsBoundParameters.ContainsKey("resource")))) {
            $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("credentialId") -and ($PsBoundParameters.ContainsKey("adapter"))) {
            $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId/adapters"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.adapterInstancesInfoDto
        }
        elseif ($PsBoundParameters.ContainsKey("credentialId") -and ($PsBoundParameters.ContainsKey("resource"))) {
            $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId/resources"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/credentials"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.credentialInstances
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSCredential

Function Add-vROPSCredential {
    <#
        .SYNOPSIS
        Add a credential

        .DESCRIPTION
        The Add-vROPSCredential cmdlet adds a credential to vRealize Operations Manager

        .EXAMPLE
        Add-vROPSCredential -json .\credentialJson
        This example adds a new credential
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json")) {
            if (!(Test-Path $json)) {
                Throw "JSON File Not Found"
            }
            else {
                $body = (Get-Content $json) # Read the json file contents into the $body variable
            }
        }
        $uri = "https://$vropsAppliance/suite-api/api/credentials"
        $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vROPSCredential

Function Remove-vROPSCredential {
    <#
        .SYNOPSIS
        Delete a credential

        .DESCRIPTION
        The Remove-vROPSCredential cmdlet deletes a credential from vRealize Operations Manager

        .EXAMPLE
        Remove-vROPSCredential -credentialId <id>
        This example deletes a credential
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$credentialId
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/credentials/$credentialId"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vropsHeaders
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vROPSCredential

Function Get-vROPSCurrency {
    <#
        .SYNOPSIS
        Get the currency configuration

        .DESCRIPTION
        The Get-vROPSCurrency cmdlet gets the currency configuration for vRealize Operations Manager

        .EXAMPLE
        Get-vROPSCurrency
        This example gets the currency configuration for vRealize Operations Manager
    #>


    Try {
        $uri = "https://$vropsAppliance/suite-api/api/costconfig/currency"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSCurrency

Function Set-vROPSCurrency {
    <#
        .SYNOPSIS
        Applies the currency configuration

        .DESCRIPTION
        The Set-vROPSCurrency cmdlet applies the currency configuration for vRealize Operations Manager. NOTE: Once
        applied for an instance it cannot be changed.

        .EXAMPLE
        Set-vROPSCurrency
        This example gets the currency configuration for vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$currency
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/costconfig/currency"
        $body = '{
            "code" : "'
+ $currency +'"
        }'

        $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vropsHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vROPSCurrency

Function Get-vROPSSolution {
    <#
        .SYNOPSIS
        Get list of solutions

        .DESCRIPTION
        The Get-vROPSSolution cmdlet gets a list of solutions in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSSolution
        This example gets a list of all solutions

        .EXAMPLE
        Get-vROPSSolution -solutionId "vSphere"
        This example gets a list of all solutions
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$solutionId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$adapterKind,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$license
    )

    Try {
        if ($PsBoundParameters.ContainsKey("solutionId") -and (-not $PsBoundParameters.ContainsKey("adapterKind") -and (-not $PsBoundParameters.ContainsKey("license")))) {
            $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("solutionId") -and ($PsBoundParameters.ContainsKey("adapterKind"))) {
            $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId/adapterkinds"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.'adapter-kind'
        }
        elseif ($PsBoundParameters.ContainsKey("solutionId") -and ($PsBoundParameters.ContainsKey("license"))) {
            $uri = "https://$vropsAppliance/suite-api/api/solutions/$solutionId/licenses"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.solutionLicenses
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/solutions"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.solution
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSSolution

Function Import-vROPSManagementPack {
    <#
        .SYNOPSIS
        Upload a management pack

        .DESCRIPTION
        The Import-vROPSManagementPack cmdlet uploads a management pack into vRealize Operations Manager

        .EXAMPLE
        Import-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pak .\managementPack.pak
        This example uploads the management pack provided to vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pak
    )

    Try {
        if ($PsBoundParameters.ContainsKey("pak")) {
            if (!(Test-Path $pak)) {
                Throw "Management Pack file $pak not found"
            }
        }
        
        $uri = "https://$server/casa/upgrade/cluster/pak/reserved/operation/upload?pak_handling_advice=CLOBBER"
        $contentType = "application/octet-stream"

        Add-Type -AssemblyName System.Net.Http
        $httpClientHandler = New-Object System.Net.Http.HttpClientHandler

        $networkCredential = New-Object System.Net.NetworkCredential @($userName, $password)
        $httpClientHandler.Credentials = $networkCredential
        $httpClient = New-Object System.Net.Http.Httpclient $httpClientHandler

        $packageFileStream = New-Object System.IO.FileStream @($pak, [System.IO.FileMode]::Open)
                
        $fileHeaderValue = New-Object System.Net.Http.Headers.ContentDispositionHeaderValue "form-data"
        $fileHeaderValue.Name = "contents"
        $fileHeaderValue.FileName = (Split-Path $pak -leaf)

        $streamContent = New-Object System.Net.Http.StreamContent $packageFileStream
        $streamContent.Headers.ContentDisposition = $fileHeaderValue
        $streamContent.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue $contentType

        $content = New-Object System.Net.Http.MultipartFormDataContent
        $content.Add($streamContent)

        $response = $httpClient.PostAsync($uri, $content).Result

        if (!$response.IsSuccessStatusCode) {
            $responseBody = $response.Content.ReadAsStringAsync().Result
            $errorMessage = "Status code {0}. Reason {1}. Server reported the following message: {2}." -f $response.StatusCode, $response.ReasonPhrase, $responseBody
            Throw [System.Net.Http.HttpRequestException] $errorMessage
        }
        Return $response.Content.ReadAsStringAsync().Result
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Import-vROPSManagementPack

Function Install-vROPSManagementPack {
    <#
        .SYNOPSIS
        Install a management pack

        .DESCRIPTION
        The Install-vROPSManagementPack cmdlet installs a management pack in vRealize Operations Manager

        .EXAMPLE
        Install-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId SDDCHealth-8115995854
        This example installs the management pack in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pakId
    )

    Try {
        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
        $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo")
        $vropsBasicHeaders.Add("Content-Type", "application/json")

        $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/$pakId/operation/install" -Method 'POST' -Headers $vropsBasicHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Install-vROPSManagementPack

Function Set-vROPSManagementPack {
    <#
        .SYNOPSIS
        Activate / Deactivate a management pack

        .DESCRIPTION
        The Set-vROPSManagementPack cmdlet activates or deactivates a management pack in vRealize Operations Manager

        .EXAMPLE
        Set-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId PingAdapter -version "8.4.0.17863953" -status enable
        This example activates the Ping management pack in vRealize Operations Manager

        Set-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId PingAdapter -version "8.4.0.17863953" -status disable
        This example deactivates the Ping management pack in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pakId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$version,
        [Parameter (Mandatory = $true)] [ValidateSet("enable","disable")] [ValidateNotNullOrEmpty()] [String]$status
    )

    Try {
        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
        $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo")
        $vropsBasicHeaders.Add("Content-Type", "application/json")

        $body = '{
            "pak_id" : "'
+ $pakId +'",
            "version" : "'
+ $version +'",
            "force_content_update": true
        }'

        $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/operation/$status" -Method 'POST' -Headers $vropsBasicHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vROPSManagementPack

Function Get-vROPSManagementPack {
    <#
        .SYNOPSIS
        Get installed management packs

        .DESCRIPTION
        The Get-vROPSManagementPack cmdlet gets a list of installed management packs in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSManagementPack -server xint-vrops01.rainpole.io -username admin -password VMw@re1!
        This example gets a list of all the management packs installed in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    Try {
        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
        $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo")
        $vropsBasicHeaders.Add("Content-Type", "application/json")

        $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/reserved/list" -Method 'GET' -Headers $vropsBasicHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSManagementPack

Function Get-vROPSManagementPackStatus {
    <#
        .SYNOPSIS
        Get install status of management pack

        .DESCRIPTION
        The Get-vROPSManagementPackStatus cmdlet gets the status of the install of a management pack in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSManagementPackStatus -server xint-vrops01.rainpole.io -username admin -password VMw@re1! -pakId SDDCHealth-8115995854
        This example uploads the management pack provided to vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pakId
    )

    Try {
        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
        $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo")

        $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/$pakId/status" -Method 'GET' -Headers $vropsBasicHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSManagementPackStatus

Function Get-vROPSManagementPackActivity {
    <#
        .SYNOPSIS
        Get current activity

        .DESCRIPTION
        The Get-vROPSManagementPackActivity cmdlet gets the current activity for management packs in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSManagementPackActivity -server xint-vrops01.rainpole.io -username admin -password VMw@re1!
        This example gets the current management pack activity in vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    Try {

        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
        $vropsBasicHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $vropsBasicHeaders.Add("Authorization", "Basic $base64AuthInfo")

        $response = Invoke-RestMethod "https://$server/casa/upgrade/cluster/pak/reserved/current_activity" -Method 'GET' -Headers $vropsBasicHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSManagementPackActivity

Function Get-vROPSAlertPlugin {
    <#
        .SYNOPSIS
        Get the alert plugins

        .DESCRIPTION
        The Get-vROPSAlertPlugin cmdlet gets the configured alert plugins in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSAlertPlugin
        This example gets a list of the alert plugins configure in vRealize Operations Manager
    #>


    Try {
        $uri = "https://$vropsAppliance/suite-api/api/alertplugins"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
        $response.notificationPluginInstances
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSAlertPlugin

Function Add-vROPSAlertPlugin {
    <#
        .SYNOPSIS
        Create an alert plugin

        .DESCRIPTION
        The Add-vROPSAlertPlugin cmdlet creates a new alert plugin in vRealize Operations Manager

        .EXAMPLE
        Add-vROPSAlertPlugin -json .\alertPlugin.json
        This example adds a new alert plugin based on the JSON provide to vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json")) {
            if (!(Test-Path $json)) {
                Throw "JSON File Not Found"
            }
            else {
                $body = (Get-Content $json) # Read the json file contents into the $body variable
            }
        }

        $uri = "https://$vropsAppliance/suite-api/api/alertplugins"
        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vROPSAlertPlugin

Function Set-vROPSAlertPlugin {
    <#
        .SYNOPSIS
        Updates an alert plugin

        .DESCRIPTION
        The Set-vROPSAlertPlugin cmdlet updates an existing alert plugin in vRealize Operations Manager

        .EXAMPLE
        Set-vROPSAlertPlugin -json .\alertPluginUpdate.json
        This example updates the configuration of an existing alert plugin based on the JSON provide to vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        if ($PsBoundParameters.ContainsKey("json")) {
            if (!(Test-Path $json)) {
                Throw "JSON File Not Found"
            }
            else {
                $body = (Get-Content $json) # Read the json file contents into the $body variable
            }
        }

        $uri = "https://$vropsAppliance/suite-api/api/alertplugins"
        $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $vropsHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vROPSAlertPlugin

Function Remove-vROPSAlertPlugin {
    <#
        .SYNOPSIS
        Delete an alert plugin

        .DESCRIPTION
        The Remove-vROPSAlertPlugin cmdlet deletes an existing alert plugin from vRealize Operations Manager

        .EXAMPLE
        Remove-vROPSAlertPlugin -plugId <plugin_id>
        This example deletes the alert plugin with the plugin ID provide to vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pluginId
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/alertplugins/$pluginId"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vROPSAlertPlugin

Function Get-vROPSAlertDefinition {
    <#
        .SYNOPSIS
        Get collection of alert definitions matching the search criteria specified

        .DESCRIPTION
        The Get-vROPSAlertDefinition cmdlet gets collection of alert definitions matching the search criteria specified in vRealize Operations

        .EXAMPLE
        Get-vROPSAlertDefinition
        This example gets all alert definitions

        .EXAMPLE
        Get-vROPSAlertDefinition -id SrmAdapter
        This example gets an alert definition by its id

        .EXAMPLE
        Get-vROPSAlertDefinition -adapterKind SrmAdapter
        This example gets all alert definitions for the adapter type SrmAdapter

        .EXAMPLE
        Get-vROPSAlertDefinition -resourceKind "Protection Groups"
        This example gets all alert definitions for the resource type SrmAdapter
    #>


    [CmdletBinding(DefaultParametersetName = 'default')][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $false, ParameterSetName = 'default')]
        [Parameter (Mandatory = $false, ParameterSetName = 'id')] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false, ParameterSetName = 'adapterKind')] [ValidateNotNullOrEmpty()] [String]$adapterKind,
        [Parameter (Mandatory = $false, ParameterSetName = 'resourceKind')] [ValidateNotNullOrEmpty()] [String]$resourceKind
    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vropsAppliance/suite-api/api/alertdefinitions?id=$id&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.alertDefinitions
        } elseif ($PsBoundParameters.ContainsKey("adapterKind")) {
            $uri = "https://$vropsAppliance/suite-api/api/alertdefinitions?adapterKind=$adapterKind&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.alertDefinitions
        } elseif ($PsBoundParameters.ContainsKey("resourceKind")) {
            $uri = "https://$vropsAppliance/suite-api/api/alertdefinitions?resourceKind=$resourceKind&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.alertDefinitions
        } else {
            $uri = "https://$vropsAppliance/suite-api/api/alertdefinitions"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.alertDefinitions
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSAlertDefinition

Function Set-vROPSAlertPluginStatus {
    <#
        .SYNOPSIS
        Enable/Disable alert plugin

        .DESCRIPTION
        The Set-vROPSAlertPluginStatus cmdlet Enables/Disables an existing alert plugin from vRealize Operations Manager

        .EXAMPLE
        Set-vROPSAlertPluginStatus -plugId <plugin_id> -status true
        This example deletes the alert plugin with the plugin ID provide to vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pluginId,
        [Parameter (Mandatory = $true)] [ValidateSet("false","true")] [ValidateNotNullOrEmpty()] [String]$status
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/alertplugins/$pluginId/enable/$status"
        $response = Invoke-RestMethod -Method 'PUT' -Uri $uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vROPSAlertPluginStatus

Function Get-vROPSAuthSource {
    <#
        .SYNOPSIS
        Get all the available authentication sources in the system

        .DESCRIPTION
        The Get-vROPSAuthSource cmdlet gets all the available authentication sources in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSAuthSource
        This example gets a list of all available authentication sources

        .EXAMPLE
        Get-vROPSAuthSource -sourceId <source_id>
        This example gets detailed information about the provided authentication source
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sourceId
    )

    Try {
        if ($PsBoundParameters.ContainsKey("sourceId")) {
            $uri = "https://$vropsAppliance/suite-api/api/auth/sources/$sourceId"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/auth/sources"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.sources
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSAuthSource

Function Get-vROPSAuthRole {
    <#
        .SYNOPSIS
        Get all the roles available in the system

        .DESCRIPTION
        The Get-vROPSAuthRole cmdlet gets all the roles available in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSAuthRole
        This example gets all the roles available
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name
    )

    Try {
        if ($PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$vropsAppliance/suite-api/api/auth/roles/$name"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/auth/roles"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.userRoles
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSAuthRole

Function Get-vROPSUserAccount {
    <#
        .SYNOPSIS
        Get list of local user accounts using identifiers or/and names.

        .DESCRIPTION
        The Get-vROPSUserAccount cmdlet gets a user account in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSUserAccount
        This example gets a list of all available authentication sources.

        .EXAMPLE
        Get-vROPSUserAccount -id <userAccount_id>
        This example gets detailed information about the user account using the ID.

        .EXAMPLE
        Get-vROPSUserAccount -username <userAccount_username>
        This example gets detailed information about the user account using the username.

        .EXAMPLE
        Get-vROPSUserAccount -roleName <userAccount_roleName>
        This example gets detailed information about the user account using the role name.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$roleName
    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vropsAppliance/suite-api/api/auth/users?id=$id&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response
        } elseif ($PsBoundParameters.ContainsKey("username")) {
            $uri = "https://$vropsAppliance/suite-api/api/auth/users?username=$username&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response.users
        } elseif ($PsBoundParameters.ContainsKey("roleName")) {
            $uri = "https://$vropsAppliance/suite-api/api/auth/users?roleName=$roleName&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.users
        } else {
            $uri = "https://$vropsAppliance/suite-api/api/auth/users"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.users
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSUserAccount

Function Get-vROPSUserGroup {
    <#
        .SYNOPSIS
        Get list of local user groups using identifiers or/and names

        .DESCRIPTION
        The Get-vROPSUserGroup cmdlet gets list of local user groups in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSUserGroup
        This example gets a list of all available authentication sources

        .EXAMPLE
        Get-vROPSUserGroup -id <userGroup_id>
        This example gets detailed information about the provided user group using the ID

        .EXAMPLE
        Get-vROPSUserGroup -id <userGroup_id>
        This example gets detailed information about the provided user group using the name
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$name

    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups?id=$id&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders
            $response
        }
        elseif ($PsBoundParameters.ContainsKey("name")) {
            $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups?name=$name&_no_links=true"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.userGroups
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.userGroups
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSUserGroup

Function Add-vROPSUserAccount {
    <#
        .SYNOPSIS
        Imports a user account from an authentication source.

        .DESCRIPTION
        The Add-vROPSUserAccount cmdlet imports a user account from the authentication source into vRealize Operations
        Manager.

        .EXAMPLE
        Add-vROPSUserAccount -sourceId <authentication_sourceId> -userName <user_account_name> -lastName <user_last_name> -firstName <user_first_name> -distinguishedName <user_distinguishedName> -role <role_name>
        This example imports a user account from the authentication source and assigns a role.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sourceId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$lastName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$firstName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$distinguishedName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/auth/sources/$sourceId/users"
        $body = '{ "users" : [
        {
            "username" : "'
 + $userName + '",
            "firstName" : "'
 + $firstName + '",
            "lastName" : "'
 + $lastName + '",
            "distinguishedName" : "'
 + $domain + '",
            "emailAddress" : "'
 + $userName + '@' + $domain + '",
            "enabled" : true,
            "role-permissions" : [ {
                "roleName" : "'
 + $role + '",
                "allowAllObjects" : true
            } ]
        }]}'

        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vROPSUserAccount

Function Add-vROPSUserGroup {
    <#
        .SYNOPSIS
        Import user group from an authentication source

        .DESCRIPTION
        The Add-vROPSUserGroup cmdlet imports a user group from the authentication source into vRealize Operations
        Manager

        .EXAMPLE
        Add-vROPSUserGroup -sourceId <authentication_sourceId> -userGroup <user_group_name> -role <role_name>
        This example imports a user group from the authentication source and assigns the Administrator Role
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sourceId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$userGroup,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups"
        $body = '{
            "authSourceId" : "'
 + $sourceId + '",
            "name" : "'
 + $userGroup + '",
            "role-permissions" : [ {
                "roleName" : "'
 + $role + '",
                "allowAllObjects" : true
            } ]
        }'

        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vROPSUserGroup

Function Remove-vROPSUserAccount {
    <#
        .SYNOPSIS
        Deletes a user account.

        .DESCRIPTION
        The Remove-vROPSUserAccount cmdlet deletes a user account from vRealize Operations Manager.

        .EXAMPLE
        Remove-vROPSUserAccount -id <userAccount_Id>
        This example deletes a user account from vRealize Operations Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/auth/users/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vROPSUserAccount

Function Remove-vROPSUserGroup {
    <#
        .SYNOPSIS
        Deletes a user group

        .DESCRIPTION
        The Remove-vROPSUserGroup cmdlet deletes a user group from vRealize Operations Manager

        .EXAMPLE
        Remove-vROPSUserGroup -id <userGroup_Id>
        This example deletes a user group from vRealize Operations Manager
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/auth/usergroups/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vROPSUserGroup

Function Search-vROPSUserAccount {
    <#
        .SYNOPSIS
        Search for a user account in the source.

        .DESCRIPTION
        The Search-vROPSUserAccount cmdlet searches for a user account in the source in vRealize Operations Manager.

        .EXAMPLE
        Search-vROPSUserAccount -sourceId 6d971ad0-a979-4dc1-81af-e77f6c8c158c -domain sfo.rainpole.io -userName "nigel.mccloud"
        This example searches for a user account in the source defined by source ID.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sourceId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$userName
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/auth/sources/$sourceId/users/search"
        
        $body = '{
                "domain": "'
 + $domain + '",
                "name": "'
 + $nameName + '"
            }'

        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
        $response.'user-search-response'
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Search-vROPSUserAccount

Function Search-vROPSUserGroup {
    <#
        .SYNOPSIS
        Search for a user group in the source

        .DESCRIPTION
        The Search-vROPSUserGroup cmdlet searches for a user group in the source in vRealize Operations Manager

        .EXAMPLE
        Search-vROPSUserGroup -sourceId 6d971ad0-a979-4dc1-81af-e77f6c8c158c -domain sfo.rainpole.io -groupName "gg-vrops-read-only@sfo.rainpole.io"
        This example searches for a user group in the source defined by source ID
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$sourceId,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$groupName
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/auth/sources/$sourceId/usergroups/search"
        
        $body = '{
                "domain": "'
 + $domain + '",
                "name": "'
 + $groupName + '"
            }'

        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
        $response.'usergroup-search-response'
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Search-vROPSUserGroup

Function Update-vROPSUserAccount {
    <#
        .SYNOPSIS
        Updates a user account.

        .DESCRIPTION
        The Update-vROPSUserAccount cmdlet updates a user account in vRealize Operations Manager.

        .EXAMPLE
        Updates-vROPSUserAccount -id <userAccount_Id>
        This example updateds a user account in vRealize Operations Manager.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/auth/users/$id"
        $response = Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vropsHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Update-vROPSUserAccount

Function Get-vROpsLogForwarding {
    <#
        .SYNOPSIS
        Gets the vRealize Operations Manager logging forwarding configuration.

        .DESCRIPTION
        The Get-vROpsLogForwarding cmdlet gets the vRealize Operations Manager logging forwarding configuration.

        .EXAMPLE
        Get-vROpsLogForwarding
        This example returns the logging forwarding configuration on vRealize Operations.
    #>


    Try {
        $uri = "https://$vropsAppliance/suite-api/api/logs/forwarding"
        if ($PSEdition -eq 'Core') {
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders -SkipCertificateCheck
        } else {
            $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders 
        }
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROpsLogForwarding

Function Get-vROPSNotification {
    <#
        .SYNOPSIS
        Get list of all notifications

        .DESCRIPTION
        The Get-vROPSNotification cmdlet gets list of all notifications in vRealize Operations Manager

        .EXAMPLE
        Get-vROPSNotification
        This example gets a list of all notifications

        .EXAMPLE
        Get-vROPSNotification -id <id>
        This example gets a list of all notifications
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id

    )

    Try {
        if ($PsBoundParameters.ContainsKey("id")) {
            $uri = "https://$vropsAppliance/suite-api/api/notifications/rules/$id"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response
        }
        else {
            $uri = "https://$vropsAppliance/suite-api/api/notifications/rules"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vropsHeaders
            $response.rules
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROPSNotification

Function New-vROPSNotification {
    <#
        .SYNOPSIS
        Creates notifications

        .DESCRIPTION
        The New-vROPSNotification cmdlet creates notifications in vRealize Operations Manager

        .EXAMPLE
        New-vROPSNotification -csvPath .\SampleNotifications\vropsNotifications-vcf.csv
        This example adds all the notifications in the csv file
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$csvPath
    )

    if ($PsBoundParameters.ContainsKey("csvPath")) {
        if (!(Test-Path $csvPath)) {
            Throw "CSV File Not Found"
        }
        else {
            $alerts = Import-CSV $csvPath | Where-Object -FilterScript { $_.alertName }
        }
    }

    Try {
        Foreach ($alert in $alerts) {
            $body = '{
                "name": "'
+ $($alert.alertName) +'",
                "pluginId": "'
+ (Get-vROPSAlertPlugin | Where-Object {$_.name -eq $($alert.alertPluginName)}).pluginId +'",
                "resourceKindFilters": [
                    {
                        "resourceKind": "'
+ $($alert.resourceKindKey) +'",
                        "adapterKind": "'
+ $($alert.adapterKindKey) +'"
                    }
                ],
                "resourceFilters": [ ],
                "alertDefinitionIdFilters": {
                    "values": [ "'
+ $($alert.alertDefinition) +'" ]
                },
                "properties": [
                    {
                        "name": "maxNotify",
                        "value": "'
+ $($alert.maxNotify) +'"
                    },
                    {
                        "name": "delay",
                        "value": "'
+ $($alert.delay) +'"
                    },
                    {
                        "name": "emailaddr",
                        "value": "'
+ $($alert.emailAddress) +'"
                    },
                    {
                        "name": "resend",
                        "value": "'
+ $($alert.resend) +'"
                    }
                ]
            }'

            $uri = "https://$vropsAppliance/suite-api/api/notifications/rules"
            if (!(Get-vROPSNotification | Where-Object {$_.name -eq $($alert.alertName)})) {
                Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vropsHeaders -Body $body
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vROPSNotification

Function Remove-vROPSNotification {
    <#
        .SYNOPSIS
        Delete a notification

        .DESCRIPTION
        The Remove-vROPSNotification cmdlet deletes a notifications in vRealize Operations Manager

        .EXAMPLE
        Remove-vROPSNotification -id <id>
        This example deletes a notifications
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id

    )

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/notifications/rules/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vropsHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vROPSNotification

Function Test-vROPsAdapterStatus {
    <#
        .SYNOPSIS
        Validates the integration status of a vRealize Operations adapter through adapter's ID
        
        .DESCRIPTION
        The Test-vROPsAdapterStatus cmdlet validates the integration status between vRealize Operations Manager and configured adapter.
    
        .EXAMPLE
        Test-vROPsAdapterStatus -resourceId "b214fd75-07cc-4dab-9fbb-95a6af739a04"
        This example validates the integration status between vRealize Operations Manager and configured adapter through its ID.
    #>

    
    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$resourceId
    )

    $name = (Get-vROPSAdapter | Where-Object { $_.id -eq $resourceId }).resourceKey.name

    Try {
        $uri = "https://$vropsAppliance/suite-api/api/resources/$resourceId"
        if ($PSEdition -eq 'Core') {
            $vropsresponse = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        } else {
            $vropsresponse = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vropsHeaders 
        }
        if ($vropsresponse.resourceHealth -eq "GREEN") {
            Write-Output "Adapter Name : $($name), Health Status: GREEN" 
        } else { 
            Write-Output "Adapter Name : $($name), Health Status: $($vropsresponse.resourceHealth), please check adapter log for details"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Test-vROPsAdapterStatus

#EndRegion End vRealize Operations Manager Functions ######
#####################################################################

#####################################################################
#Region Start vRealize Log Insight Functions ######

Function Request-vRLIToken {
    <#
        .SYNOPSIS
        Connects to the specified vRealize Log Insight and obtains authorization token

        .DESCRIPTION
        The Request-vRLIToken cmdlet connects to the specified vRealize Log Insight and obtains an authorization token.
        It is required once per session before running all other cmdlets.

        .EXAMPLE
        Request-vRLIToken -fqdn sfo-vvrli01.sfo.rainpole.io -username admin -password VMw@re1!
        This example shows how to connect to the vRealize Log Insight appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) {
        $creds = Get-Credential # Request Credentials
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }

    Try {

        $vrliBasicHeaders = createBasicAuthHeader $username $password
        $Global:vrliAppliance = $fqdn
        $Global:vrliHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $vrliHeaders.Add("Accept", "application/json")
        $vrliHeaders.Add("Content-Type", "application/json")
        $uri = "https://$vrliAppliance/api/v1/sessions"

        $body = "{
        `n `"username`" : `"$username`",
        `n `"provider`" : `"Local`",
        `n `"password`" : `"$password`"
        `n}"

        
        if ($PSEdition -eq 'Core') {
            $vrliResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vrliBasicHeaders -Body $body -SkipCertificateCheck # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        }
        else {
            $Global:vrliResponse = Invoke-RestMethod -Uri $uri -Method 'POST' -Headers $vrliBasicHeaders -Body $body
        }

        if ($vrliResponse.sessionId) {
            $vrliHeaders.Add("Authorization", "Bearer " + $vrliResponse.sessionId)
            Write-Output "Successfully connected to vRealize Log Insight: $vrliAppliance"
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-vRLIToken

Function Get-vRLIAuthenticationWSA {
    <#
        .SYNOPSIS
        Get configuration of Workspace ONE Access

        .DESCRIPTION
        The Get-vRLIAuthenticationWSA cmdlet gets the configuration for Workspace ONE Access Integration

        .EXAMPLE
        Get-vRLIAuthenticationWSA
        This example gets the configuration for Workspace ONE Access Integration
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/vidm"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vrliHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIAuthenticationWSA

Function Set-vRLIAuthenticationWSA {
    <#
        .SYNOPSIS
        Configure Workspace ONE Access Intergration

        .DESCRIPTION
        The Set-vRLIAuthenticationWSA cmdlet configures Workspace ONE Access Integration

        .EXAMPLE
        Set-vRLIAuthenticationWSA -hostname sfo-wsa01.sfo.rainpole.io -port 443 -redirectUrl sfo-vrli01.sfo.rainpole.io -username admin -password VMw@re1!
        This example configures Workspace ONE Access Integration
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$hostname,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$redirectUrl,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    Try {
        $jsonSpec = @()
        $jsonSpec += [pscustomobject]@{
            'acceptCert'    = $true
            'enabled'       = $true
            'hostname'      = $hostname
            'port'          = $port
            'redirectURL'   = $redirectUrl
            'username'      = $username
            'password'      = $password 
        }
        
        $body = $jsonSpec | ConvertTo-Json -Depth 12
        $uri = "https://$vrliAppliance/api/v1/vidm"
        $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vrliHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRLIAuthenticationWSA

Function Remove-vRLIAuthenticationWSA {
    <#
        .SYNOPSIS
        Disables Workspace ONE Access Intergration

        .DESCRIPTION
        The Remove-vRLIAuthenticationWSA cmdlet disables Workspace ONE Access Integration

        .EXAMPLE
        Remove-vRLIAuthenticationWSA
        This example disables Workspace ONE Access Integration
    #>


    Try {
        $jsonSpec = @()
        $jsonSpec += [pscustomobject]@{
            'enabled'       = $false
        }
        
        $body = $jsonSpec | ConvertTo-Json -Depth 12
        $uri = "https://$vrliAppliance/api/v1/vidm"
        $response = Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vrliHeaders -Body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRLIAuthenticationWSA

Function Get-vRLIContentPack {
    <#
        .SYNOPSIS
        Get list of installed content packs

        .DESCRIPTION
        The Get-vRLIContentPack cmdlet gets a list of all content packs installed on vRealize Log Insight

        .EXAMPLE
        Get-vRLIContentPack
        This example gets a list of all content packs
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/content/contentpack"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vrliHeaders
        $response.contentPackMetadataList
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIContentPack

Function Get-vRLIAgentGroup {
    <#
        .SYNOPSIS
        Get list of agent groups

        .DESCRIPTION
        The Get-vRLIAgentGroup cmdlet gets a list of agent groups

        .EXAMPLE
        Get-vRLIAgentGroup
        This example gets a list agent groups
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/agent/groups"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vrliHeaders
        $response.groups
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIAgentGroup

Function New-vRLIAgentGroup {
    <#
        .SYNOPSIS
        Create a new agent group

        .DESCRIPTION
        The New-vRLIAgentGroup cmdlet creates a new agent group

        .EXAMPLE
        New-vRLIAgentGroup -agentGroupType wsa -criteria sfo-wsa01.sfo.rainpole.io
        This example creats a new agent group for Workspace ONE Access and assigns the sfo-wsa01.sfo.rainpole.io host

        New-vRLIAgentGroup -agentGroupType photon -criteria sfo-vcf01.sfo.rainpole.io,xint-vrslcm01.rainpole.io,sfo-wsa01.sfo.rainpole.io
        This example creats a new agent group for Workspace ONE Access and assigns the hosts provided in the criteria host
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("wsa","photon")] [ValidateNotNullOrEmpty()] [String]$agentGroupType,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$agentGroupName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$criteria
    )

    if ($agentGroupType -eq "wsa") {
        $agentGroupConfig = '[filelog|gb-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=greenbox*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=gb-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"greenbox\"}\n\n[parser|gb-parser-onprem]\nbase_parser=clf\nformat=%t %{priority}i (%{thread}i) [%{java_class}i] - %M\n; Analytics Log InSight agent section\n\n[filelog|analytics-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=analytics-*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=analytics-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"analytics\"}\n\n[parser|analytics-parser-onprem]\nbase_parser=clf\nformat=%t %{timezone}i %{priority}i %{instance}i:%{service}i (%{thread}i) [%{src_str}i] %{java_class}i - %M\n; Password vault Log InSight agent section\n\n[filelog|pwvault-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=pwvault-*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=pwvault-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"pwvault\"}\n\n[parser|pwvault-parser-onprem]\nbase_parser=clf\nformat=%t %{timezone}i %{priority}i %{instance}i:%{service}i (%{thread}i) [%{src_str}i] %{java_class}i - %M\n\n[filelog|cert-proxy-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=cert-proxy*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=cert-proxy-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"cert-proxy\"}\n\n[parser|cert-proxy-parser-onprem]\nbase_parser=clf\nformat=%t %{priority}i (%{thread}i) [%{src_str}i] %{java_class}i - %M\n; vIDM SaaS Log InSight agent section\n\n[filelog|vidm-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=*.log\nevent_marker=^\\d{4}-\\d{2}-\\d{2}\nparser=vidm-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"vidm\"}\n\n[parser|vidm-parser-onprem]\nbase_parser=clf\nformat=%t %{priority}i (%{thread}i) [%{authentication}i] %{java_class}i - %M\nfield_decoder={\"authentication\":\"vidm-authentication-decoder-onprem\",\"log_message\":\"vidm-message-decoder-onprem\"}\nexclude_fields=log_message\n; vIDM SaaS Log InSight agent section for *.txt file\n\n[filelog|vidm-txt-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=*.txt\nevent_marker=^\nparser=vidm-txt-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"vidm\"}\n\n[parser|vidm-txt-parser-onprem]\nbase_parser=clf\nformat=%h %l %u [%t] \"%{request}i\" %{status_code}i %b %{response_time}i\n\n[filelog|kdc-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=kdc*.log\ntags={\"product\":\"vidm-aws\",\"component\":\"kdc\"}\n\n[filelog|kdc-mtkadmin-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs\ninclude=mtkadmin.log\ntags={\"product\":\"vidm-aws\",\"component\":\"kdc\"}\n;cfn-init Log InSight agent section\n\n[filelog|cfn-init-onprem]\n; IMPORTANT: Change the directory as per the environment\ndirectory=/opt/vmware/horizon/workspace/logs/\ninclude=cfn.*.log\nevent_marker=^\nparser=cfn-init-parser-onprem\ntags={\"product\":\"vidm-aws\",\"component\":\"cfn-init\"}\n\n[parser|cfn-init-parser-onprem]\nbase_parser=clf\n\n[parser|vidm-authentication-decoder-onprem]\nbase_parser=csv\ndelimiter=\";\"\nfields=tenant, user_uuid, remote_host\n\n[parser|vidm-message-decoder-onprem]\nbase_parser=clf\nformat=%{status}i %{operation}i (%{referer}i)\nfield_decoder={\"referer\":\"vidm-referer-decoder-onprem\"}\n\n[parser|vidm-referer-decoder-onprem]\nbase_parser=csv\nfields=url, , mime_type, method, ,'
    }
    elseif ($agentGroupType -eq "photon") {
        $agentGroupConfig = '[journaldlog|journal_config]\njournal_files=all\ntags={\"generator\":\"journald\"}\n\n[filelog|audit]\ndirectory=/root/\ninclude=.bash_history\ntags={\"audit\":\"bash_history\"}'
    }

    if ($criteria.Count -ge "1") {
        $criteriaInput = ""
        $count = $criteria.Count
        $pollLoopCounter = 0
        foreach ($component in $criteria) {
            $pollLoopCounter ++
            if ($pollLoopCounter -ne $count) {
                $criteriaInput += '(hostname=~\"'+$component+'\") or '
            }
            else {
                $criteriaInput += '(hostname=~\"'+$component+'\")'
            }
        }
    }
    else {
        $criteriaInput = '"hostname=~\"'+$criteria+'\""'
    }

    Try {
        $uri = "https://$vrliAppliance/api/v1/agent/groups"
        $body = '{
            "name":"'
+$agentGroupName+'",
            "criteria":"'
+$criteriaInput+'",
            "agentConfig":"'
+$agentGroupConfig+'"
        }'

        Invoke-RestMethod -Method 'POST' -Uri $Uri -Headers $vrliHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRLIAgentGroup

Function Remove-vRLIAgentGroup {
    <#
        .SYNOPSIS
        Remove an agent group

        .DESCRIPTION
        The Remove-vRLIAgentGroup cmdlet deletes an agent group

        .EXAMPLE
        Remove-vRLIAgentGroup -groupName "Workspace ONE Access (IAM) - Appliance Agent Group"
        This example deletes an agent group
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$groupName
    )

    Try {
        $groupName = $groupName.replace(' ','%20')
        $uri = "https://$vrliAppliance/api/v1/agent/groups/$groupName"
        Invoke-RestMethod -Method 'DELETE' -Uri $Uri -Headers $vrliHeaders
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRLIAgentGroup

Function Get-vRLISmtpConfiguration {
    <#
        .SYNOPSIS
        Get SMTP server settings

        .DESCRIPTION
        The Get-vRLISmtpConfiguration cmdlet gets the SMTP server configuration in vRealize Log Insight

        .EXAMPLE
        Get-vRLISmtpConfiguration
        This example gets the SMTP settings
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/notification/channels"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vrliHeaders
        $response.channels.config
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLISmtpConfiguration

Function Set-vRLISmtpConfiguration {
    <#
        .SYNOPSIS
        Configure the SMTP server settings

        .DESCRIPTION
        The Set-vRLISmtpConfiguration cmdlet configures the SMTP server settings in vRealize Log Insight

        .EXAMPLE
        Set-vRLISmtpConfiguration -smtpServer smtp.rainpole.io -port 25 -sender administrator@rainpole.io -username administrator@rainpole.io -password VMw@re1!
        This example sets the SMTP server settings
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$smtpServer,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sender,
        [Parameter (Mandatory = $false)] [String]$username,
        [Parameter (Mandatory = $false)] [String]$password
    )

    Try {
        $uri = "https://$vrliAppliance/api/v1/notification/channels"
        $body = '{
            "channels": [
              {
                "type": "email",
                "config": {
                  "server": "'
+ $smtpServer +'",
                  "port": '
+ $port + ',
                  "sslAuth": false,
                  "tls": false,
                  "defaultSender": "'
+ $sender +'",
                  "login": "'
+ $username +'",
                  "password": "'
+ $password +'"
                }
              }
            ]
          }'

        $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vrliHeaders -body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRLIEmailConfiguration

Function Get-vRLIRetentionThreshold {
    <#
        .SYNOPSIS
        Get the retention threshold configuration

        .DESCRIPTION
        The Get-vRLIRetentionThreshold cmdlet gets the retention configuration in vRealize Log Insight

        .EXAMPLE
        Get-vRLIRetentionThreshold
        This example gets the retention configuration
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/notification/config/retention-threshold"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vrliHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIRetentionThreshold

Function Set-vRLIRetentionThreshold {
    <#
        .SYNOPSIS
        Configuer the retention threshold settings

        .DESCRIPTION
        The Set-vRLIRetentionThreshold cmdlet configures the retention settings in vRealize Log Insight

        .EXAMPLE
        Set-vRLIRetentionThreshold -enable true -interval 1 -intervalUnit weeks
        This example configures the retention configuration
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("true", "false")] [ValidateNotNullOrEmpty()] [String]$enable,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$interval,
        [Parameter (Mandatory = $true)] [ValidateSet("minutes","hours","days","weeks","months")] [ValidateNotNullOrEmpty()] [String]$intervalUnit
    )

    Try {
        $uri = "https://$vrliAppliance/api/v1/notification/config/retention-threshold"
        $body = '{
            "sendNotification" : '
+ $enable +',
            "dataInterval" : '
+ $interval +',
            "intervalUnit" : "'
+ $intervalUnit.ToUpper() +'"
          }'

        $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vrliHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRLIRetentionThreshold

Function Get-vRLIIndexPartition {
    <#
        .SYNOPSIS
        Get the index partitions

        .DESCRIPTION
        The Get-vRLIIndexPartition cmdlet gets a list of index partitions in vRealize Log Insight

        .EXAMPLE
        Get-vRLIIndexPartition
        This example gets a list of index partitions
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/partitioning"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vrliHeaders
        $response.partitions
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIIndexPartition

Function Set-vRLILogArchive {
    <#
        .SYNOPSIS
        Configuer the index partitions

        .DESCRIPTION
        The Set-vRLILogArchive cmdlet configures the log archive location for a partition in vRealize Log Insight

        .EXAMPLE
        Set-vRLILogArchive -id d41d8cd9-8f00-3204-a980-0998ecf8427e -enable true -retentionPeriod 7 -archiveEnable true -archiveLocation nfs://172.27.11.4/sfo-m01-vrli01-400GB
        This example configures the retention configuration
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $true)] [ValidateSet("true", "false")] [ValidateNotNullOrEmpty()] [String]$enable,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Int]$retentionPeriodDays,
        [Parameter (Mandatory = $true)] [ValidateSet("true", "false")] [ValidateNotNullOrEmpty()] [String]$archiveEnable,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$archiveLocation
    )

    Try {
        $uri = "https://$vrliAppliance/api/v1/partitioning"
        $body = '{
            "id": "'
 + $id + '",
            "name": "",
            "enabled": '
+ $enable +',
            "routingFilter": "",
            "retentionPeriodSeconds": '
+ $retentionPeriodDays * 86400 +',
            "archiveEnabled": '
+ $archiveEnable +',
            "archiveLocation": "'
+ $archiveLocation +'"
        }'

        $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vrliHeaders -Body $body
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRLILogArchive

Function Get-vRLIEmailNotification {
    <#
        .SYNOPSIS
        Get list of email address for notifications

        .DESCRIPTION
        The Get-vRLIEmailNotification cmdlet gets a list of the emails notifications will be sent to in vRealize Log Insight

        .EXAMPLE
        Get-vRLIEmailNotification
        This example gets a list of email notifications
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/notification/email"
        $response = Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $vrliHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIEmailNotification

Function Set-vRLIEmailNotification {
    <#
        .SYNOPSIS
        Configure email address for notifications

        .DESCRIPTION
        The Set-vRLIEmailNotification cmdlet configures the emails addresses for notifications in vRealize Log Insight

        .EXAMPLE
        Set-vRLIEmailNotification -emailAddress "administrator@rainpole.io"
        This example adds a new email address to the notifications
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$emailAddress
    )  

    Try {
        $uri = "https://$vrliAppliance/api/v1/notification/email"
        $body = '{
            "emails": ["'
+ $emailAddress +'"
                ]
        }'

        $response = Invoke-RestMethod -Method 'PUT' -Uri $Uri -Headers $vrliHeaders -body $body
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRLIEmailNotification

Function Get-vRLIRole {
    <#
        .SYNOPSIS
        Get list of roles

        .DESCRIPTION
        The Get-vRLIRole cmdlet gets a list of roles in vRealize Log Insight

        .EXAMPLE
        Get-vRLIRole
        This example gets a list of roles in vRealize Log Insight
    #>

    Try {
        $uri = "https://$vrliAppliance/api/v1/roles"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vrliHeaders
        $response.roles
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIRole

Function Get-vRLIGroup {
    <#
        .SYNOPSIS
        Get list of groups by authentication provider

        .DESCRIPTION
        The Get-vRLIGroup cmdlet gets a list of groups by authentication provider

        .EXAMPLE
        Get-vRLIGroup -authProvider vidm
        This example gets a list groups assigned using the vIDM authenitcation provider

        .EXAMPLE
        Get-vRLIGroup-authProvider ad
        This example gets a list groups assigned using the ActiveDirectory authenitcation provider
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vidm","ad")] [ValidateNotNullOrEmpty()] [String]$authProvider
    )

    Try {
        $uri = "https://$vrliAppliance/api/v1/authgroups/$authProvider"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vrliHeaders
        $response.authProviderGroups
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIGroup

Function Add-vRLIGroup {
    <#
        .SYNOPSIS
        Add a group by authentication provider

        .DESCRIPTION
        The Add-vRLIGroup cmdlet adds a group by authentication provider

        .EXAMPLE
        Add-vRLIGroup -authProvider vidm -domain sfo.rainpole.io -group gg-vrli-admins -role "Super Admin"
        This example adds a group assigned using the the vIDM authenitcation provider and assigns the Super Admin role
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vidm","ad")] [ValidateNotNullOrEmpty()] [String]$authProvider,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group,
        [Parameter (Mandatory = $true)] [ValidateSet("Super Admin","User","Dashboard User","View Only Admin")] [ValidateNotNullOrEmpty()] [String]$role
    )

    Try {
        $roleId = (Get-vRLIRole | Where-Object {$_.name -eq $role}).id
        $uri = "https://$vrliAppliance/api/v1/authgroups"
        $json = '{ "provider": "' + $authProvider + '", "domain": "'+ $domain +'", "name": "'+ $group + "@" + $domain +'", "groupIds": [ "'+ $roleId + '" ]}'
        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vrliHeaders -Body $json
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Add-vRLIGroup

Function Remove-vRLIGroup {
    <#
        .SYNOPSIS
        Remove a group by authentication provider

        .DESCRIPTION
        The Remove-vRLIGroup cmdlet removes a group by authentication provider

        .EXAMPLE
        Remove-vRLIGroup -authProvider vidm -domain sfo.rainpole.io -group gg-vrli-admins
        This example removes a group assigned using the the vIDM authenitcation provider
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("vidm","ad")] [ValidateNotNullOrEmpty()] [String]$authProvider,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$group
    )

    Try {
        $uri = "https://$vrliAppliance/api/v1/authgroups/$authProvider/$domain/$group@$domain"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vrliHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRLIGroup

Function Get-vRLIAlert {
    <#
        .SYNOPSIS
        Get list of alerts

        .DESCRIPTION
        The Get-vRLIGroup cmdlet gets a list of alerts

        .EXAMPLE
        Get-vRLIGroup
        This example gets a list alerts from vRealize Log Insight
    #>


    Try {
        $uri = "https://$vrliAppliance/api/v1/alerts"
        $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vrliHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLIAlert

Function New-vRLIAlert {
    <#
        .SYNOPSIS
        Create an alert

        .DESCRIPTION
        The New-vRLIAlert cmdlet creates an alert in vRealize Log Insight

        .EXAMPLE
        New-vRLIAlert -json (Get-Content -Raw .\vrliAlert.json)
        This example creates an alert in vRealize Log Insight based on the contents of the JSON
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$vrliAppliance/api/v1/alerts"
        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vrliHeaders -Body $json
        $response   
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function New-vRLIAlert

Function Remove-vRLIAlert {
    <#
        .SYNOPSIS
        Delete an alerts

        .DESCRIPTION
        The Get-vRLIGroup cmdlet deletes an alerts

        .EXAMPLE
        Get-vRLIGroup -alertId <alert_id>
        This example deletes an alert from vRealize Log Insight
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$alertId
    )

    Try {
        $uri = "https://$vrliAppliance/api/v1/alerts/$alertId"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vrliHeaders
        $response
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRLIAlert

Function Get-vRLILogForwarder {
    <#
        .SYNOPSIS
        Get list of log forwarders.

        .DESCRIPTION
        The Get-vRLILogForwarder cmdlet returns log forwarders from vRealize Log Insight.

        .EXAMPLE
        Get-vRLILogForwarder
        This example gets a list of log forwarders from vRealize Log Insight.

        .EXAMPLE
        Get-vRLILogForwarder -id "04f98100-995b-3f56-b321-0e10f21ee022"
        This example gets a log forwarder from vRealize Log Insight by ID.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        if ($PsBoundParameters.ContainsKey('id')) {
            $uri = "https://$vrliAppliance/api/v2/log-forwarder/$id"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vrliHeaders
            $response
        }
        else {
            $uri = "https://$vrliAppliance/api/v2/log-forwarder"
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $vrliHeaders
            $response.forwarders
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vRLILogForwarder

Function Set-vRLILogForwarder {
    <#
        .SYNOPSIS
        Adds a log forwarder destination.

        .DESCRIPTION
        The Set-vRLILogForwarder cmdlet adds a log forwarder destination to vRealize Log Insight.

        .EXAMPLE
        Set-vRLILogForwarder -name "lax01-vrli01" -server "lax01-vrli01.lax.rainpole.io" -protocol SYSLOG -port 514 -transport TCP -acceptCert false -sslEnabled false -testConnection false
        This example adds a log forwarder to vRealize Log Insight using syslog over TCP 514.

        .EXAMPLE
        Set-vRLILogForwarder -name "lax01-vrli01" -server "lax01-vrli01.lax.rainpole.io" -protocol CFAPI -port 9543 acceptCert true -sslEnabled true -testConnection true
        This example adds a log forwarder to vRealize Log Insight using the Ingestion API and SSL enabled.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$name,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateSet("CFAPI", "SYSLOG", "RAW")] [String]$protocol,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $false)] [ValidateSet("TCP", "UDP")] [String]$transport,
        [Parameter (Mandatory = $true)] [ValidateSet('true', 'false')] [String]$acceptCert,
        [Parameter (Mandatory = $true)] [ValidateSet('true', 'false')] [String]$sslEnabled,
        [Parameter (Mandatory = $true)] [ValidateSet('true', 'false')] [String]$testConnection
    )

    Try {
        $uri = "https://$vrliAppliance/api/v2/log-forwarder"

        if ($protocol -eq 'SYSLOG' -and (-not $PsBoundParameters.ContainsKey('transport'))) {
            Throw 'You must enter a transport for SYSLOG.'
        } elseif ($protocol -eq 'SYSLOG' -and ($PsBoundParameters.ContainsKey('transport'))) {
            $body = '{
                "name": "'
 + $name + '",
                "host": "'
+ $server +'",
                "port": '
+ $port +',
                "protocol": "'
+ $protocol.ToUpper() +'",
                "transport": "'
+ $transport.Tolower() +'",
                "acceptCert": '
+ $acceptCert.ToString().ToLower() +',
                "sslEnabled": '
+ $sslEnabled.ToString().ToLower() +',
                "testConnection": '
+ $testConnection.ToString().ToLower() +'
            }'

        } else {
            $body = '{
                "name": "'
 + $name + '",
                "host": "'
+ $server +'",
                "port": '
+ $port +',
                "protocol": "'
+ $protocol.ToUpper() +'",
                "acceptCert": '
+ $acceptCert.ToString().ToLower() +',
                "sslEnabled": '
+ $sslEnabled.ToString().ToLower() +',
                "forwardComplementaryFields": true,
                "testConnection": '
+ $testConnection.ToString().ToLower() +'
            }'

        }
        Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vrliHeaders -Body $body
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Set-vRLILogForwarder

Function Remove-vRLILogForwarder {
    <#
        .SYNOPSIS
        Remove a log forwarder.

        .DESCRIPTION
        The Remove-vRLILogForwarder cmdlet removes a log forwarder destination from vRealize Log Insight.

        .EXAMPLE
        Remove-vRLILogForwarder
        This example removes a log forwarder destination from vRealize Log Insight.

        .EXAMPLE
        Remove-vRLILogForwarder -id "04f98100-995b-3f56-b321-0e10f21ee022"
        This example removes a log forwarder destination from vRealize Log Insight by ID.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$id
    )

    Try {
        $uri = "https://$vrliAppliance/api/v2/log-forwarder/$id"
        $response = Invoke-RestMethod -Method 'DELETE' -Uri $uri -Headers $vrliHeaders
        $response
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Remove-vRLILogForwarder

Function Update-vRLILogForwarder {
    <#
        .SYNOPSIS
        Updates a log forwarder.

        .DESCRIPTION
        The Updates-vRLILogForwarder cmdlet updates s a log forwarder destination from vRealize Log Insight.

        .EXAMPLE
        Updates-vRLILogForwarder
        This example updates a log forwarder destination from vRealize Log Insight.

        .EXAMPLE
        Updates-vRLILogForwarder -id "04f98100-995b-3f56-b321-0e10f21ee022" -json $json
        This example updates a log forwarder destination from vRealize Log Insight.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json
    )

    Try {
        $uri = "https://$vrliAppliance/api/v2/log-forwarder/$id"
        Invoke-RestMethod -Method 'PATCH' -Uri $uri -Headers $vrliHeaders -Body $json
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Update-vRLILogForwarder

Function Test-vRLILogForwarder {
    <#
        .SYNOPSIS
        Test a log forwarder destination endpoint.

        .DESCRIPTION
        The Test-vRLILogForwarder cmdlet tests a log forwarder destination from vRealize Log Insight.

        .EXAMPLE
        Test-vRLILogForwarder -server "lax01-vrli01.lax.rainpole.io" -port 9000 -protocol CFAPI
        This example tests a log forwarder destination from vRealize Log Insight.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$port,
        [Parameter (Mandatory = $true)] [ValidateSet("CFAPI", "TCP", "UDP")] [String]$protocol
    )

    Try {
        $uri = "https://$vrliAppliance/api/v2/log-forwarder/testconnection"
        $body = '{ "host": "' + $server + '", "port": ' + $port + ', "protocol": "'+ $protocol.ToLower() +'"}'
        Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $vrliHeaders -Body $body
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Test-vRLILogForwarder

Function Get-vRLIMarketplaceMetadata {
    <#
        .SYNOPSIS
        Returns metadate for available items in the Content Pack Marketplace.

        .DESCRIPTION
        The Get-vRLIMarketplaceMetadata cmdlet returns the metadata for vRealize Log Insight content packs available in
        the Content Pack Marketplace hosted on GitHub (https://github.com/vmw-loginsight/).

        .EXAMPLE
        Get-vRLIMarketplaceMetadata
        This example returns the metadata for vRealize Log Insight content packs in the Content Pack MarketPlace.
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$index
    )
    
    Try {
        # Get the headers with authorization to pull content pack from the GitHub repository
        createGitHubAuthHeader
        if ($PsBoundParameters.ContainsKey("index")) {
            # Get the content pack index from the GitHub repository
            $uri = 'https://api.github.com/repos/vmw-loginsight/vlcp/contents/index.json'
        } else {
            # Get the content pack metadata from the GitHub repository
            $uri = 'https://api.github.com/repos/vmw-loginsight/vlcp/contents/content/'
        }
        Invoke-RestMethod -Method 'GET' -Uri $Uri -Headers $ghHeaders
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-vRLIMarketplaceMetadata

Function Install-vRLIContentPack {
    <#
        .SYNOPSIS
        Installs a content pack to vRealize Log Insight.

        .DESCRIPTION
        The Install-vRLIContentPack cmdlet installed a content pack to vRealize Log Insight.

        .EXAMPLE
        Install-vRLIContentPack -json $json
        This example installs a content pack to vRealize Log Insight from a JSON payload.

        .EXAMPLE
        Insall-vRLIContentPack -update -json $json
        This example updates a content pack in vRealize Log Insight from a JSON payload.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$json,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$update
    )

    Try {
        if ($PsBoundParameters.ContainsKey("update")) {
            $uri = "https://$vrliAppliance/api/v1/content/contentpack?overwrite=true"
        } else {
            $uri = "https://$vrliappliance/api/v1/content/contentpack"
        }
        Invoke-RestMethod -Method 'POST' -Uri $Uri -ContentType 'application/octet-stream' -Headers $vrliHeaders -Body $json
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Install-vRLIContentPack

#EndRegion End vRealize Log Insight Functions ######
#####################################################################

#####################################################################
#Region Start vRealize Cloud Services Functions ######

Function Request-CSPToken {
    <#
        .SYNOPSIS
        Request authorization token from VMware Cloud Service

        .DESCRIPTION
        The Request-CSPToken cmdlet connects to the VMware Cloud Service and obtains an authorization token.
        It is required once per session before running all other cmdlets.

        .EXAMPLE
        Request-CSPToken -environment production -apiToken <string>
        This example shows how to connect to the production VMware Cloud Service and obtain an authorization token.

        .EXAMPLE
        Request-CSPToken -environment staging -apiToken <string>
        This example shows how to connect to the staging VMware Cloud Service and obtain an authorization token.

        .EXAMPLE
        Request-CSPToken -environment staging -apiToken <string> -extensibilityProxy sfo-vmc-cep01.sfo.rainpole.io
        This example shows how to connect to the staging VMware Cloud Service and obtain an authorization token and set
        set the fqdn for the Cloud Extensibility Proxy for vRealize Orchestrator configuration.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("production","staging")] [ValidateNotNullOrEmpty()] [String]$environment,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$apiToken,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$extensibilityProxy
    )

    Try {
        if ($environment -eq "staging") {
            $Global:cspBaseUrl = "https://console-stg.cloud.vmware.com"
        } elseif ($environment -eq "production") {
            $Global:cspBaseUrl = "https://console.cloud.vmware.com"
        }

        if ($PSBoundParameters.ContainsKey('extensibilityProxy')) {
            $Global:cepAppliance = $extensibilityProxy
        }
        
        $Global:basicHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $basicHeader.Add("Content-Type", "application/x-www-form-urlencoded")
        $path = "/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$apiToken"
        $uri = $cspBaseUrl + $path

        if ($PSEdition -eq 'Core') {
            $cspResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $basicHeader -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        } else {
            $cspResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $basicHeader -UseBasicParsing
        }

        if ($cspResponse.StatusCode -eq 200) {
            $Global:cspHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
            $cspHeader.Add("Accept", "application/json")
            $cspHeader.Add("Content-Type", "application/json")
            $cspHeader.Add("Authorization", "Bearer " + ($cspResponse.Content | ConvertFrom-Json).access_token)
            Write-Output "Successfully connected to VMware Cloud Console: $cspBaseUrl"
        } else {
            Write-Error "Invalid API Token Failed to connect to VMware Cloud Console: $cspBaseUrl"
        }
    } Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Request-CSPToken

Function Get-CloudProxy {
    <#
        .SYNOPSIS
        Request Cloud Proxies from VMware Cloud Service

        .DESCRIPTION
        The Get-CloudProxy cmdlet connects to the VMware Cloud Service and either downloads the OVA or
        supplies the OVA link.

        .EXAMPLE
        Get-CloudProxy -environment production -type 'Cloud Proxy' -download -path <string>
        This example shows how to download the Cloud Proxy OVA to the path provided.

        .EXAMPLE
        Get-CloudProxy -environment production -type 'Cloud Extensibility Proxy' -download -path <string>
        This example shows how to download the Cloud Extensibility Proxy OVA to the path provided.

        .EXAMPLE
        Get-CloudProxy -environment production -type 'Cloud Proxy' -ovaUrl
        This example shows how to obtain the URL to the Cloud Proxy OVA.

        .EXAMPLE
        Get-CloudProxy -environment production -region uk -type 'Cloud Proxy' -ovaUrl
        This example shows how to obtain the URL to the Cloud Proxy OVA for the United Kingdom region.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("production","staging")] [ValidateNotNullOrEmpty()] [String]$environment,
        [Parameter (Mandatory = $false)] [ValidateSet("au","br","ca","de","jp","sg","uk","us")] [ValidateNotNullOrEmpty()] [String]$region,
        [Parameter (Mandatory = $true)] [ValidateSet("Cloud Proxy","Cloud Extensibility Proxy")] [ValidateNotNullOrEmpty()] [String]$type,
        [Parameter (Mandatory = $false, ParameterSetName = 'download')] [ValidateNotNullOrEmpty()] [Switch]$download,
        [Parameter (Mandatory = $false, ParameterSetName = 'download')] [ValidateNotNullOrEmpty()] [String]$path,
        [Parameter (Mandatory = $false, ParameterSetName = 'ovaUrl')] [ValidateNotNullOrEmpty()] [Switch]$ovaUrl
    )

    Try {
        if ($environment -eq "staging") {
            $baseUrl = "https://api.staging.symphony-dev.com"
        } elseif ($environment -eq "production") {
            if ($PsBoundParameters.ContainsKey("region")) {
                if ($region -eq "us") {
                    $baseUrl = 'https://api.mgmt.cloud.vmware.com'
                } else {
                    $baseUrl = "https://$region.api.mgmt.cloud.vmware.com"
                }       
            } else {
                $baseUrl = "https://api.mgmt.cloud.vmware.com"
            }
        }

        if ($type -eq "Cloud Proxy") {
            $apiUrl = "/api/artifact-provider?artifact=data-collector"
            $uri = $baseUrl + $apiUrl
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $cspHeader
            $ovaName = ($response.providerUrl -Split (".com/"))[1]
        } elseif ($type -eq "Cloud Extensibility Proxy") {
            $apiUrl = "/api/artifact-provider?artifact=cexp-data-collector"
            $uri = $baseUrl + $apiUrl
            $response = Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $cspHeader
            $ovaName = ($response.providerUrl -Split (".com/staging/"))[1]
        }

        if ($PsBoundParameters.ContainsKey("download")) {
            if ($PsBoundParameters.ContainsKey("path")) {
                $downloadPath = $path + "\" + $ovaName
            } else {
                $downloadPath = $PSScriptRoot + "\" + $ovaName
            }
            if ($PSEdition -eq "Core" -and ($PSVersionTable.OS).Split(' ')[0] -eq "Linux" -or ($PSVersionTable.OS).Split(' ')[0] -eq "Darwin" ) {
                $downloadPath = ($downloadPath).split('\') -join '/' | Split-Path -NoQualifier
            }

            if (!(Test-Path $downloadPath)) {
                Write-Output "Started to Download the Cloud Assembly Cloud Proxy OVA to '$downloadPath'"
                (New-Object System.Net.WebClient).DownloadFile($($response.providerUrl), $downloadPath)
                if (Test-Path $downloadPath) {
                    Write-Output "Downloading the Cloud Assembly Cloud Proxy OVA to '$downloadPath': SUCCESSFUL"
                } else {
                    Write-Error "Downloading the Cloud Assembly Cloud Proxy OVA to '$downloadPath': POST_VALIDATION_FAILED"
                }
            } else {
                Write-Warning "Downloading the Cloud Assembly Cloud Proxy OVA to '$downloadPath', already downloaded: SKIPPED"
            }
        } elseif ($PsBoundParameters.ContainsKey("ovaUrl")) {
            $response.providerUrl
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-CloudProxy

Function Get-CloudProxyOtk {
    <#
        .SYNOPSIS
        Request One Time Key (OTK) for Cloud Proxies from VMware Cloud Service

        .DESCRIPTION
        The Get-CloudProxyOtk cmdlet connects to the VMware Cloud Service and requests a One Time Key (OTK) which is
        used during the deployment of the OVA.

        .EXAMPLE
        Get-CloudProxyOtk -environment production -type 'Cloud Proxy'
        This example shows how to get the One Time Key (OTK) for the Cloud Proxy.

        .EXAMPLE
        Get-CloudProxyOtk -environment production -type 'Cloud Extensibility Proxy'
        This example shows how to get the One Time Key (OTK) for the Cloud Extensibility Proxy.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet("production","staging")] [ValidateNotNullOrEmpty()] [String]$environment,
        [Parameter (Mandatory = $true)] [ValidateSet("Cloud Proxy","Cloud Extensibility Proxy")] [ValidateNotNullOrEmpty()] [String]$type,
        [Parameter (Mandatory = $false)] [ValidateSet("au","br","ca","de","jp","sg","uk","us")] [ValidateNotNullOrEmpty()] [String]$region
    )

    Try {
        if ($environment -eq 'staging') {
            $baseUrl = 'https://api.staging.symphony-dev.com'
        }
        elseif ($environment -eq 'production') {
            if ($PsBoundParameters.ContainsKey('region')) {
                if ($region -eq 'us') {
                    $baseUrl = 'https://api.mgmt.cloud.vmware.com'
                }
                else {
                    $baseUrl = "https://$region.api.mgmt.cloud.vmware.com"
                }       
            } else {
                $baseUrl = 'https://api.mgmt.cloud.vmware.com'
            }
        }
        $apiUrl = "/api/otk-v3"
        $uri = $baseUrl + $apiUrl

        if ($type -eq "Cloud Proxy") {
            $body = '{"url":"' + $baseUrl + '","service":"cloud_assembly"}'
        } elseif ($type -eq "Cloud Extensibility Proxy") {
            $body = '{"url":"' + $baseUrl + '","service":"cloud_assembly_extensibility"}'
        }
        $response = Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $cspHeader -Body $body
        $response

    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-CloudProxyOtk

Function Get-vROVersion {
    <#
        .SYNOPSIS
        Retrieve the vRealize Orchestrator version details
        
        .DESCRIPTION
        The Get-vROVersion cmdlet retrieves the vRealize Orchestrator version information. It supports the following:
        (Requires an access token before a connection can be made)
        - Standalone vRealize Orchestrator
        - Embedded vRealize Orchestrator with vRealize Automation
        - Cloud Extensibility Proxy with vRealize Orchestrator

        .EXAMPLE
        Get-vROVersion -standalone
        This examples retrieves the version details from a standlaone vRealize Orchestrator appliance

        .EXAMPLE
        Get-vROVersion -embedded
        This examples retrieves the version details from an embedded vRealize Orchestrator instance running within the
        vRealize Automation appliances.

        .EXAMPLE
        Get-vROVersion -extensibility
        This examples retrieves the version details from a vRealize Orchestrator instance running within the
        vCloud Extensibility Proxy appliance.
    #>


    [CmdletBinding(DefaultParametersetName = "embedded")][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $false, ParameterSetName = "standalone")] [ValidateNotNullOrEmpty()] [Switch]$standalone,
        [Parameter (Mandatory = $false, ParameterSetName = "embedded")] [ValidateNotNullOrEmpty()] [Switch]$embedded,
        [Parameter (Mandatory = $false, ParameterSetName = "extensibility")] [ValidateNotNullOrEmpty()] [Switch]$extensibility
    )

    Try {
        Switch ($PsCmdlet.ParameterSetName) {
            "standalone" {
                $baseUrl = "https://$vroAppliance"
                Break
            }
            "embedded" {
                $baseUrl = "https://$vraAppliance"
                Break
            }
            "extensibility" {
                $baseUrl = "https://$cepAppliance"
                Break
            }
        }

        $path = "/vco/api/about"
        $uri = $baseUrl + $path
        Invoke-RestMethod -Method 'GET' -Uri $uri -Headers $cspHeader
    } 
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-vROVersion

Function Get-CEPWorkflow {
    <#
        .SYNOPSIS
        Get vRealize Orchestrator workflows

        .DESCRIPTION
        The Get-CEPWorkflow cmdlet returns details for vRealize Orchestrator workflows

        .EXAMPLE
        Get-CEPWorkflow

        .EXAMPLE
        Get-CEPWorkflow -categoryName 'SSL Trust Manager'

        .EXAMPLE
        Get-CEPWorkflow -categoryId 3f23f186158a4869b464b7271fc216ba

        .EXAMPLE
        Get-CEPWorkflow -id '93a7bb21-0255-4750-9293-2437abe9d2e5'

        .EXAMPLE
        Get-CEPWorkflow -name 'Import a trusted certificate from a file'

        .EXAMPLE
        Get-CEPWorkflow -name 'Import a trusted certificate' -wildcard

        .NOTES
        Attribution: PowervRO by Jakku Labs (https://github.com/jakkulabs/PowervRO/)
    #>


    [CmdletBinding(DefaultParametersetName = "All")][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $false, ParameterSetName = "categoryName")] [Alias("Category")] [String]$categoryName,
        [Parameter (Mandatory = $false, ParameterSetName = "categoryId")] [String]$categoryId,
        [Parameter (Mandatory = $false, ParameterSetName = "id")] [String]$id,
        [Parameter (Mandatory = $false, ParameterSetName = "name")] [String]$name,
        [Parameter (Mandatory = $false, ParameterSetName = "name")] [Switch]$wildcard,
        [Parameter (Mandatory = $false, ParameterSetName = "all")]
        [Parameter (Mandatory = $false, ParameterSetName = "categoryName")]
        [Parameter (Mandatory = $false, ParameterSetName = "category")] [String[]]$tag
    )

    Try {
        Switch ($PsCmdlet.ParameterSetName) {
            "all" {
                $uri = "https://$cepAppliance/vco/api/workflows"
                break
            }
            "categoryName" {
                $uri = "https://$cepAppliance/vco/api/workflows/?conditions=categoryName=$($categoryName)"
                break
            }
            "categoryId" {
                $uri = "https://$cepAppliance/vco/api/catalog/System/WorkflowCategory/$($categoryId)/workflows"
                break
            }
            "id" {
                $uri = "https://$cepAppliance/vco/api/workflows/$($id)"
                break
            }
            "name" {
                if ($PSBoundParameters.ContainsKey('wildcard')) {
                    $uri = "https://$cepAppliance/vco/api/workflows/?conditions=name~$($name)"
                }
                else {
                    $uri = "https://$cepAppliance/vco/api/workflows/?conditions=name=$($name)"
                }
                break
            }
        }
        # Filter by tag, if needed
        if ($PSBoundParameters.ContainsKey('tag')) {
            $uri += if ($PSCmdlet.ParameterSetName -eq 'all') { '?' } else { '&' }
            $newParams = @()
            foreach ($tagAttr in $tag) {
                $newParams += "tags=$($tagAttr)"
            }
            $uri += $newParams -join '&'
        }
        Switch ($PsCmdlet.ParameterSetName) {
            "id" {
                $workflow = Invoke-RestMethod -method 'GET' -uri $uri -Headers $cspHeader
                [pscustomobject]@{
                    Name         = $workflow.name
                    ID           = $workflow.id
                    Description  = $workflow.description
                    ItemHref     = $workflow.href
                    Version      = $workflow.version
                    CategoryName = $null
                    CategoryHref = $null
                    CustomIcon   = $workflow.'customized-icon'
                    CanExecute   = $null
                    CanEdit      = $null
                }
            }
            "categoryId" {
                $workflows = Invoke-RestMethod -method 'GET' -uri $uri -Headers $cspHeader
                foreach ($workflow in $workflows.link) {
                    $returnObject = @{
                        Name         = ($workflow.attributes | Where-Object { $_.name -eq 'name' }).value
                        ID           = ($workflow.attributes | Where-Object { $_.name -eq 'id' }).value
                        Description  = ($workflow.attributes | Where-Object { $_.name -eq 'description' }).value
                        ItemHref     = $workflow.href
                        Version      = ($workflow.attributes | Where-Object { $_.name -eq 'version' }).value
                        CategoryName = ($workflow.attributes | Where-Object { $_.name -eq 'categoryName' }).value
                        CategoryHref = ($workflow.attributes | Where-Object { $_.name -eq 'categoryHref' }).value
                        CustomIcon   = ($workflow.attributes | Where-Object { $_.name -eq 'customIcon' }).value
                        CanExecute   = ($workflow.attributes | Where-Object { $_.name -eq 'canExecute' }).value
                        CanEdit      = ($workflow.attributes | Where-Object { $_.name -eq 'canEdit' }).value
                    }
                    # Add tags if needed
                    $tags = $workflow.attributes | Where-Object { $_.name -eq 'globalTags' } | Select-Object -ExpandProperty 'value'
                    if ($tags) {
                        $tagsArray = ($tags -replace ':__SYSTEM_TAG__|.$', '').Split(' ')
                        $returnObject.Add('tags', $tagsArray)
                    }
                    [PSCustomObject]$returnObject
                }
            }
            Default {
                $workflows = Invoke-RestMethod -method 'GET' -uri $uri -Headers $cspHeader
                Foreach ($workflow in $workflows.link) {
                    $returnObject = @{
                        Name         = ($workflow.attributes | Where-Object { $_.name -eq 'name' }).value
                        ID           = ($workflow.attributes | Where-Object { $_.name -eq 'id' }).value
                        Description  = ($workflow.attributes | Where-Object { $_.name -eq 'description' }).value
                        ItemHref     = ($workflow.attributes | Where-Object { $_.name -eq 'itemHref' }).value
                        Version      = ($workflow.attributes | Where-Object { $_.name -eq 'version' }).value
                        CategoryName = ($workflow.attributes | Where-Object { $_.name -eq 'categoryName' }).value
                        CategoryHref = ($workflow.attributes | Where-Object { $_.name -eq 'categoryHref' }).value
                        CustomIcon   = ($workflow.attributes | Where-Object { $_.name -eq 'customIcon' }).value
                        CanExecute   = ($workflow.attributes | Where-Object { $_.name -eq 'canExecute' }).value
                        CanEdit      = ($workflow.attributes | Where-Object { $_.name -eq 'canEdit' }).value
                    }
                    # Add tags, if needed
                    $tags = $workflow.attributes | Where-Object { $_.name -eq 'globalTags' } | Select-Object -ExpandProperty 'value'
                    if ($tags) {
                        $tagsArray = ($tags -replace ':__SYSTEM_TAG__|.$', '').Split(' ')
                        $returnObject.Add('tags', $tagsArray)
                    }
                    [PSCustomObject]$returnObject
                }
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-CEPWorkflow

Function Invoke-CEPWorkflow {
    <#
        .SYNOPSIS
        Invoke a vRealize Orchestrator workflow

        .DESCRIPTION
        The Invoke-CEPWorkflow cmdlet starts a vRealize Orchestrator workflow

        .EXAMPLE
        Invoke-CEPWorkflow -ID 3f23f186-158a-4869-b464-b7271fc216ba

        .EXAMPLE
        Invoke-CEPWorkflow -ID 3f23f186-158a-4869-b464-b7271fc216ba -parameterName 'text' -parameterValue 'foo' -parameterType 'string'

        .EXAMPLE
        $Parameters = @"
        {"parameters":
            [
                {
                    "value": {"string":{ "value": "bar"}},
                    "type": "string",
                    "name": "foo",
                    "scope": "local"
                },
                {
                    "value": {"number":{ "value": 2022}},
                    "type": "number",
                    "name": "year",
                    "scope": "local"
                }
            ]
        }
        "@

        Invoke-CEPWorkflow -id 3f23f186-158a-4869-b464-b7271fc216ba -parameters ($parameters | ConvertFrom-Json).parameters

        .EXAMPLE
        $param1 = New-vROParameterDefinition -name 'foo' -value 'bar' -type string -scope LOCAL
        Invoke-CEPWorkflow -id 3f23f186-158a-4869-b464-b7271fc216ba -parameters $param1

        .EXAMPLE
        Invoke-CEPWorkflow -name 'Import a trusted certificate from a file' | Invoke-CEPWorkflow -parameterName 'foo' -parameterValue 'bar' -parameterType string
    #>


    [CmdletBinding(DefaultParametersetName = "A")][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $true, ValueFromPipelinebyPropertyName = $true, ParameterSetName = "A")]
        [Parameter (Mandatory = $true, ParameterSetName = "B")] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [ValidateNotNullOrEmpty()] [String]$parameterName,
        [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [String]$parameterValue,
        [Parameter (Mandatory = $false, ParameterSetName = "A")] [Parameter (ParameterSetName = "C")] [ValidateNotNullOrEmpty()] [String]$parameterType,
        [Parameter (Mandatory = $false, ParameterSetName = "B")] [Parameter (ParameterSetName = "D")] [ValidateNotNullOrEmpty()] [PSCustomObject[]]$parameters
    )

    Begin {}
    Process {
        Try {
            if ($PSBoundParameters.ContainsKey('parameterType')) {
                $parameterType = $parameterType.ToLower()
                $body = @"
{"parameters":
    [
        {
            "value": {"$($parameterType)":{ "value": "$($parameterValue)"}},
            "type": "$($parameterType)",
            "name": "$($parameterName)",
            "scope": "local"
        }
    ]
}
"@

            }
            elseif ($PSBoundParameters.ContainsKey('parameters')) {
                $object = [PSCustomObject]@{
                    parameters = @()
                }
                foreach ($parameter in $parameters) {
                    $object.parameters += $parameter
                }
                $body = $object | ConvertTo-Json -Depth 100
            } else {
                $body = @"
{"parameters":
[
]
}
"@

            }
            $uri = "https://$cepAppliance/vco/api/workflows/$id/executions/"
            $response = Invoke-RestMethod -method 'POST' -uri $uri -body $body -Headers $cspHeader

            if ($PSEdition -eq 'Core') {
                [pscustomobject]@{
                    StatusCode        = $response.StatusCode
                    StatusDescription = $response.StatusDescription
                    Execution         = ([System.Uri]$response.Headers.Location[0]).LocalPath
                }
            } else {
                [pscustomobject]@{
                    StatusCode        = $response.StatusCode
                    StatusDescription = $response.StatusDescription
                    Execution         = ([System.Uri]$response.Headers.Location).LocalPath
                }
            }
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }
}
Export-ModuleMember -Function Invoke-CEPWorkflow

Function Get-CEPWorkflowExecution {
    <#
        .SYNOPSIS
        Retrieve vRealize Orchestrator Workflow Status

        .DESCRIPTION
        The Get-CEPWorkflowExecution cmdlet returns the execution status for a vRealize Orchestrator workflow

        .EXAMPLE
        Get-CEPWorkflowExecution -id 93a7bb21-0255-4750-9293-2437abe9d2e5
        The example retrieves the status for all workflows based on workflow ID

        .EXAMPLE
        Get-CEPWorkflowExecution -name 'Import a trusted certificate from a file'
        The example retrieves the status for all workflows based on workflow name

        .EXAMPLE
        Get-CEPWorkflowExecution -name 'Import a trusted certificate from a file' -executionId 397a7b99-cdd0-427e-8fa1-2ff9cdd96fae
    #>


    [CmdletBinding(DefaultParametersetName = "A")][OutputType('System.Management.Automation.PSObject')]

    Param (   
        [Parameter (Mandatory = $false, ParameterSetName = "id")] [ValidateNotNullOrEmpty()] [String]$id,
        [Parameter (Mandatory = $false, ParameterSetName = "name")] [ValidateNotNullOrEmpty()] [String]$name
    )

    Try {
        if ($PSCmdlet.ParameterSetName -eq "name") {
            $id = (Get-CEPWorkflow -name $name).id
        }
        $uri = "https://$cepAppliance/vco/api/workflows/$id/executions"
        $response = Invoke-RESTMethod -Method 'GET' -Uri $uri -Headers $cspHeader
        $data = $response.relations.link | Where-Object { $_.attributes }
        Foreach ($execution in $data) {
            [PSCustomObject]@{                                
                Name      = ($execution.attributes | Where-Object { $_.name -eq 'name' }).value
                ID        = ($execution.attributes | Where-Object { $_.name -eq 'id' }).value
                Execution = "$uri/$(($execution.attributes | Where-Object {$_.name -eq 'id'}).value)/"
                State     = ($execution.attributes | Where-Object { $_.name -eq 'state' }).value
                StartedBy = ($execution.attributes | Where-Object { $_.name -eq 'startedBy' }).value
                StartDate = ($execution.attributes | Where-Object { $_.name -eq 'StartDate' }).value
                EndDate   = ($execution.attributes | Where-Object { $_.name -eq 'EndDate' }).value
            }
        }
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-CEPWorkflowExecution

Function Get-CEPWorkflowExecutionState {
    <#
        .SYNOPSIS
        Get a vRealize Orchestrator Workflow execution state

        .DESCRIPTION
        The Get-CEPWorkflowExecutionState cmdlet returns the status of vRealize Orchestrator workflow execution runs

        .EXAMPLE
        Get-CEPWorkflowExecutionState -workflowId 93a7bb21-0255-4750-9293-2437abe9d2e5 -executionId 0f37aa69-b95c-4c80-8b63-b8e5085aa3fd
        The examples returns the execution status of a workflow based on the Workflow ID and Execution ID
    #>


    Param (   
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$workflowId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$executionId
    )

    Try {
        $uri = "https://$cepAppliance/vco/api/workflows/$workflowId/executions/$executionId/state"   
        (Invoke-RestMethod -method 'GET' -uri $uri -Headers $cspHeader).value
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}
Export-ModuleMember -Function Get-CEPWorkflowExecutionState

Function Add-CEPTrustedCertificate {
    <#
        .SYNOPSIS
        Adds a trusted certificate to an embedded vRealize Orchestrator.

        .DESCRIPTION
        The Add-vROTrustedCertificateOnCEP cmdlet invokes a workflow in vRealize Orchestrator to add trusted certificate.
        The cmdlet connects to SDDC Manager using the -server, -user, and -password values and then:
        - Makes a connection to the embedded vRealize Orchestrator using the -vraUser and -vraPass values.
        - Verifies the workflow exists.
        - Adds the trusted certificate using the -certFile value.

        .EXAMPLE
        Add-CEPTrustedCertificate -extensibilityProxy sfo-vmc-cep01.sfo.rainpole.io -environment staging -apiToken <string> -certFile "C:\Root64.pem"
        This example adds a trusted certificate in PEM-encoded format to the Cloud Extensibility Proxy vRealize Orchestrator instance.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$extensibilityProxy,
        [Parameter (Mandatory = $true)] [ValidateSet("production","staging")] [ValidateNotNullOrEmpty()] [String]$environment="production",
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$apiToken,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$certFile
    )

    $workflowName = "Import a trusted certificate from a file"

    if (!$PsBoundParameters.ContainsKey("certFile")) {
        $certFile = Get-ExternalFileName -title "Select the trusted certificate file (.cer)" -fileType "cer" -location "default"
    } elseif ($PsBoundParameters.ContainsKey("certFile")) {
        if (!(Test-Path -Path $certFile)) {
            Write-Error  "Selecting the trusted certificate file ($certFile), file not found: PRE_VALIDATION_FAILED"
            Break
        }
    }

    Try {
        Request-CSPToken -environment $environment -apiToken $apiToken -extensibilityProxy $extensibilityProxy | Out-Null
        if ($workflow = Get-CEPWorkflow -name $workflowName) {
            $certName = Split-Path -Path "$certFile" -Leaf
            $certContent = [Convert]::ToBase64String([IO.File]::ReadAllBytes("$certFile"))
            $Global:parameters =  
            @"
{"parameters":
    [
        {"value": {
            "mime-attachment": {
                "name":"$certName",
                "content": "$certContent",
                "mime-type": "application/x-x509-ca-cert"}
            },
            "type": "MimeAttachment",
            "name": "cer",
            "scope": "local"
        }
    ]
}
"@

            Invoke-CEPWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters | Out-Null
            $workflowExecution = (Get-CEPWorkflowExecution -name $workflowName | Select-Object -last 1)
            if (Get-CEPWorkflowExecutionState -workflowId $workflow.ID -executionId $workflowExecution.ID | Where-Object { $_.State -ne "failed" }) {
                Do {
                    $workflowStatus = Get-CEPWorkflowExecutionState -workflowId $workflow.ID -executionId $workflowExecution.ID
                } 
                Until ($workflowStatus.State -ne "running")
                if ((Get-CEPWorkflowExecutionState -workflowId $workflow.ID -executionId $workflowExecution.ID) -eq "completed") { 
                    Write-Output "Adding trusted certificate ($certFile) to the vRealize Orchestrator ($($extensibilityProxy)): SUCCESSFUL"
                } else {
                    Write-Error "Adding trusted certificate ($certFile) to the vRealize Orchestrator ($($extensibilityProxy)), check certificate format: POST_VALIDATION_FAILED"
                }
            } else {
                Write-Error "Adding trusted certificate ($certFile) to the vRealize Orchestrator ($($extensibilityProxy)): FAILED"
            }
        } 
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-CEPTrustedCertificate

Function Add-CEPvCenterServer {
    <#
        .SYNOPSIS
        Adds a vCenter Server instance to an embedded vRealize Orchestrator.

        .DESCRIPTION
        The Add-vROvCenterServer cmdlet invokes the workflow in vRealize Orchestrator to add a vCenter Server.
        The cmdlet connects to SDDC Manager using the -server, -user, -password, and -domain values
        to return the workload domain vCenter Server details from its inventory and then:
        - Makes a connection to the Cloud Extensibility Proxy vRealize Orchestrator instance using the -apiToken.
        - Verifies the workflow exists.
        - Adds the vCenter Server instance using the -serviceAccount and -servicePassword values.

        .EXAMPLE
        Add-CEPvCenterServer -server sfo-vcf01.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1! -domain sfo-w01 -apiToken <string> -environment staging -extensibilityProxy sfo-vmc-cep01.sfo.rainpole.io -serviceAccount svc-vro-vsphere@sfo.rainpole.io -servicePassword VMw@re1!
        This example adds the vCenter Server instance from the "sfo-w01" workload domain to the Cloud Extensibility Proxy vRealize Orchestrator instance.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateSet("production","staging")] [ValidateNotNullOrEmpty()] [String]$environment="production",
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$apiToken,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$extensibilityProxy,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$serviceAccount,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$servicePassword
    )

    $workflowName = "Add a vCenter Server instance"

    Try {
        if (Test-VCFConnection -server $server) {
            if (Test-VCFAuthentication -server $server -user $user -pass $pass) {
                if (Get-VCFWorkloadDomain | Where-Object { $_.name -eq $domain }) {
                    $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain          
                    Request-CSPToken -environment $environment -apiToken $apiToken -extensibilityProxy $extensibilityProxy | Out-Null
                    $checkExists = (Invoke-RestMethod -Method 'GET' -URI "https://$cepAppliance/vco/api/catalog/VC" -headers $cspHeader)
                    if ((($checkExists.relations.link.attributes | Where-Object { $_.name -eq "id" }).value) -ne "$($vcenter.fqdn)") {
                        if ($workflow = Get-CEPWorkflow -name $workflowName) {
                            $parameters =  
                            @"
{"parameters":
    [
        {
            "value": {
                "boolean": {
                    "value": true
                }
            },
            "type": "boolean",
            "name": "enabled",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "$($vcenter.fqdn)"
                }
            },
            "type": "string",
            "name": "host",
            "scope": "local"
        },
        {
            "value": {
                "number": {
                    "value": 443
                }
            },
            "type": "number",
            "name": "port",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "/sdk"
                }
            },
            "type": "string",
            "name": "path",
            "scope": "local"
        },
        {
            "value": {
                "boolean": {
                    "value": false
                }
            },
            "type": "boolean",
            "name": "sessionPerUser",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "$serviceAccount"
                }
            },
            "type": "string",
            "name": "userName",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "$servicePassword"
                }
            },
            "type": "string",
            "name": "password",
            "scope": "local"
        },
        {
            "value": {
                "boolean": {
                    "value": true
                }
            },
            "type": "boolean",
            "name": "ignoreCertificateWarnings",
            "scope": "local"
        },
        {
            "value": {
                "number": {
                    "value": 443
                }
            },
            "type": "number",
            "name": "httpPort",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "https://$($vcenter.fqdn):443/pbm"
                }
            },
            "type": "string",
            "name": "pbmUrl",
            "scope": "local"
        },
        {
            "value": {
                "string": {
                    "value": "https://$($vcenter.fqdn):443/sms/sdk"
                }
            },
            "type": "string",
            "name": "smsUrl",
            "scope": "local"
        }
    ]
}
"@

                            Invoke-CEPWorkflow -id $($workflow.ID) -parameters ($parameters | ConvertFrom-Json).parameters | Out-Null
                            $workflowExecution = (Get-CEPWorkflowExecution -name $workflowName | Select-Object -last 1)
                            if (Get-CEPWorkflowExecutionState -workflowId $workflow.ID -executionId $workflowExecution.ID | Where-Object { $_.State -ne "failed" }) { 
                                Do {
                                    $workflowStatus = Get-CEPWorkflowExecutionState -workflowId $workflow.ID -executionId $workflowExecution.ID
                                } 
                                Until ($workflowStatus -ne "running")
                                if ((Get-CEPWorkflowExecutionState -workflowId $workflow.ID -executionId $workflowExecution.ID) -eq "completed") { 
                                    Write-Output "Adding vCenter Server ($($vcenter.fqdn)) to vRealize Orchestrator ($cepAppliance) for Workload Domain ($domain): SUCCESSFUL"
                                }
                                else {
                                    Write-Error "Adding vCenter Server ($($vcenter.fqdn)) to vRealize Orchestrator ($cepAppliance) for Workload Domain ($domain), check credentials: POST_VALIDATION_FAILED"
                                }
                            }
                            else {
                                Write-Error "Adding vCenter Server ($($vcenter.fqdn)) to vRealize Orchestrator ($cepAppliance) for Workload Domain ($domain): FAILED"
                            }
                        }
                        else {
                            Write-Error "Unable to find the workflow named ($workflowName) to vRealize Orcherator ($cepAppliance): PRE_VALIDATION_FAILED"
                        }
                    }
                    else {
                        Write-Warning "Adding vCenter Server ($($vcenter.fqdn)) to vRealize Orchestrator ($cepAppliance) for Workload Domain ($domain), already exists: SKIPPED"
                    }                                
                }
                else {
                    Write-Error "Unable to find Workload Domain named ($domain) in the inventory of SDDC Manager ($server): PRE_VALIDATION_FAILED"
                }
            }
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-CEPvCenterServer

#EndRegion End vRealize Cloud Services Functions ######
#####################################################################

#####################################################################
#Region Start of vSphere Replication Functions ######

Function Request-VrmsToken {
    <#
        .SYNOPSIS
        Connects to the specified vSphere Replication Appliance and obtains an authorization token

        .DESCRIPTION
        The Request-VrmsToken cmdlet connects to the specified vSphere Replication Appliance and obtains an
        authorization token. It is required once per session before running all other cmdlets.

        .EXAMPLE
        Request-VrmsToken -fqdn sfo-m01-vrms01.sfo.rainpole.io -username admin -password VMw@re1!
        This example shows how to connect to the vRealize Suite Lifecycle Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password
    )

    if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) {
        $creds = Get-Credential # Request Credentials
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }

    Try {
        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
        $vrmsBasicHeader = @{"Accept" = "application/json, text/plain, */*" }
        $vrmsBasicHeader.Add("Authorization", "Basic $base64AuthInfo")
        $vrmsBasicHeader.Add("Content-Type", "application/json")
        $Global:vrmsAppliance = $fqdn

        $uri = "https://$vrmsAppliance/api/rest/configure/v1/session"
        if ($PSEdition -eq 'Core') {
            $vrmsResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vrmsBasicHeader -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        } else {
            $vrmsResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $vrmsBasicHeader -UseBasicParsing
        }
        if ($vrmsResponse.StatusCode -eq 200) {
            $Global:vrmsHeader = @{"Accept" = "application/json"}
            $vrmsHeader.Add("Content-Type", "application/json")
            $vrmsHeader.Add("x-dr-session", "$(($vrmsResponse.Content | ConvertFrom-Json).session_id)")
            Write-Output "Successfully connected to the vSphere Replication Appliance: $vrmsAppliance"
        }
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Request-VrmsToken

Function Get-VrmsApplianceDetail {
    <#
        .SYNOPSIS
        Get information about the vSphere Replication Appliance

        .DESCRIPTION
        The Get-VrmsApplianceDetail cmdlet retrives information about the vSphere Replication Appliance.

        .EXAMPLE
        Get-VrmsApplianceDetail
        This example retrives information about the vSphere Replication Appliance
    #>


    Try {
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsApplianceDetail

Function Set-VrmsApplianceState {
    <#
        .SYNOPSIS
        Restart or shutdown the appliance

        .DESCRIPTION
        The Set-VrmsApplianceState cmdlet allows you to restart or shutdown the vSphere Replication appliance.

        .EXAMPLE
        Set-VrmsApplianceState -action restart
        This example restarts the vSphere Replication appliance

        .EXAMPLE
        Set-VrmsApplianceState -action stop
        This example shutsdown the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet('restart','stop')] [String]$action
    )

    Try {
        if ($PsBoundParameters.ContainsKey('action') -eq 'restart') {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/actions/restart"
        } elseif ($PsBoundParameters.ContainsKey('action') -eq 'stop') {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/actions/stop"
        }
        Invoke-RestMethod -Method POST -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Set-VrmsApplianceState

Function Get-VrmsTask {
    <#
        .SYNOPSIS
        Get tasks

        .DESCRIPTION
        The Get-VrmsTask cmdlet retrives the tasks for a vSphere Replication appliance.

        .EXAMPLE
        Get-VrmsTask
        This example retrives all the tasks from the vSphere Replication appliance

        .EXAMPLE
        Get-VrmsTask -taskId <task_id>
        This example retrives a specific task based on the task ID from the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$taskId
    )

    Try {
        if ($PsBoundParameters.ContainsKey('taskId')) {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/tasks/$taskId"
        } else {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/tasks"
        }
        Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsTask

Function Get-VrmsService {
    <#
        .SYNOPSIS
        Get information about vSphere Replication appliance services

        .DESCRIPTION
        The Get-VrmsService cmdlet retrives information about the vSphere Replication appliance services.

        .EXAMPLE
        Get-VrmsService
        This example retrives information about all services on the vSphere Replication appliance

        .EXAMPLE
        Get-VrmsService -serviceId hms
        This example retrives information about hms service on the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateSet('drclient','hbrsrv','hmsdb','hms','telegraf','iperf3','auditd','drrest','drclientplugin')] [String]$serviceId
    )

    Try {
        if ($PsBoundParameters.ContainsKey("serviceId")) {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/services/$serviceId"
            Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader

        } else {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/services"
            (Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader).list
        }
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsService

Function Set-VrmsService {
    <#
        .SYNOPSIS
        Get information about vSphere Replication appliance services

        .DESCRIPTION
        The Set-VrmsService cmdlet retrives information about the vSphere Replication appliance services.

        .EXAMPLE
        Set-VrmsService -serviceId hms -state stop
        This example stops the hms service on the vSphere Replication appliance

        .EXAMPLE
        Set-VrmsService -serviceId hms -state start
        This example starts the hms service on the vSphere Replication appliance

        .EXAMPLE
        Set-VrmsService -serviceId hms -state restart
        This example restarts the hms service on the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet('drclient','hbrsrv','hmsdb','hms','telegraf','iperf3','auditd','drrest','drclientplugin')] [String]$serviceId,
        [Parameter (Mandatory = $true)] [ValidateSet('start','stop','restart')] [String]$state
    )

    Try {
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/services/$serviceId/actions/$state"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Set-VrmsService

Function Get-VrmsNetworkAll {
    <#
        .SYNOPSIS
        Get all network configuration

        .DESCRIPTION
        The Get-VrmsNetworkAll cmdlet retrives all the network configuration of a vSphere Replication appliance.

        .EXAMPLE
        Get-VrmsNetworkAll
        This example retrives all network configuration of the vSphere Replication appliance
    #>


    Try {
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/settings/network"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsNetworkAll

Function Get-VrmsNetworkDns {
    <#
        .SYNOPSIS
        Get DNS configuration

        .DESCRIPTION
        The Get-VrmsNetworkDns cmdlet retrives DNS configuration of a vSphere Replication appliance.

        .EXAMPLE
        Get-VrmsNetworkDns
        This example retrives information about the DNS configuration of the vSphere Replication appliance
    #>


    Try {
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/settings/network/dns"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsNetworkDns

Function Set-VrmsNetworkDns {
    <#
        .SYNOPSIS
        Set DNS configuration

        .DESCRIPTION
        The Set-VrmsNetworkDns cmdlet change the DNS configuration of a vSphere Replication appliance.

        .EXAMPLE
        Set-VrmsNetworkDns -vrmsHostname sfo-m01-vrms01.sfo.rainpole.io -dnsServers "172.18.95.4","172.18.95.5"
        This example retrives information about the DNS configuration of the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vrmsHostname,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$dnsServers
    )

    Try {
        $body = New-Object psobject -Property @{servers = $dnsServers}
        $body | Add-Member -notepropertyname 'hostname' -notepropertyvalue $vrmsHostname
        $body | Add-Member -notepropertyname 'mode' -notepropertyvalue 'STATIC'
        $body = $body | ConvertTo-Json
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/settings/network/dns"
        Invoke-RestMethod -Method PUT -Uri $uri -Headers $vrmsHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Set-VrmsNetworkDns

Function Get-VrmsNetworkInterface {
    <#
        .SYNOPSIS
        Get network interface configuration

        .DESCRIPTION
        The Get-VrmsNetworkInterface cmdlet retrives network interface configuration of a vSphere Replication appliance.

        .EXAMPLE
        Get-VrmsNetworkInterface
        This example retrives information about the network interface configuration of the vSphere Replication appliance
    #>


    Try {
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/settings/network/interfaces"
        (Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader).list
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsNetworkInterface

Function Set-VrmsNetworkInterface {
    <#
        .SYNOPSIS
        Set network interface configuration

        .DESCRIPTION
        The Set-VrmsNetworkInterface cmdlet configures the network interface of a vSphere Replication appliance.

        .EXAMPLE
        Set-VrmsNetworkInterface -interface eth1 -ipAddress 172.18.111.125 -gateway 172.18.111.1 -prefix 24
        This example configures the network interface of the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$interface,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ipAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$gateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefix
    )

    Try {
        $ipv4Object = New-Object -TypeName psobject
        $ipv4Object | Add-Member -notepropertyname 'address' -notepropertyvalue $ipAddress
        $ipv4Object | Add-Member -notepropertyname 'assignment_mode' -notepropertyvalue 'STATIC'
        $ipv4Object | Add-Member -notepropertyname 'default_gateway' -notepropertyvalue $gateway
        $ipv4Object | Add-Member -notepropertyname 'prefix' -notepropertyvalue $prefix
        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'ipv4' -notepropertyvalue $ipv4Object
        $body = $body | ConvertTo-Json
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/settings/network/interfaces/$interface"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $vrmsHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Set-VrmsNetworkInterface

Function Get-VrmsConfiguration {
    <#
        .SYNOPSIS
        Get registration

        .DESCRIPTION
        The Get-VrmsConfiguration cmdlet retrives registration configuration for a vSphere Replication appliance.

        .EXAMPLE
        Get-VrmsConfiguration
        This example retrives the registration configuration for the vSphere Replication appliance

        .EXAMPLE
        Get-VrmsConfiguration -reconfigure
        This example retrives the reconfiguration status for the vSphere Replication appliance

        .EXAMPLE
        Get-VrmsConfiguration -replication
        This example retrives the storage replication configuration for the vSphere Replication appliance
    #>

    
    [CmdletBinding(DefaultParametersetName = 'default')][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $false, ParameterSetName = 'default')]
        [Parameter (Mandatory = $false, ParameterSetName = 'reconfigure')] [ValidateNotNullOrEmpty()] [Switch]$reconfigure,
        [Parameter (Mandatory = $false, ParameterSetName = 'replication')] [ValidateNotNullOrEmpty()] [Switch]$replication
    )

    Try {
        if ($PsBoundParameters.ContainsKey('reconfigure')) {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/configuration-manager/reconfigure-required"
        } elseif ($PsBoundParameters.ContainsKey('replication')) {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/configuration-manager/replication-server-settings"
        } else {
            $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/configuration-manager/configuration"
        }
        Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsConfiguration

Function Set-VrmsConfiguration {
    <#
        .SYNOPSIS
        Set the vCenter Server registration

        .DESCRIPTION
        The Set-VrmsConfiguration cmdlet configures the vCenter Server registration for a vSphere Replication appliance.

        .EXAMPLE
        Set-VrmsConfiguration -vcenterFqdn sfo-m01-vc01.sfo.rainpole.io -vcenterInstanceId 6d6399d4-65ce-4e68-8009-ed8a4735b4a2 -ssoUser administrator@vsphere.local -ssoPassword VMw@re1! -adminEmail vrms-administrator@rainpole.io -siteName SFO-M01
        This example configures the vCenter Server registration with the vSphere Replication appliance
    #>

    
    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterInstanceId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmail,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteName
    )

    Try {
        # $webRequest = [Net.WebRequest]::Create("https://$($vcenterFqdn):443")
        # $webRequest.GetResponse()
        # $certificate = $webRequest.ServicePoint.Certificate
        # $exportCertificate = $certificate.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert)
        # Set-Content -value $exportCertificate -encoding byte -path $ENV:TMP\cert-temp
        # $thumbprint = (Get-FileHash -Path $ENV:TMP\cert-temp -Algorithm SHA256).Hash
        # $thumbprint = $thumbprint -replace '(..(?!$))','$1:'
        $command = 'openssl s_client -connect ' + $vcenterFQDN + ':443 2>&1 | openssl x509 -sha256 -fingerprint -noout'
        $thumbprint = (Invoke-Expression "& $command").Split("=")[1]

        $connectionObject = New-Object -TypeName psobject
        $connectionObject | Add-Member -notepropertyname 'psc_thumbprint' -notepropertyvalue $thumbprint
        $connectionObject | Add-Member -notepropertyname 'psc_uri' -notepropertyvalue ($vcenterFqdn + ":443")
        $connectionObject | Add-Member -notepropertyname 'vc_instance_id' -notepropertyvalue $vcenterInstanceId
        $connectionObject | Add-Member -notepropertyname 'vc_thumbprint' -notepropertyvalue $thumbprint

        $credentialsObject = New-Object -TypeName psobject
        $credentialsObject | Add-Member -notepropertyname 'admin_password' -notepropertyvalue $ssoPassword
        $credentialsObject | Add-Member -notepropertyname 'admin_user' -notepropertyvalue $ssoUser

        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'admin_email' -notepropertyvalue $adminEmail
        $body | Add-Member -notepropertyname 'extension_key' -notepropertyvalue "com.vmware.vcHms"
        $body | Add-Member -notepropertyname 'host_name' -notepropertyvalue $vrmsAppliance
        $body | Add-Member -notepropertyname 'site_name' -notepropertyvalue $siteName
        $body | Add-Member -notepropertyname 'connection' -notepropertyvalue $connectionObject
        $body | Add-Member -notepropertyname 'credentials' -notepropertyvalue $credentialsObject
        $body = $body | ConvertTo-Json

        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/configuration-manager/configuration"
        Invoke-RestMethod -Method PUT -Uri $uri -Headers $vrmsHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Set-VrmsConfiguration

Function Remove-VrmsConfiguration {
    <#
        .SYNOPSIS
        Remove the configuration

        .DESCRIPTION
        The Remove-VrmsConfiguration cmdlet removes the vCenter Server registration for a vSphere Replication appliance.

        .EXAMPLE
        Remove-VrmsConfiguration -ssoUser administrator@vsphere.local -ssoPassword VMw@re1!
        This example removes the vCenter Server registration for the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoPassword
    )

    Try {
        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'admin_password' -notepropertyvalue $ssoPassword
        $body | Add-Member -notepropertyname 'admin_user' -notepropertyvalue $ssoUser
        $body = $body | ConvertTo-Json
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/configuration-manager/configuration/actions/remove"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $vrmsHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Remove-VrmsConfiguration

Function Set-VrmsReplication {
    <#
        .SYNOPSIS
        Set the replication server settings

        .DESCRIPTION
        The Set-VrmsReplication cmdlet configures the replication server settings for a vSphere Replication appliance.

        .EXAMPLE
        Set-VrmsReplication -filterIp 172.18.111.125 -managementIp 172.18.95.125
        This example configures the vCenter Server registration with the vSphere Replication appliance
    #>

    
    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$filterIp,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$managementIp
    )

    Try {
        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'filter_ip' -notepropertyvalue $filterIp
        $body | Add-Member -notepropertyname 'management_ip' -notepropertyvalue $managementIp
        $body = $body | ConvertTo-Json
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/configuration-manager/replication-server-settings"
        Invoke-RestMethod -Method PUT -Uri $uri -Headers $vrmsHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Set-VrmsReplication

Function Get-VrmsVamiCertificate {
    <#
        .SYNOPSIS
        Get the certificate of the VAMI Appliance interface

        .DESCRIPTION
        The Get-VrmsConfiguration cmdlet retrives the certificate of the VAMI interface of a vSphere Replication appliance.

        .EXAMPLE
        Get-VrmsConfiguration
        This example retrives the registration configuration for the vSphere Replication appliance
    #>


    Try {
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/certificates/server"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $vrmsHeader
    } Catch {
        internalCatchWriter -applianceName "vSphere Replication Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Get-VrmsVamiCertificate

Function Set-VrmsVamiCertificate {
    <#
        .SYNOPSIS
        Install a Signed Certificate for the VAMI Appliance interface

        .DESCRIPTION
        The Set-VrmsVamiCertificate cmdlet replaces the certificate on the VAMI interface of the vSphere
        Replication appliance.

        .EXAMPLE
        Set-VrmsVamiCertificate -pkcs12CertFile C:\Certs\sfo-m01-vrms01.4.p12 -certPassword VMw@re1!
        This example replaces the certificate on the VAMI Appliance interface of the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pkcs12CertFile,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certPassword
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("pkcs12CertFile")) {
            $pkcs12CertFile = Get-ExternalFileName -title "Select the Appliance Certificate File (.p12)" -fileType
        } elseif ($PsBoundParameters.ContainsKey("pkcs12CertFile")) {
            if (!(Test-Path -Path $pkcs12CertFile)) {
                Write-Error  "Certificate (.p12) '$pkcs12CertFile' File Not Found"
            }
        }

        $certContent = [Convert]::ToBase64String([IO.File]::ReadAllBytes($pkcs12CertFile))
        $pkcs12Object = New-Object -TypeName psobject
        $pkcs12Object | Add-Member -notepropertyname 'certificate' -notepropertyvalue $certContent
        $pkcs12Object | Add-Member -notepropertyname 'password' -notepropertyvalue $certPassword
        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'pkcs12_format' -notepropertyvalue $pkcs12Object
        $body = $body | ConvertTo-Json
        $uri = "https://$vrmsAppliance/api/rest/configure/v1/appliance/certificates/server"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $vrmsHeader -Body $body
        Set-VrmsApplianceState -action restart | Out-Null
    } Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Set-VrmsVamiCertificate

#EndRegion End of vSphere Replication Functions ######
#####################################################################

#####################################################################
#Region Start of Site Recovery Manager Functions ######

Function Request-SrmToken {
    <#
        .SYNOPSIS
        Connects to the specified Site Recovery Manager Appliance and obtains an authorization token

        .DESCRIPTION
        The Request-SrmToken cmdlet connects to the specified Site Recovery Manager and obtains an authorization
        token. It is required once per session before running all other cmdlets.

        .EXAMPLE
        Request-SrmToken -fqdn sfo-m01-srm01.sfo.rainpole.io -username admin -password VMw@re1!
        This example shows how to connect to the vRealize Suite Lifecycle Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$password
    )

    if ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) {
        $creds = Get-Credential # Request Credentials
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }

    Try {
        $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
        $srmBasicHeader = @{"Accept" = "application/json, text/plain, */*" }
        $srmBasicHeader.Add("Authorization", "Basic $base64AuthInfo")
        $srmBasicHeader.Add("Content-Type", "application/json")
        $Global:srmAppliance = $fqdn

        $uri = "https://$srmAppliance/api/rest/configure/v1/session"
        if ($PSEdition -eq 'Core') {
            $srmResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $srmBasicHeader -SkipCertificateCheck -UseBasicParsing # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
        }
        else {
            $srmResponse = Invoke-WebRequest -Method POST -Uri $uri -Headers $srmBasicHeader -UseBasicParsing
        }
        if ($srmResponse.StatusCode -eq 200) {
            $Global:srmHeader = @{"Accept" = "application/json"}
            $srmHeader.Add("Content-Type", "application/json")
            $srmHeader.Add("x-dr-session", "$(($srmResponse.Content | ConvertFrom-Json).session_id)")
            Write-Output "Successfully connected to the Site Recovery Manager Appliance: $srmAppliance"
        }
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Request-SrmToken

Function Get-SrmApplianceDetail {
    <#
        .SYNOPSIS
        Get information about the Site Recovery Manager Appliance

        .DESCRIPTION
        The Get-SrmApplianceDetail cmdlet retrives information about the Site Recovery Manager Appliance.

        .EXAMPLE
        Get-SrmApplianceDetail
        This example retrives information about the Site Recovery Manager Appliance
    #>


    Try {
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmApplianceDetail

Function Set-SrmApplianceState {
    <#
        .SYNOPSIS
        Restart or shutdown the appliance

        .DESCRIPTION
        The Set-SrmApplianceState cmdlet allows you to restart or shutdown the Site Recovery Manager appliance.

        .EXAMPLE
        Set-SrmApplianceState -action restart
        This example restarts the Site Recovery Manager appliance

        .EXAMPLE
        Set-SrmApplianceState -action stop
        This example shutsdown the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet('restart','stop')] [String]$action
    )

    Try {
        if ($PsBoundParameters.ContainsKey('action') -eq 'restart') {
            $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/actions/restart"
        } elseif ($PsBoundParameters.ContainsKey('action') -eq 'stop') {
            $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/actions/stop"
        }
        Invoke-RestMethod -Method POST -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Set-SrmApplianceState

Function Get-SrmTask {
    <#
        .SYNOPSIS
        Get tasks

        .DESCRIPTION
        The Get-SrmTask cmdlet retrives the tasks for a Site Recovery Manager appliance.

        .EXAMPLE
        Get-SrmTask
        This example retrives all the tasks from the Site Recovery Manager appliance

        .EXAMPLE
        Get-SrmTask -taskId <task_id>
        This example retrives a specific task based on the task ID from the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$taskId
    )

    Try {
        if ($PsBoundParameters.ContainsKey('taskId')) {
            $uri = "https://$srmAppliance/api/rest/configure/v1/tasks/$taskId"
        } else {
            $uri = "https://$srmAppliance/api/rest/configure/v1/tasks"
        }
        Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmTask

Function Get-SrmService {
    <#
        .SYNOPSIS
        Get information about Site Recovery Manager appliance services

        .DESCRIPTION
        The Get-SrmService cmdlet retrives information about the Site Recovery Manager appliance services.

        .EXAMPLE
        Get-SrmService
        This example retrives information about all services on the Site Recovery Manager appliance

        .EXAMPLE
        Get-SrmService -serviceId hms
        This example retrives information about hms service on the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateSet('srm','db','drclient','telegraf','iperf3','auditd','drrest','drclientplugin')] [String]$serviceId
    )

    Try {
        if ($PsBoundParameters.ContainsKey("serviceId")) {
            $uri = "https://$srmAppliance/api/rest/configure/v1/services/$serviceId"
            Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader

        } else {
            $uri = "https://$srmAppliance/api/rest/configure/v1/services"
            (Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader).list
        }
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmService

Function Set-SrmService {
    <#
        .SYNOPSIS
        Get information about Site Recovery Manager appliance services

        .DESCRIPTION
        The Set-SrmService cmdlet retrives information about the Site Recovery Manager appliance services.

        .EXAMPLE
        Set-SrmService -serviceId srm -state stop
        This example stops the hms service on the Site Recovery Manager appliance

        .EXAMPLE
        Set-SrmService -serviceId srm -state start
        This example starts the hms service on the Site Recovery Manager appliance

        .EXAMPLE
        Set-SrmService -serviceId srm -state restart
        This example restarts the hms service on the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateSet('srm','db','drclient','telegraf','iperf3','auditd','drrest','drclientplugin')] [String]$serviceId,
        [Parameter (Mandatory = $true)] [ValidateSet('start','stop','restart')] [String]$state
    )

    Try {
        $uri = "https://$srmAppliance/api/rest/configure/v1/services/$serviceId/actions/$state"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Set-SrmService

Function Get-SrmNetworkAll {
    <#
        .SYNOPSIS
        Get all network configuration

        .DESCRIPTION
        The Get-SrmNetworkAll cmdlet retrives all the network configuration of a Site Recovery Manager appliance.

        .EXAMPLE
        Get-SrmNetworkAll
        This example retrives all network configuration of the Site Recovery Manager appliance
    #>


    Try {
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/settings/network"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmNetworkAll

Function Get-SrmNetworkDns {
    <#
        .SYNOPSIS
        Get DNS configuration

        .DESCRIPTION
        The Get-SrmNetworkDns cmdlet retrives DNS configuration of a Site Recovery Manager appliance.

        .EXAMPLE
        Get-SrmNetworkDns
        This example retrives information about the DNS configuration of the Site Recovery Manager appliance
    #>


    Try {
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/settings/network/dns"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmNetworkDns

Function Set-SrmNetworkDns {
    <#
        .SYNOPSIS
        Set DNS configuration

        .DESCRIPTION
        The Set-SrmNetworkDns cmdlet change the DNS configuration of a Site Recovery Manager appliance.

        .EXAMPLE
        Set-SrmNetworkDns -srmHostname sfo-m01-srm01.sfo.rainpole.io -dnsServers "172.18.95.4","172.18.95.5"
        This example retrives information about the DNS configuration of the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmHostname,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$dnsServers
    )

    Try {
        $body = New-Object psobject -Property @{servers = $dnsServers}
        $body | Add-Member -notepropertyname 'hostname' -notepropertyvalue $srmHostname
        $body | Add-Member -notepropertyname 'mode' -notepropertyvalue 'STATIC'
        $body = $body | ConvertTo-Json
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/settings/network/dns"
        Invoke-RestMethod -Method PUT -Uri $uri -Headers $srmHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Set-SrmNetworkDns

Function Get-SrmNetworkInterface {
    <#
        .SYNOPSIS
        Get network interface configuration

        .DESCRIPTION
        The Get-SrmNetworkInterface cmdlet retrives network interface configuration of a Site Recovery Manager appliance.

        .EXAMPLE
        Get-SrmNetworkInterface
        This example retrives information about the network interface configuration of the Site Recovery Manager appliance
    #>


    Try {
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/settings/network/interfaces"
        (Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader).list
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmNetworkInterface

Function Set-SrmNetworkInterface {
    <#
        .SYNOPSIS
        Set network interface configuration

        .DESCRIPTION
        The Set-SrmNetworkInterface cmdlet configures the network interface of a Site Recovery Manager appliance.

        .EXAMPLE
        Set-SrmNetworkInterface -interface eth0 -ipAddress 172.18.95.126 -gateway 172.18.95.1 -prefix 24
        This example configures the network interface of the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$interface,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ipAddress,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$gateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$prefix
    )

    Try {
        $ipv4Object = New-Object -TypeName psobject
        $ipv4Object | Add-Member -notepropertyname 'address' -notepropertyvalue $ipAddress
        $ipv4Object | Add-Member -notepropertyname 'assignment_mode' -notepropertyvalue 'STATIC'
        $ipv4Object | Add-Member -notepropertyname 'default_gateway' -notepropertyvalue $gateway
        $ipv4Object | Add-Member -notepropertyname 'prefix' -notepropertyvalue $prefix
        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'ipv4' -notepropertyvalue $ipv4Object
        $body = $body | ConvertTo-Json
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/settings/network/interfaces/$interface"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $srmHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Set-SrmNetworkInterface

Function Get-SrmConfiguration {
    <#
        .SYNOPSIS
        Get registration

        .DESCRIPTION
        The Get-SrmConfiguration cmdlet retrives registration configuration for a Site Recovery Manager appliance.

        .EXAMPLE
        Get-SrmConfiguration
        This example retrives the registration configuration for the Site Recovery Manager appliance

        .EXAMPLE
        Get-SrmConfiguration -reconfigure
        This example retrives the reconfiguration status for the Site Recovery Manager appliance
    #>

    
    [CmdletBinding(DefaultParametersetName = 'default')][OutputType('System.Management.Automation.PSObject')]

    Param (
        [Parameter (Mandatory = $false, ParameterSetName = 'default')]
        [Parameter (Mandatory = $false, ParameterSetName = 'reconfigure')] [ValidateNotNullOrEmpty()] [Switch]$reconfigure
    )

    Try {
        if ($PsBoundParameters.ContainsKey('reconfigure')) {
            $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/configuration-manager/reconfigure-required"
        } else {
            $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/configuration-manager/configuration"
        }
        Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmConfiguration

Function Set-SrmConfiguration {
    <#
        .SYNOPSIS
        Set the vCenter Server registration

        .DESCRIPTION
        The Set-SrmConfiguration cmdlet configures the vCenter Server registration for a Site Recovery Manager appliance.

        .EXAMPLE
        Set-SrmConfiguration -vcenterFqdn sfo-m01-vc01.sfo.rainpole.io -vcenterInstanceId 6d6399d4-65ce-4e68-8009-ed8a4735b4a2 -ssoUser administrator@vsphere.local -ssoPassword VMw@re1! -adminEmail srm-administrator@rainpole.io -siteName SFO-M01
        This example configures the vCenter Server registration with the vSphere Replication appliance
    #>

    
    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcenterInstanceId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmail,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteName
    )

    Try {
        # $webRequest = [Net.WebRequest]::Create("https://$($vcenterFqdn):443")
        # $webRequest.GetResponse() | Out-Null
        # $certificate = $webRequest.ServicePoint.Certificate
        # $exportCertificate = $certificate.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert)
        # Set-Content -value $exportCertificate -encoding byte -path $ENV:TMP\cert-temp
        # $thumbprint = (Get-FileHash -Path $ENV:TMP\cert-temp -Algorithm SHA256).Hash
        # $thumbprint = $thumbprint -replace '(..(?!$))','$1:'
        $command = 'openssl s_client -connect ' + $vcenterFQDN + ':443 2>&1 | openssl x509 -sha256 -fingerprint -noout'
        $thumbprint = (Invoke-Expression "& $command").Split("=")[1]

        $connectionObject = New-Object -TypeName psobject
        $connectionObject | Add-Member -notepropertyname 'psc_thumbprint' -notepropertyvalue $thumbprint
        $connectionObject | Add-Member -notepropertyname 'psc_uri' -notepropertyvalue ($vcenterFqdn + ":443")
        $connectionObject | Add-Member -notepropertyname 'vc_instance_id' -notepropertyvalue $vcenterInstanceId
        $connectionObject | Add-Member -notepropertyname 'vc_thumbprint' -notepropertyvalue $thumbprint

        $credentialsObject = New-Object -TypeName psobject
        $credentialsObject | Add-Member -notepropertyname 'admin_password' -notepropertyvalue $ssoPassword
        $credentialsObject | Add-Member -notepropertyname 'admin_user' -notepropertyvalue $ssoUser

        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'admin_email' -notepropertyvalue $adminEmail
        $body | Add-Member -notepropertyname 'extension_key' -notepropertyvalue "com.vmware.vcDr"
        $body | Add-Member -notepropertyname 'host_name' -notepropertyvalue $srmAppliance
        $body | Add-Member -notepropertyname 'site_name' -notepropertyvalue $siteName
        $body | Add-Member -notepropertyname 'connection' -notepropertyvalue $connectionObject
        $body | Add-Member -notepropertyname 'credentials' -notepropertyvalue $credentialsObject
        $body = $body | ConvertTo-Json

        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/configuration-manager/configuration"
        Invoke-RestMethod -Method PUT -Uri $uri -Headers $srmHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Set-SrmConfiguration

Function Remove-SrmConfiguration {
    <#
        .SYNOPSIS
        Remove the configuration

        .DESCRIPTION
        The Remove-SrmConfiguration cmdlet removes the vCenter Server registration for a vSphere Replication appliance.

        .EXAMPLE
        Remove-SrmConfiguration -ssoUser administrator@vsphere.local -ssoPassword VMw@re1!
        This example removes the vCenter Server registration for the vSphere Replication appliance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoPassword
    )

    Try {
        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'admin_password' -notepropertyvalue $ssoPassword
        $body | Add-Member -notepropertyname 'admin_user' -notepropertyvalue $ssoUser
        $body = $body | ConvertTo-Json
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/configuration-manager/configuration/actions/remove"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $srmHeader -Body $body
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $vrmsAppliance
    }
}
Export-ModuleMember -Function Remove-SrmConfiguration

Function Get-SrmVamiCertificate {
    <#
        .SYNOPSIS
        Get the certificate of the VAMI Appliance interface

        .DESCRIPTION
        The Get-SrmVamiCertificate cmdlet retrives the certificate of the VAMI interface of a Site Recovery Manager appliance.

        .EXAMPLE
        Get-SrmVamiCertificate
        This example retrives the registration configuration for the Site Recovery Manager appliance
    #>


    Try {
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/certificates/server"
        Invoke-RestMethod -Method GET -Uri $uri -Headers $srmHeader
    } Catch {
        internalCatchWriter -applianceName "Site Recovery Manager Appliance" -applianceFqdn $srmAppliance
    }
}
Export-ModuleMember -Function Get-SrmVamiCertificate

Function Set-SrmVamiCertificate {
    <#
        .SYNOPSIS
        Install a Signed Certificate for the VAMI Appliance interface

        .DESCRIPTION
        The Set-SrmVamiCertificate cmdlet replaces the certificate on the VAMI interface of the Site Recovery
        Manager appliance.

        .EXAMPLE
        Set-SrmVamiCertificate -pkcs12CertFile C:\Certs\sfo-m01-srm01.4.p12 -certPassword VMw@re1!
        This example replaces the certificate on the VAMI Appliance interface of the Site Recovery Manager appliance
    #>


    Param (
        [Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pkcs12CertFile,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$certPassword
    )

    Try {
        if (!$PsBoundParameters.ContainsKey("pkcs12CertFile")) {
            $pkcs12CertFile = Get-ExternalFileName -title "Select the Appliance Certificate File (.p12)" -fileType
        } elseif ($PsBoundParameters.ContainsKey("pkcs12CertFile")) {
            if (!(Test-Path -Path $pkcs12CertFile)) {
                Write-Error  "Certificate (.p12) '$pkcs12CertFile' File Not Found"
            }
        }

        $certContent = [Convert]::ToBase64String([IO.File]::ReadAllBytes($pkcs12CertFile))
        $pkcs12Object = New-Object -TypeName psobject
        $pkcs12Object | Add-Member -notepropertyname 'certificate' -notepropertyvalue $certContent
        $pkcs12Object | Add-Member -notepropertyname 'password' -notepropertyvalue $certPassword
        $body = New-Object -TypeName psobject
        $body | Add-Member -notepropertyname 'pkcs12_format' -notepropertyvalue $pkcs12Object
        $body = $body | ConvertTo-Json
        $uri = "https://$srmAppliance/api/rest/configure/v1/appliance/certificates/server"
        Invoke-RestMethod -Method POST -Uri $uri -Headers $srmHeader -Body $body
        Set-SrmApplianceState -action restart | Out-Null
    } Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Set-SrmVamiCertificate

#EndRegion End of Site Recovery Manager Functions ######
#####################################################################

#####################################################################
#Region Start Utility Functions ######

Function internalCatchWriter ($applianceName, $applianceFqdn) {
    if ($_.Exception.Message -match "400") {
        Write-Error "400 (Bad Request: ($_.Exception.ErrorLabel)"
    } elseif ($_.Exception.Message -match "401") {
        Write-Error "401 (Unauthorized: Not Connected to $($applianceName): $($applianceFqdn))"
    } elseif ($_.Exception.Message -match "403") {
        Write-Error "403 (Forbidden on $($applianceName): $($applianceFqdn))"
    } elseif ($_.Exception.Message -match "404") {
        Write-Error "404 (Resouce Not Found on $($applianceName): $($applianceFqdn))"
    } elseif ($_.Exception.Message -match "409") {
        Write-Error "409 (Conflict: $_.Exception.ErrorLabel"
    } elseif ($_.Exception.Message -match "500") {
        Write-Error "500 (Internal Server Error: $_.Exception.ErrorLabel"
    } elseif ($_.Exception.Message -match "Cannot bind parameter 'Uri'") {
        Write-Error "Missing Access Token (Request an access token for the $($applianceName) to continue)"
    } else {
        Write-Error $_.Exception.Message
    }
}

Function Debug-ExceptionWriter {
    Param (
        [Parameter(Mandatory = $true)]
        [PSObject]$object
    )

    $lineNumber = $object.InvocationInfo.ScriptLineNumber
    $lineText = $object.InvocationInfo.Line.trim()
    $errorMessage = $object.Exception.Message
    Write-Output " Error at Script Line $lineNumber"
    Write-Output " Relevant Command: $lineText"
    Write-Output " Error Message: $errorMessage"
}
Export-ModuleMember -Function Debug-ExceptionWriter

Function Get-ExternalFileName ($title, $fileType, $location) {
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.Title = "$title"
    if ($location -eq "default") {
        $OpenFileDialog.initialDirectory = Get-Location
    }
    else {
        $OpenFileDialog.initialDirectory = $location
    }
    $OpenFileDialog.filter = "All files (*.$fileType) | *.$fileType"
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.filename
}

Function Get-ExternalDirectoryPath {
    Add-Type -AssemblyName System.Windows.Forms
    $directory = New-Object System.Windows.Forms.FolderBrowserDialog
    $null = $directory.ShowDialog()
    $directoryPath = $directory.SelectedPath
    $directoryPath
}

Function cidrMaskLookup {
    Param (
        [Parameter (Mandatory = $true)][ValidateSet("mask", "cidr")] [String]$source,  
        [Parameter (Mandatory = $true)] [String]$value
    )

    $subnetMasks = @(
        ($32 = @{ cidr = "32"; mask = "255.255.255.255" }),
        ($31 = @{ cidr = "31"; mask = "255.255.255.254" }),
        ($30 = @{ cidr = "30"; mask = "255.255.255.252" }),
        ($29 = @{ cidr = "29"; mask = "255.255.255.248" }),
        ($28 = @{ cidr = "28"; mask = "255.255.255.240" }),
        ($27 = @{ cidr = "27"; mask = "255.255.255.224" }),
        ($26 = @{ cidr = "26"; mask = "255.255.255.192" }),
        ($25 = @{ cidr = "25"; mask = "255.255.255.128" }),
        ($24 = @{ cidr = "24"; mask = "255.255.255.0" }),
        ($23 = @{ cidr = "23"; mask = "255.255.254.0" }),
        ($22 = @{ cidr = "22"; mask = "255.255.252.0" }),
        ($21 = @{ cidr = "21"; mask = "255.255.248.0" }),
        ($20 = @{ cidr = "20"; mask = "255.255.240.0" }),
        ($19 = @{ cidr = "19"; mask = "255.255.224.0" }),
        ($18 = @{ cidr = "18"; mask = "255.255.192.0" }),
        ($17 = @{ cidr = "17"; mask = "255.255.128.0" }),
        ($16 = @{ cidr = "16"; mask = "255.255.0.0" }),
        ($15 = @{ cidr = "15"; mask = "255.254.0.0" }),
        ($14 = @{ cidr = "14"; mask = "255.252.0.0" }),
        ($13 = @{ cidr = "13"; mask = "255.248.0.0" }),
        ($12 = @{ cidr = "12"; mask = "255.240.0.0" }),
        ($11 = @{ cidr = "11"; mask = "255.224.0.0" }),
        ($10 = @{ cidr = "10"; mask = "255.192.0.0" }),
        ($9 = @{ cidr = "9"; mask = "255.128.0.0" }),
        ($8 = @{ cidr = "8"; mask = "255.0.0.0" }),
        ($7 = @{ cidr = "7"; mask = "254.0.0.0" }),
        ($6 = @{ cidr = "6"; mask = "252.0.0.0" }),
        ($5 = @{ cidr = "5"; mask = "248.0.0.0" }),
        ($4 = @{ cidr = "4"; mask = "240.0.0.0" }),
        ($3 = @{ cidr = "3"; mask = "224.0.0.0" }),
        ($2 = @{ cidr = "2"; mask = "192.0.0.0" }),
        ($1 = @{ cidr = "1"; mask = "128.0.0.0" }),
        ($0 = @{ cidr = "0"; mask = "0.0.0.0" })            
    )
    If ($source -eq "Mask")
    {
        $found = $subnetMasks | Where-Object { $_.'mask' -eq $value }
        $returnValue = $found.cidr
    }
    else
    {
        $found = $subnetMasks | Where-Object { $_.'cidr' -eq $value }
        $returnValue = $found.mask
    }   
    Return $returnValue
}

Function createHeader {
    $Global:headers = @{"Accept" = "application/json" }
    $Global:headers.Add("Authorization", "Bearer $accessToken")
}

Function createBasicAuthHeader {
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password))) # Create Basic Authentication Encoded Credentials
    $headers = @{"Accept" = "application/json" }
    $headers.Add("Authorization", "Basic $base64AuthInfo")
    $headers.Add("Content-Type", "application/json")
    $headers
}

Function createvCenterAuthHeader {
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
    $vcAuthHeaders = @{"vmware-use-header-authn" = "true" }
    $vcAuthHeaders.Add("Authorization", "Basic $base64AuthInfo")
    $vcAuthHeaders
}

Function createGitHubAuthHeader {
    # Get the headers with authorization to pull content pack from the GitHub repository
    # Note: Uses the same token used by vRealize Log Insight's in-product Marketplace as seen in Chrome Developer Tools
    $ghToken = 'bGktbWFya2V0cGxhY2U6Y2UzYjBkODFjYzczMTJhZjk5ZDYzMjFjZDlkMTUzOTc4ZjZlZjM2NQ=='
    $Global:ghHeaders = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]'
    $ghHeaders.Add('Accept', 'application/vnd.github.VERSION.raw')
    $ghHeaders.Add('Authorization', "Basic $ghToken")
}

#EndRegion End Utility Functions ######
#####################################################################

#####################################################################
#Region Start of Test Functions ######

Function Test-VCFConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vcfConnection = $True
        Return $vcfConnection
    }   
    else { 
        Write-Error "Unable to communicate with SDDC Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vcfConnection = $False
        Return $vcfConnection
    }
}
Export-ModuleMember -Function Test-VCFConnection

Function Test-VCFAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Item variable:accessToken -Force -Confirm:$false -ErrorAction Ignore

    Request-VCFToken -fqdn $server -Username $user -Password $pass -skipCertificateCheck -ErrorAction SilentlyContinue -ErrorVariable ErrMsg | Out-Null
    if ($accessToken) {
        $vcfAuthentication = $True
        Return $vcfAuthentication
    }   
    else {
        Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials: PRE_VALIDATION_FAILED"
        $vcfAuthentication = $False
        Return $vcfAuthentication
    }
}
Export-ModuleMember -Function Test-VCFAuthentication

Function Test-VsphereConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vsphereConnection = $True
        Return $vsphereConnection
    }   
    else { 
        Write-Error "Unable to communicate with vCenter Server ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vsphereConnection = $False
        Return $vsphereConnection
    }
}
Export-ModuleMember -Function Test-VsphereConnection

Function Test-VsphereAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        Connect-VIServer -Server $server -User $user -pass $pass | Out-Null
        if ($DefaultVIServer.Name -eq $server) {
            $vsphereAuthentication = $True
            Return $vsphereAuthentication
        }   
        else {
            Write-Error "Unable to authenticate to vCenter Server ($server), check credentials: PRE_VALIDATION_FAILED"
            $vsphereAuthentication = $False
            Return $vsphereAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-VsphereAuthentication

Function Test-SSOConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $ssoConnection = $True
        Return $ssoConnection
    }   
    else { 
        Write-Error "Unable to communicate with Single-Sign On Server ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $ssoConnection = $False
        Return $ssoConnection
    }
}
Export-ModuleMember -Function Test-SSOConnection

Function Test-SSOAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Try {
        $Script:ssoConnectionDetail = Connect-SsoAdminServer -Server $server -User $user -Password $pass
        if ($DefaultSsoAdminServers.Name -eq $server) {
            $ssoAuthentication = $True
            Return $ssoAuthentication
        }   
        else {
            Write-Error "Unable to authenticate to Single-Sign-On Server ($server), check credentials: PRE_VALIDATION_FAILED"
            $ssoAuthentication = $False
            Return $ssoAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-SSOAuthentication

Function Test-vSphereApiConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vSphereApiConnection = $True
        Return $vSphereApiConnection
    }   
    else { 
        Write-Error "Unable to communicate with vSphere API Endpoint ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vSphereApiConnection = $False
        Return $vSphereApiConnection
    }
}
Export-ModuleMember -Function Test-vSphereApiConnection

Function Test-vSphereApiAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [Switch]$admin
    )

    Try {
        if ($PsBoundParameters.ContainsKey("admin")) {
            $response = Request-vSphereApiToken -fqdn $server -username $user -password $pass -admin
        }
        else {
            $response = Request-vSphereApiToken -fqdn $server -username $user -password $pass
        }
        if ($response -match "Successfully Requested") {
            $vSphereApiAuthentication = $True
            Return $vSphereApiAuthentication
        }   
        else {
            Write-Error "Unable to authenticate to vSphere API Endpoint ($server), check credentials: PRE_VALIDATION_FAILED"
            $vSphereApiAuthentication = $False
            Return $vSphereApiAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-vSphereApiAuthentication

Function Test-NSXTConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $nsxtConnection = $True
        Return $nsxtConnection
    }   
    else { 
        Write-Error "Unable to communicate with NSX Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $nsxtConnection = $False
        Return $nsxtConnection
    }
}
Export-ModuleMember -Function Test-NSXTConnection

Function Test-NSXTAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Item variable:nsxtHeaders -Force -Confirm:$false -ErrorAction Ignore

    Try {
        $response = Request-NsxtToken -fqdn $server -username $user -password $pass -skipCertificateCheck
        if ($response -match "Successfully Requested") {
            $nsxtAuthentication = $True
            Return $nsxtAuthentication
        }   
        else {
            Write-Error "Unable to obtain access token from NSX Manager ($server), check credentials: PRE_VALIDATION_FAILED"
            $nsxtAuthentication = $False
            Return $nsxtAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-NSXTAuthentication

Function Test-vRSLCMConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vrslcmConnection = $True
        Return $vrslcmConnection
    }   
    else { 
        Write-Error "Unable to communicate with vRealize Suite Lifecycle Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vrslcmConnection = $False
        Return $vrslcmConnection
    }
}
Export-ModuleMember -Function Test-vRSLCMConnection

Function Test-vRSLCMAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Item variable:vrslcmHeaders -Force -Confirm:$false -ErrorAction Ignore

    Try {
        Request-vRSLCMToken -fqdn $server -username $user -password $pass -ErrorAction Ignore -ErrorVariable ErrMsg | Out-Null
        if ((Get-vRSLCMHealth).'vrlcm-server' -eq "UP") {
            $vrslcmAuthentication = $True
            Return $vrslcmAuthentication
        }   
        else {
            Write-Error "Unable to obtain access token from vRealize Suite Lifecycle Manager ($server), check credentials: PRE_VALIDATION_FAILED"
            $vrslcmAuthentication = $False
            Return $vrslcmAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-vRSLCMAuthentication

Function Test-vROPSConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vropsConnection = $True
        Return $vropsConnection
    }   
    else { 
        Write-Error "Unable to communicate with vRealize Operations Manager ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vropsConnection = $False
        Return $vropsConnection
    }
}
Export-ModuleMember -Function Test-vROPSConnection

Function Test-vROPSAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Item variable:vropsHeaders -Force -Confirm:$false -ErrorAction Ignore

    Try {
        Request-vROPSToken -fqdn $server -username $user -password $pass | Out-Null
        if ($vropsHeaders.Authorization) {
            $vropsAuthentication = $True
            Return $vropsAuthentication
        }   
        else {
            Write-Error "Unable to obtain access token from vRealize Operations Manager ($server), check credentials: PRE_VALIDATION_FAILED"
            $vropsAuthentication = $False
            Return $vropsAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-vROPSAuthentication

Function Test-vRLIConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vrliConnection = $True
        Return $vrliConnection
    }   
    else { 
        Write-Error "Unable to communicate with vRelize Log Insight ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vrliConnection = $False
        Return $vrliConnection
    }
}
Export-ModuleMember -Function Test-vRLIConnection

Function Test-vRLIAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Item variable:vrliHeaders -Force -Confirm:$false -ErrorAction Ignore

    Try {
        Request-vRLIToken -fqdn $server -Username $user -Password $pass -ErrorAction Ignore -ErrorVariable ErrMsg | Out-Null
        if ($vrliHeaders.Authorization) {
            $vrliAuthentication = $True
            Return $vrliAuthentication
        }   
        else {
            Write-Error "Unable to obtain access token from vRealize Log Insight ($server), check credentials: PRE_VALIDATION_FAILED"
            $vrliAuthentication = $False
            Return $vrliAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-vRLIAuthentication

Function Test-vRAConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vraConnection = $True
        Return $vraConnection
    }   
    else { 
        Write-Error "Unable to communicate with vRelize Automation ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vraConnection = $False
        Return $vraConnection
    }
}
Export-ModuleMember -Function Test-vRAConnection

Function Test-vRAAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Item variable:vraHeaders -Force -Confirm:$false -ErrorAction Ignore

    Try {
        Request-vRAToken -fqdn $server -Username $user -Password $pass | Out-Null
        if ($vraHeaders.Authorization) {
            $vraAuthentication = $True
            Return $vraAuthentication
        }   
        else {
            Write-Error "Unable to obtain access token from vRealize Automation ($server), check credentials: PRE_VALIDATION_FAILED"
            $vraAuthentication = $False
            Return $vraAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-vRAAuthentication

Function Test-WSAConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $wsaConnection = $True
        Return $wsaConnection
    }   
    else { 
        Write-Error "Unable to communicate with Workspace ONE Access ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $wsaConnection = $False
        Return $wsaConnection
    }
}
Export-ModuleMember -Function Test-WSAConnection

Function Test-WSAAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Item variable:sessionToken -Force -Confirm:$false -ErrorAction Ignore

    Try {
        Request-WSAToken -fqdn $server -user $user -pass $pass | Out-Null
        if ($sessionToken) {
            $wsaAuthentication = $True
            Return $wsaAuthentication
        }   
        else {
            Write-Error "Unable to obtain access token from Workspace ONE Access ($server), check credentials: PRE_VALIDATION_FAILED"
            $wsaAuthentication = $False
            Return $wsaAuthentication
        }
    }
    Catch {
        # Do Nothing
    }
}
Export-ModuleMember -Function Test-WSAAuthentication

Function Test-VrmsVamiConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vrmsVamiConnection = $True
        Return $vrmsVamiConnection
    }   
    else { 
        Write-Error "Unable to communicate with vSphere Replication Appliance ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vrmsVamiConnection = $False
        Return $vrmsVamiConnection
    }
}
Export-ModuleMember -Function Test-VrmsVamiConnection

Function Test-VrmsVamiAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Variable -Name vrmsHeader -Scope Global -Force -Confirm:$false -ErrorAction Ignore

    Try {
        $response = Request-VrmsToken -fqdn $server -username $user -password $pass
        if ($vrmsHeader) {
            $vrmsVamiConnection = $True
            Return $vrmsVamiConnection
        }   
        else {
            Write-Error $response
            $vrmsVamiConnection = $False
            Return $vrmsVamiConnection
        }
    }
    Catch {
        Write-Error $response
    }
}
Export-ModuleMember -Function Test-VrmsVamiAuthentication

Function Test-SrmVamiConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $srmVamiConnection = $True
        Return $srmVamiConnection
    }   
    else { 
        Write-Error "Unable to communicate with Site Recovery Manager Appliance ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $srmVamiConnection = $False
        Return $srmVamiConnection
    }
}
Export-ModuleMember -Function Test-SrmVamiConnection

Function Test-SrmVamiAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Variable -Name srmHeader -Scope Global -Force -Confirm:$false -ErrorAction Ignore

    Try {
        $response = Request-SrmToken -fqdn $server -username $user -password $pass
        if ($srmHeader) {
            $srmVamiConnection = $True
            Return $srmVamiConnection
        }   
        else {
            Write-Error $response
            $srmVamiConnection = $False
            Return $srmVamiConnection
        }
    }
    Catch {
        Write-Error $response
    }
}
Export-ModuleMember -Function Test-SrmVamiAuthentication

Function Test-SRMConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $srmConnection = $True
        Return $srmConnection
    }   
    else { 
        Write-Error "Unable to communicate with Site Recovery Manager appliance ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $srmConnection = $False
        Return $srmConnection
    }
}
Export-ModuleMember -Function Test-SRMConnection

Function Test-SRMAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [String]$remoteUser,
        [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [String]$remotePass
    )

    Try {
        if ($remoteUser -and $remotePass) {
            Connect-SrmServer -SrmServerAddress $server -user $user -password $pass -remoteUser $remoteUser -remotePassword $remotePass | Out-Null
        }
        else {
            Connect-SrmServer -SrmServerAddress $server -user $user -password $pass | Out-Null
        }
    }
    Catch {
        if ($_.Exception.Message -eq "Cannot complete login due to an incorrect user name or password.") {
            $PSCmdlet.ThrowTerminatingError(
                [System.Management.Automation.ErrorRecord]::new(
                    ([System.Security.Authentication.InvalidCredentialException]"Unable to authenticate with Site Recovery Manager ($server), check credentials: PRE_VALIDATION_FAILED"),
                    'Test-SRMAuthentication',
                    [System.Management.Automation.ErrorCategory]::AuthenticationError,
                    ""
                )
            )
        }
        elseif ($_.Exception.Message -eq "Unable to connect to the remote server: One or more errors occurred.") {
            $PSCmdlet.ThrowTerminatingError(
                [System.Management.Automation.ErrorRecord]::new(
                    ([System.Management.Automation.ProviderNotFoundException]"Unable to authenticate with Site Recovery Manager ($server), check server IP address/FQDN: PRE_VALIDATION_FAILED"),
                    'Test-SRMAuthentication',
                    [System.Management.Automation.ErrorCategory]::InvalidArgument,
                    ""
                )
            )
        }
        elseif ($_.Exception.Message -eq "Unable to connect to the remote server: The connection to the remote server is down.") {
            $PSCmdlet.ThrowTerminatingError(
                [System.Management.Automation.ErrorRecord]::new(
                    ([System.Management.Automation.RemoteException]"Unable to authenticate with the remote Site Recovery Manager instance: PRE_VALIDATION_FAILED"),
                    'Test-SRMAuthentication',
                    [System.Management.Automation.ErrorCategory]::ConnectionError,
                    ""
                )
            )
        }
    }
    if ($defaultSrmServers) {
        $srmAuthentication = $True
        Return $srmAuthentication
    }
    else {
        $srmAuthentication = $False
        Return $srmAuthentication
    }
}
Export-ModuleMember -Function Test-SRMAuthentication

Function Test-WMSubnetInput {
    <#
        .SYNOPSIS
        Tests whether an IPv4 subnet is sized correctly for Developer Ready Infrastructure pools

        .DESCRIPTION
        The Test-WMSubnetInput cmdlet tests whether an IPv4 subnet is sized correctly for Developer Ready Infrastructure pools
        
        .EXAMPLE
        Test-WMSubnetInput -Subnet 192.168.21.0/24 -SubnetType Ingress
        This example will return as 'true'

        #>


    Param (
        [Parameter (Mandatory = $true)] [String]$Subnet,
        [Parameter (Mandatory = $true)][ValidateSet("Pod", "Service", "Egress", "Ingress")] [String]$SubnetType
    )

  
    Switch ($subnetType) {
        "Pod" {
            $subnetMinimum = 23
            Break
        }
        "Service" {
            $subnetMinimum = 22
            Break
        }
        "Egress" {
            $subnetMinimum = 27
            Break
        }
        "Ingress" {
            $subnetMinimum = 27
            Break
        }
        default {
            Write-Error "Unsuported Subnet Type ($subnetType)"
            Break
        }
    }
    
    
    Try {
        $checkSubnet = $null
        $subnetStart = $null
        [bool]$testElement = $false

        $subnetStart = $Subnet.Split("/")[0]
        Try {
            $checkSubnet = [IPAddress]$subnetStart
        }
        Catch {
            #Do nothing
        }

        if ($checksubnet.IPAddressToString -ne $subnetStart -or !$checkSubnet) {
            
            Write-Error "Improperly formatted subnet ($subnet) : VALIDATION_FAILED"
            
        }
        else {
            $testElement = $true
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }

    Try {
        [bool]$testSufix = $false
        $suffix = $Subnet.Split("/")[1]
        $checkSuffix = [int[]]$suffix
        if ($checkSuffix -gt $subnetMinimum -or !$checkSuffix) {
            Write-Error "Improperly sized $subnetType subnet ($subnet). Host prefix length should be at least {$subnetminimum)"
            
        }
        else {
            $testSufix = $true
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }

    if ($testElement -and $testSufix) {
        Return $true
    }
    else {
        Return $false
    }
    
}
Export-ModuleMember -Function Test-WMSubnetInput

Function Test-IpAddress {
    <#
        .SYNOPSIS
        Tests whether an IPv4 address is in a specified subnet.

        .DESCRIPTION
        The Test-IpAddress cmdlet tests whether an IPv4 address is in a specified subnet.

        .EXAMPLE
        Test-IpAddress -ipAddress 192.168.20.10 -Subnet 192.168.20.0/24
        This example will test whether the IPv4 address 192.168.20.10 is in the 192.168.20.0/24 subnet.
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$ipAddress,
        [Parameter (Mandatory = $true)] [String]$Subnet
    )

    $subnetStart = $Subnet.Split("/")[0]
    $suffix = $Subnet.Split("/")[1]

    $subnetStartBinary = $subnetStart -split '\.' | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')}
    $subnetStartBinary =  $subnetStartBinary -join ""
    $subnetStartBinary = ($subnetStartBinary).ToCharArray()

    $ipAddressBinary = $ipAddress -split '\.' | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')}
    $ipAddressBinary =  $ipAddressBinary -join ""
    $ipAddressBinary = ($ipAddressBinary).ToCharArray()

    for($i=0;$i -lt $subnetStartBinary.length;$i++){
        if($i -ge $suffix){
            $subnetStartBinary[$i] = "1"
        } 
    }

    for ($i = 0;$i -lt $subnetStartBinary.length;$i++) {
        $partSubnetStartBinary += $subnetStartBinary[$i] 
        if(($i+1)%8 -eq 0){
            $partSubnetStartBinary = $partSubnetStartBinary -join ""
            $subnetBroadcastBinary += $partSubnetStartBinary -join ""
            $partSubnetStartBinary = ""
        }
    }

    $subnetBroadcastBinary = $subnetBroadcastBinary.ToCharArray()

    [Int[]]$suffixComparison = (1..32)

    for($i=0; $i -lt $suffixComparison.length; $i++){
        if($suffixComparison[$i] -gt $suffix) {
            $suffixComparison[$i] = "0"
        } else {
            $suffixComparison[$i] = "1"
        }
    }
        
    [string]$suffixBinaryString = $suffixComparison -join ""
    [char[]]$suffixBinary = $suffixBinaryString.ToCharArray()
    $comparison = $true

    for ($i=0; $i -le $subnetStartBinary.length; $i++){
        if($subnetStartBinary[$i] -ne $ipAddressBinary[$i] -and $suffixBinary[$i] -ne "0") {
            $comparison = $false
        } 
    }

    $output = New-Object -TypeName PSCustomObject
    $output | Add-Member -notepropertyname 'IpAddress' -notepropertyvalue $ipAddress
    $output | Add-Member -notepropertyname 'Subnet' -notepropertyvalue $subnet
    $output | Add-Member -notepropertyname 'Validated' -notepropertyvalue $comparison
    $output
}
Export-ModuleMember -Function Test-IpAddress

Function Test-IPaddressArray {

    <#
        .SYNOPSIS
        Tests whether an array of strings can be converted to valid IPv4 addresses.

        .DESCRIPTION
        The Test-IpAddressArray cmdlet tests whether an array of strings can be converted to valid IPv4 addresses.
        Returns $true if all strings are valid IPv4 address or $false when at least one is not valid IPv4 address

        .EXAMPLE
        Test-IpAddressArray -ipAddressArray @("192.168.20.10","172.16.31.1")
        This example will test whether the strings "192.168.20.10","172.16.31.1" can be converted to valid IPv4 addresses.

        .EXAMPLE
        Test-IpAddressArray -ipAddressArray "192.168.20.10"
        This example will test whether the string "192.168.20.10" can be converted to valid IPv4 addresses.
    #>


    Param (
        [Parameter (Mandatory = $true)] [Array]$IPaddressArray
    )

    Foreach ($ipAddress in $IPaddressArray) {
        [bool]$testElement = $false
        Try {
            $convertToIPv4 = [ipaddress]$ipAddress
        }
        Catch {
            Write-Error "Can not convert $ipAddress to valid IPv4 address."
            Return $false 
        }
        if (($convertToIPv4.IPAddressToString -ne $ipAddress) -or (!$convertToIPv4)) {
            Write-Error "Can not convert $ipAddress to valid IPv4 address due to missing octet"
            Return $false
        }
        else {
            $testElement = $true
        }
    }
    Return $testElement
    
}
Export-ModuleMember -Function Test-IPaddressArray

Function Test-DnsServers {

    <#
        .SYNOPSIS
        Tests whether an array of DNS servers can resolve given domain name..

        .DESCRIPTION
        The Test-DnsServers cmdlet tests whether an array of DNS servers can resolve given domain name.
        Returns $true if all servers can resolve the given domain name or $false when at least one fails.

        .EXAMPLE
        Test-DnsServers -dnsServers @("192.168.20.10","172.16.31.1") -domainName vmware.com
        This example will test whether all dns servers "192.168.20.10","172.16.31.1" can can resolve domain name vmware.com.

        .EXAMPLE
        Test-DnsServers -dnsServers "192.168.20.10" -domainName vmware.com
        This example will test whether dns server "192.168.20.10" can resolve domain name vmware.com.
    #>


    Param (
        [Parameter (Mandatory = $true)] [Array]$dnsServers,
        [Parameter (Mandatory = $false)] [string]$domainName="vmware.com"
    )

    if (Test-IPaddressArray -IPaddressArray $dnsServers) {
    
        Foreach ($dnsServer in $dnsServers) {
            [bool]$resolveResult=$false
                                                                
            Try {
                $checkDnsServer = Resolve-DnsName -Name $domainName -Type A -Server $dnsServer -QuickTimeout -ErrorAction Stop
            } 
            Catch [System.ComponentModel.Win32Exception] {
                Write-Error "Can not resolve: $domainName using dns server: $dnsServer"
                Return $false
            }
            if (!$checkDnsServer) {
                Write-Error "Can not resolve: $domainName using dns server: $dnsServer"
                $resolveResult = $false
            }
            else {
                $resolveResult = $true
            }
 
        }
        Return $resolveResult
    }
}
Export-ModuleMember -Function Test-DnsServers

Function Test-NtpServer {
    <#
        .SYNOPSIS
        Checks the status of an NTP server

        .DESCRIPTION
        The Test-NtpServer cmdlet checks the status of an NTP server

        .EXAMPLE
        Test-NtpServer -Server pool.ntp.org
        This example will return the status of the NTP server responding at pool.ntp.org
    #>


    Param (
        [Parameter (Mandatory = $true)] [String]$server
    )

    $ntpStatus = $null
    Try {
        [Byte[]]$NtpData = ,0 * 48
        $NtpData[0] = 0x1B
    
        $Socket = New-Object Net.Sockets.Socket([Net.Sockets.AddressFamily]::InterNetwork,
                                                [Net.Sockets.SocketType]::Dgram,
                                                [Net.Sockets.ProtocolType]::Udp)
    
        $Socket.ReceiveTimeout = 2000
        $Socket.SendTimeout = 2000
    
        $Socket.Connect($Server,123)
    
        [Void]$Socket.Send($NtpData)
        [Void]$Socket.Receive($NtpData)  
        $Socket.Close()
    }
    Catch {
        # Do nothing
    }   

    if ($ntpData -eq 0x1B) {
        $ntpStatus = $false
    }
    else {
        $ntpStatus = $true
    }
    Return $ntpStatus

}
Export-ModuleMember -Function Test-NtpServer

#EndRegion End of Test Functions ######
#####################################################################

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################

#######################################################################################################################
#Region D E P R E C A T E D F U N C T I O N S ###########

Function Join-ESXiActiveDirectory {
    # Join each ESXi Host to the Active Directory Domain
    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainJoinUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainJoinPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcfDomain
    )

    Try {
        $vcenter = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $vcfDomain
        Connect-VIServer -Server $vcenter.fqdn -User $vcenter.ssoAdmin -pass $vcenter.ssoAdminPass | Out-Null
        if ($DefaultVIServer.Name -eq $($vcenter.fqdn)) {
            $checkAdAuthentication = Test-ADAuthentication -user $domainJoinUser -pass $domainJoinPass -server $domain -domain $domain
            if ($checkAdAuthentication -contains "2") {
                $esxiHosts = Get-VMHost
                $count = 0
                Foreach ($esxiHost in $esxiHosts) {
                    $currentDomainState = Get-VMHostAuthentication -VMHost $esxiHost
                    $currentDomain = [String]$currentDomainState.Domain
                    if ($currentDomain -ne $domain) {
                        Get-VMHostAuthentication -VMHost $esxiHost | Set-VMHostAuthentication -Domain $domain -JoinDomain -Username $domainJoinUser -Password $domainJoinPass -Confirm:$false | Out-Null
                        $currentDomainState = Get-VMHostAuthentication -VMHost $esxiHost
                        $currentDomain = [String]$currentDomainState.Domain
                        if ($currentDomain -eq $domain.ToUpper()) {
                            Write-Output "Confirmed ESXi Host $esxiHost joined Active Directory Domain $domain Successfully"
                        }
                        else {
                            Write-Error "Adding ESXi Host $esxiHost to Active Directory Domain $domain Failed"
                        }
                    }
                    else {
                        Write-Warning "ESXi Host $esxiHost already joined to Active Directory Domain $domain"
                    }
                    $count = $count + 1
                }
            }
            else {
                Write-Error "Domain User $domainJoinUser Authentication Failed"
            }
        }
        else {
            Write-Error "Unable to connect to vCenter Server ($($vcenter.fqdn))"
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Join-ESXiActiveDirectory

Function Add-ESXiDomainUser {
    # Assign an Active Directory Group to each ESXi Host for Administration
    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domain,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$domainBindPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$principal,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$role,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [bool]$propagate,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcfDomain
    )

    $securePass = ConvertTo-SecureString -String $domainBindPass -AsPlainText -Force
    $domainCreds = New-Object System.Management.Automation.PSCredential ($domainBindUser, $securePass)
    $addPrincipal = ($domain.Split(".")[0]).ToUpper() + "\" + $principal

    Try {
        Request-VCFToken -fqdn $server -Username $user -Password $pass | Out-Null
        if ($accessToken) {
            $esxiHosts = (Get-VCFCredential | Where-Object { $_.resource.domainName -eq $vcfDomain -and $_.accountType -eq "USER" -and $_.resource.resourceType -eq "ESXI" }).resource.resourceName
            if (Get-ADGroup -Server $domain -Credential $domainCreds -Filter { SamAccountName -eq $principal }) {
                $count = 0
                Foreach ($esxiHost in $esxiHosts) {
                    $esxiCreds = Get-VCFCredential | Where-Object { $_.resource.resourceName -eq $esxiHost -and $_.accountType -eq "USER" }
                    Connect-VIServer -Server $esxihost -User $esxiCreds.username -Pass $esxiCreds.password | Out-Null # Connect to ESXi Server
                    if ($DefaultVIServer.Name -eq $esxihost) {
                        $checkPermission = Get-VIPermission | Where-Object { $_.Principal -eq $addPrincipal }
                        if ($checkPermission.Principal -eq $addPrincipal) {
                            Write-Warning "Active Directory Group '$addPrincipal' already assigned permissions to $esxihost"
                        }
                        else {
                            New-VIPermission -Entity $esxiHost -Principal $addPrincipal -Propagate $propagate -Role $role
                            $checkPermission = Get-VIPermission | Where-Object { $_.Principal -eq $addPrincipal }
                            if ($checkPermission.Principal -eq $addPrincipal) {
                                Write-Output "Active Directory Group '$addPrincipal' assigned the Administrator role to $esxihost Successfully"
                            }
                            else {
                                Write-Error "Assigning Active Directory Group '$addPrincipal' the Administrator role to $esxihost Failed"
                            }
                        }
                        Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue # Disconnect from ESXi Server
                        $count = $count + 1
                    }
                    else {
                        Write-Error "Failed to connect to ESXi host $esxihost"
                        $count = $count + 1
                    }
                }
            }
            else {
                Write-Error "Active Directory User/Group '$addPrincipal' not found in the Active Directory Domain, please create and retry"
            }
        }
        else {
            Write-Error "Unable to obtain access token from SDDC Manager ($server), check credentials"
        }
    }
    Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Add-ESXiDomainUser

Function Set-SRMLicenseConfig {
    <#
        .SYNOPSIS
        Configure the license for Site Recovery Manager in the protected and recovery sites

        .DESCRIPTION
        The Set-SRMLicenseConfig cmdlet configures the license for Site Recovery Manager in the protected and recovery
        sites.
        The cmdlet connects to SDDC Manager in both the protected and recovery sites using the -sddcManagerAFqdn,
        -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both vSphere Replication instances
        - Validates whether the license keys exist in vCenter Server inventory, and if not, installs them
        - Configures the license for Site Recovery Manager in the protected and recovery sites.

        .EXAMPLE
        Set-SRMLicenseConfig -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -vCenterSiteARootPass VMw@re1! -vCenterSiteBRootPass VMw@re1! -srmSiteAKey AAAAA-BBBBB-CCCCC-DDDDD-EEEEE -srmSiteBKey 00000-11111-22222-33333-4444
        This example configures the Site Recovery Manager instances in the protected and recovery sites with their respective license key.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vCenterRootPassSiteA,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vCenterRootPassSiteB,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmSiteAKey,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmSiteBKey
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $srmAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $srmBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                                if ((Test-SRMConnection -server $srmAFqdn) -and (Test-SRMConnection -server $srmBFqdn)) {
                                                    if (Test-SRMAuthentication -server $srmAFqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                                                        $serviceInstanceA = Get-View -Server $siteAvCenterDetails.fqdn ServiceInstance 
                                                        $licenseManagerA = Get-View -Server $siteAvCenterDetails.fqdn $serviceInstanceA.Content.LicenseManager | Where-Object {$_.LicensedEdition -match $siteAvCenterDetails.fqdn}
                                                        $licenseAssignmentManagerA = Get-View -Server $siteAvCenterDetails.fqdn $licenseManagerA.licenseAssignmentManager
                                                        $licenseExistsA = $licenseManagerA.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteAKey}
                                                        if ($licenseExistsA) {
                                                            Write-Warning "License key for Site Recovery Manager ($srmSiteAKey) has already been installed on vCenter Server ($($siteAvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseManagerA.AddLicense($srmSiteAKey,$null) | Out-Null
                                                                $licenseManagerA.UpdateViewData()
                                                                $validateLicenseExistsA = $licenseManagerA.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteAKey}
                                                                if ($validateLicenseExistsA) {
                                                                    Write-Output "Add license key for Site Recovery Manager ($srmSiteAKey) to vCenter Server ($($siteAvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key for Site Recovery Manager ($srmSiteAKey) has been added to vCenter Server ($($siteAvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Set-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            } 
                                                        }
                                                        $srmASiteName = (($global:DefaultSrmServers | Where-Object {$_.Name -eq $srmAFqdn}).ExtensionData.GetLocalSiteInfo()).SiteName
                                                        $srmAPartialUuid = ($licenseAssignmentManagerA.QueryAssignedLicenses($null) | Where-Object {$_.EntityDisplayName -eq $srmASiteName}).EntityId
                                                        $scriptCommand = "/usr/lib/vmware-vmafd/bin/vmafd-cli get-ldu --server-name localhost"
                                                        $output = Invoke-VMScript -VM ($siteAvCenterDetails.fqdn).Split(".")[0] -ScriptText $scriptCommand -GuestUser root -GuestPassword $vCenterRootPassSiteA -Server $siteAvCenterDetails.fqdn
                                                        $srmAUuid = ($srmAPartialUuid + "-" + $output.ScriptOutput).Trim()
                                                        $existingSrmALicenseKey = $licenseAssignmentManagerA.QueryAssignedLicenses($srmAUuid).AssignedLicense.LicenseKey
                                                        if ($existingSrmALicenseKey -eq $srmSiteAKey) {
                                                            Write-Warning "License key ($srmSiteAKey) has already been configured for Site Recovery Manager on vCenter Server ($($siteAvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseAssignmentManagerA.UpdateAssignedLicense($srmAUuid,$srmSiteAKey,$null) | Out-Null
                                                                $licenseAssignmentManagerA.UpdateViewData() | Out-Null
                                                                $validateSrmLicenseKey = $licenseAssignmentManagerA.QueryAssignedLicenses($srmAUuid).AssignedLicense.LicenseKey
                                                                if ($validateSrmLicenseKey -eq $srmSiteAKey) {
                                                                    Write-Output "Configure license key ($srmSiteAKey) for Site Recovery Manager on vCenter Server ($($siteAvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key ($srmSiteAKey) has been configured for Site Recovery Manager on vCenter Server ($($siteAvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Set-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                    }
                                                    if (Test-SRMAuthentication -server $srmBFqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                        $serviceInstanceB = Get-View -Server $siteBvCenterDetails.fqdn ServiceInstance 
                                                        $licenseManagerB = Get-View -Server $siteBvCenterDetails.fqdn $serviceInstanceB.Content.LicenseManager | Where-Object {$_.LicensedEdition -match $siteBvCenterDetails.fqdn}
                                                        $licenseAssignmentManagerB = Get-View -Server $siteBvCenterDetails.fqdn $licenseManagerB.licenseAssignmentManager
                                                        $licenseExistsB = $licenseManagerB.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteBKey}
                                                        if ($licenseExistsB) {
                                                            Write-Warning "License key for Site Recovery Manager ($srmSiteBKey) has already been installed on vCenter Server ($($siteBvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseManagerB.AddLicense($srmSiteBKey,$null) | Out-Null
                                                                $licenseManagerB.UpdateViewData()
                                                                $validateLicenseExistsB = $licenseManagerB.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteBKey}
                                                                if ($validateLicenseExistsB) {
                                                                    Write-Output "Add license key for Site Recovery Manager ($srmSiteBKey) to vCenter Server ($($siteBvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key for Site Recovery Manager ($srmSiteBKey) has been added to vCenter Server ($($siteBvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Set-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            } 
                                                        }
                                                        $srmBSiteName = (($global:DefaultSrmServers | Where-Object {$_.Name -eq $srmBFqdn}).ExtensionData.GetLocalSiteInfo()).SiteName
                                                        $srmBPartialUuid = ($licenseAssignmentManagerB.QueryAssignedLicenses($null) | Where-Object {$_.EntityDisplayName -eq $srmBSiteName}).EntityId
                                                        $scriptCommand = "/usr/lib/vmware-vmafd/bin/vmafd-cli get-ldu --server-name localhost"
                                                        $output = Invoke-VMScript -VM ($siteBvCenterDetails.fqdn).Split(".")[0] -ScriptText $scriptCommand -GuestUser root -GuestPassword $vCenterRootPassSiteB -Server $siteBvCenterDetails.fqdn
                                                        $srmBUuid = ($srmBPartialUuid + "-" + $output.ScriptOutput).Trim()
                                                        $existingSrmBLicenseKey = $licenseAssignmentManagerB.QueryAssignedLicenses($srmBUuid).AssignedLicense.LicenseKey
                                                        if ($existingSrmBLicenseKey -eq $srmSiteBKey) {
                                                            Write-Warning "License key ($srmSiteBKey) has already been configured for Site Recovery Manager on vCenter Server ($($siteBvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseAssignmentManagerB.UpdateAssignedLicense($srmBUuid,$srmSiteBKey,$null) | Out-Null
                                                                $licenseAssignmentManagerB.UpdateViewData() | Out-Null
                                                                $validateSrmBLicenseKey = $licenseAssignmentManagerB.QueryAssignedLicenses($srmBUuid).AssignedLicense.LicenseKey
                                                                if ($validateSrmBLicenseKey -eq $srmSiteBKey) {
                                                                    Write-Output "Configure license key ($srmSiteBKey) for Site Recovery Manager on vCenter Server ($($siteBvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key ($srmSiteBKey) has been configured for Site Recovery Manager on vCenter Server ($($siteBvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Set-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-SRMLicenseConfig

Function Undo-SRMLicenseConfig {
    <#
        .SYNOPSIS
        Removes the license configuration for Site Recovery Manager in the protected and recovery sites

        .DESCRIPTION
        The Undo-SRMLicenseConfig cmdlet removes the license configuration from Site Recovery Manager in the protected
        and recovery sites.
        The cmdlet connects to SDDC Manager in both the protected and recovery sites using the -sddcManagerAFqdn,
        -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both vSphere Replication instances
        - Validates whether the license keys exist in vCenter Server inventory, and if not, installs them
        - Removes the license configuration for Site Recovery Manager in the protected and recovery sites

        .EXAMPLE
        Undo-SRMLicenseConfig -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -vCenterSiteARootPass VMw@re1! -vCenterSiteBRootPass VMw@re1! -srmSiteAKey AAAAA-BBBBB-CCCCC-DDDDD-EEEEE -srmSiteBKey 00000-11111-22222-33333-4444
        This example removes the license configuration from Site Recovery Manager instances in the protected and recovery sites with their respective license key.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vCenterRootPassSiteA,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vCenterRootPassSiteB,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmSiteAKey,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$srmSiteBKey
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $srmAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $srmBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcDr"}).Server.Url -Split "//" -Split ":")[2]
                                                if ((Test-SRMConnection -server $srmAFqdn) -and (Test-SRMConnection -server $srmBFqdn)) {
                                                    if (Test-SRMAuthentication -server $srmAFqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                                                        $serviceInstanceA = Get-View -Server $siteAvCenterDetails.fqdn ServiceInstance 
                                                        $licenseManagerA = Get-View -Server $siteAvCenterDetails.fqdn $serviceInstanceA.Content.LicenseManager | Where-Object {$_.LicensedEdition -match $siteAvCenterDetails.fqdn}
                                                        $licenseAssignmentManagerA = Get-View -Server $siteAvCenterDetails.fqdn $licenseManagerA.licenseAssignmentManager
                                                        $srmASiteName = (($global:DefaultSrmServers | Where-Object {$_.Name -eq $srmAFqdn}).ExtensionData.GetLocalSiteInfo()).SiteName
                                                        $srmAPartialUuid = ($licenseAssignmentManagerA.QueryAssignedLicenses($null) | Where-Object {$_.EntityDisplayName -eq $srmASiteName}).EntityId
                                                        $scriptCommand = "/usr/lib/vmware-vmafd/bin/vmafd-cli get-ldu --server-name localhost"
                                                        $output = Invoke-VMScript -VM ($siteAvCenterDetails.fqdn).Split(".")[0] -ScriptText $scriptCommand -GuestUser root -GuestPassword $vCenterRootPassSiteA -Server $siteAvCenterDetails.fqdn
                                                        $srmAUuid = ($srmAPartialUuid + "-" + $output.ScriptOutput).Trim()
                                                        $srmALicenseKeyAlreadyRemoved = $licenseAssignmentManagerA.QueryAssignedLicenses($srmAUuid).AssignedLicense.LicenseKey
                                                        if (!$srmALicenseKeyAlreadyRemoved -or $srmALicenseKeyAlreadyRemoved -eq "00000-00000-00000-00000-00000") {
                                                            Write-Warning "License key ($srmSiteAKey) has already been unconfigured for Site Recovery Manager on vCenter Server ($($siteAvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseAssignmentManagerA.RemoveAssignedLicense($srmAUuid) | Out-Null
                                                                $licenseAssignmentManagerA.UpdateViewData() | Out-Null
                                                                $validateSrmALicenseKeyRemoved = $licenseAssignmentManagerA.QueryAssignedLicenses($srmAUuid).AssignedLicense.LicenseKey
                                                                if (!$validateSrmALicenseKeyRemoved) {
                                                                    Write-Output "Unconfigure license key ($srmSiteAKey) for Site Recovery Manager on vCenter Server ($($siteAvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key ($srmSiteAKey) has been unconfigured from Site Recovery Manager on vCenter Server ($($siteAvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Undo-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                        $licenseExistsA = $licenseManagerA.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteAKey}
                                                        if (!$licenseExistsA) {
                                                            Write-Warning "License key for Site Recovery Manager ($srmSiteAKey) does not exist on vCenter Server ($($siteAvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseManagerA.RemoveLicense($srmSiteAKey) | Out-Null
                                                                $licenseManagerA.UpdateViewData()
                                                                $validateLicenseRemovedA = $licenseManagerA.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteAKey}
                                                                if (!$validateLicenseRemovedA) {
                                                                    Write-Output "Remove license key for Site Recovery Manager ($srmSiteAKey) from vCenter Server ($($siteAvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key for Site Recovery Manager ($srmSiteAKey) has been removed from vCenter Server ($($siteAvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Undo-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            } 
                                                        }
                                                    }
                                                    if (Test-SRMAuthentication -server $srmBFqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                        $serviceInstanceB = Get-View -Server $siteBvCenterDetails.fqdn ServiceInstance 
                                                        $licenseManagerB = Get-View -Server $siteBvCenterDetails.fqdn $serviceInstanceB.Content.LicenseManager | Where-Object {$_.LicensedEdition -match $siteBvCenterDetails.fqdn}
                                                        $licenseAssignmentManagerB = Get-View -Server $siteBvCenterDetails.fqdn $licenseManagerB.licenseAssignmentManager
                                                        $srmBSiteName = (($global:DefaultSrmServers | Where-Object {$_.Name -eq $srmBFqdn}).ExtensionData.GetLocalSiteInfo()).SiteName
                                                        $srmBPartialUuid = ($licenseAssignmentManagerB.QueryAssignedLicenses($null) | Where-Object {$_.EntityDisplayName -eq $srmBSiteName}).EntityId
                                                        $scriptCommand = "/usr/lib/vmware-vmafd/bin/vmafd-cli get-ldu --server-name localhost"
                                                        $output = Invoke-VMScript -VM ($siteBvCenterDetails.fqdn).Split(".")[0] -ScriptText $scriptCommand -GuestUser root -GuestPassword $vCenterRootPassSiteB -Server $siteBvCenterDetails.fqdn
                                                        $srmBUuid = ($srmBPartialUuid + "-" + $output.ScriptOutput).Trim()
                                                        $existingSrmBLicenseKey = $licenseAssignmentManagerB.QueryAssignedLicenses($srmBUuid).AssignedLicense.LicenseKey
                                                        if (!$existingSrmBLicenseKey -or $existingSrmBLicenseKey -eq "00000-00000-00000-00000-00000") {
                                                            Write-Warning "License key ($srmSiteBKey) has already been unconfigured for Site Recovery Manager on vCenter Server ($($siteBvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseAssignmentManagerB.RemoveAssignedLicense($srmBUuid) | Out-Null
                                                                $licenseAssignmentManagerB.UpdateViewData() | Out-Null
                                                                $validateSrmBLicenseKeyRemoved = $licenseAssignmentManagerB.QueryAssignedLicenses($srmBUuid).AssignedLicense.LicenseKey
                                                                if (!$validateSrmBLicenseKeyRemoved) {
                                                                    Write-Output "Unconfigure license key ($srmSiteBKey) for Site Recovery Manager on vCenter Server ($($siteBvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key ($srmSiteBKey) has been configured for Site Recovery Manager vCenter Server ($($siteBvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Undo-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                        }
                                                        $licenseExistsB = $licenseManagerB.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteBKey}
                                                        if (!$licenseExistsB) {
                                                            Write-Warning "License key for Site Recovery Manager ($srmSiteBKey) does not exist on vCenter Server ($($siteBvCenterDetails.fqdn)): SKIPPING"
                                                        } else {
                                                            Try {
                                                                $licenseManagerB.RemoveLicense($srmSiteBKey) | Out-Null
                                                                $licenseManagerB.UpdateViewData() | Out-Null
                                                                $validateLicenseBRemoved = $licenseManagerB.Licenses | Where-Object {$_.LicenseKey -eq $srmSiteBKey}
                                                                if (!$validateLicenseBRemoved) {
                                                                    Write-Output "Remove license key for Site Recovery Manager ($srmSiteBKey) from vCenter Server ($($siteBvCenterDetails.fqdn)): SUCCESSFUL"
                                                                } else {
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.GetValueException]"Unable to validate license key for Site Recovery Manager ($srmSiteBKey) has been removed from vCenter Server ($($siteBvCenterDetails.fqdn)): POST_VALIDATION_FAILED"),
                                                                            'Undo-SRMLicense',
                                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            } 
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-SRMLicenseConfig

Function Request-VAMISessionId {
    <#
        .SYNOPSIS
        Connects to the specified VAMI interface and requests a session token

        .DESCRIPTION
        The Request-VAMISessionId cmdlet connects to the specified VAMI interface and requests a session token.
        It is required once per session before running all other cmdlets

        .EXAMPLE
        Request-VAMISessionId -fqdn sfo-m01-vc01.sfo.rainpole.io -username root -password VMw@re1!
        This example shows how to connect to a VAMI interface to request a session token
      #>


      Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$fqdn,
        [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$username,
        [Parameter (Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$password
      )

      If ( -not $PsBoundParameters.ContainsKey("username") -or ( -not $PsBoundParameters.ContainsKey("password"))) {
           # Request Credentials
        $creds = Get-Credential
        $username = $creds.UserName.ToString()
        $password = $creds.GetNetworkCredential().password
    }


          # Validate credentials by executing an API call
          $headers = @{"Content-Type" = "application/json"}
          $uri = "https://"+$fqdn+":5480/configure/requestHandlers/login"
          $body = '{"username": "'+$username+'","password": "'+$password+'"}'

          Try {
            # PS Core has -SkipCertificateCheck implemented, PowerShell 5.x does not
            if ($PSEdition -eq 'Core') {
                  $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -body $body -SkipCertificateCheck
                  $sessionId = $response.data.sessionId
            }
            else {
                  $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -body $body
                  $Global:sessionId = $response.data.sessionId
               
            }
            if ($response.data.sessionId) {
                #Write-Output "Successfully Requested New VAMI Session Token From: $fqdn"
                $sessionId
            }
          }
          Catch {
            Write-Error $_.Exception.Message
        }
}
Export-ModuleMember -Function Request-VAMISessionId

Function createVAMIAuthHeader {
    $VAMIAuthheaders = @{"Content-Type" = "application/json" }
    $VAMIAuthheaders.Add("dr.config.service.sessionid", "$sessionId")
    $VAMIAuthheaders
}

Function Test-VAMIConnection {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server
    )

    if (Test-Connection -ComputerName ($server) -Quiet -Count 1) {
        $vamiConnection = $True
        Return $vamiConnection
    }   
    else { 
        Write-Error "Unable to communicate with appliance VAMI interface ($server), check fqdn/ip address: PRE_VALIDATION_FAILED"
        $vamiConnection = $False
        Return $vamiConnection
    }
}
Export-ModuleMember -Function Test-VAMIConnection

Function Test-VAMIAuthentication {
    Param (
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$server,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$user,
        [Parameter (Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$pass
    )

    Remove-Variable -Name VAMIAuthHeaders -Scope Global -Force -Confirm:$false -ErrorAction Ignore
    Remove-Variable -Name SessionId -Scope Global -Force -Confirm:$false -ErrorAction Ignore

    Try {
        $i=0
        do {
            $i++
            Start-Sleep -Seconds 1
            Request-VAMISessionId -fqdn $server -username $user -password $pass -ErrorAction SilentlyContinue
            if ($i -ge 30) {
                $PSCmdlet.ThrowTerminatingError(
                    [System.Management.Automation.ErrorRecord]::new(
                        ([System.Management.Automation.GetValueException]"Get session ID from appliance VAMI interface ($server): PRE_VALIDATION_FAILED"),
                        'Request-VAMISessionId',
                        [System.Management.Automation.ErrorCategory]::ConnectionError,
                        ""
                    )
                )   
            }
        }
        while ($global:sessionId -eq $null)
        $global:VAMIAuthHeaders = createVAMIAuthHeader($sessionId)

        if ($VAMIAuthHeaders) {
            $vamiAuthentication = $True
            Return $vamiAuthentication
        }   
        else {
            Write-Error "Unable to authenticate with appliance VAMI interface ($server), check credentials: PRE_VALIDATION_FAILED"
            $vamiAuthentication = $False
            Return $vamiAuthentication
        }
    }
    Catch {
        $PSCmdlet.ThrowTerminatingError($PSItem)
    }
}
Export-ModuleMember -Function Test-VAMIAuthentication

Function Set-vSRIncomingStorageTraffic {
    <#
        .SYNOPSIS
        Configures the IP address for incoming storage traffic on vSphere Replication via VAMI interface

        .DESCRIPTION
        The Set-vSRIncomingStorageTraffic cmdlet configures the IP address for incoming storage traffic on vSphere
        Replication via VAMI interface

        .EXAMPLE
        Set-vSRIncomingStorageTraffic -fqdn sfo-m01-vrms01.sfo.rainpole.io -user admin -password VMw@re1! -ipAddress 172.27.15.123
        This example sets the IP address for incoming storage traffic on vSphere Replication appliance sfo-m01-vrms01.sfo.rainpole.io to 172.27.15.123
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ipAddress
    )

    Try {
        if (Test-VAMIConnection -server $fqdn) {
            if (Test-VAMIAuthentication -server $fqdn -user $username -pass $password) {
                $data =  [PSCustomObject] @{
                    "filterIp" = "$ipAddress"
                    "managementIp" = ""
                }
                $data = $data | ConvertTo-Json
                $uri = "https://"+$fqdn+":5480/configure/requestHandlers/setHbrNic"
                $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $VAMIAuthheaders -Body $data
                $response
            }
        }        
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}    
Export-ModuleMember -Function Set-vSRIncomingStorageTraffic

Function Get-vSRIncomingStorageTraffic {
    <#
        .SYNOPSIS
        Retrieves the IP address for incoming storage traffic on vSphere Replication via VAMI interface

        .DESCRIPTION
        The Get-vSRIncomingStorageTraffic cmdlet retrieves the IP address for incoming storage traffic on vSphere
        Replication via VAMI interface

        .EXAMPLE
        Get-vSRIncomingStorageTraffic -fqdn sfo-m01-vrms01.sfo.rainpole.io -user admin -password VMw@re1!
        This example retrieves the IP address for incoming storage traffic on vSphere Replication appliance sfo-m01-vrms01.sfo.rainpole.io
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    Try {
        if (Test-VAMIConnection -server $fqdn) {
            if (Test-VAMIAuthentication -server $fqdn -user $username -pass $password) {
                $uri = "https://"+$fqdn+":5480/configure/requestHandlers/getHbrNic"
                $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $VAMIAuthheaders
                $response.data
            }
        }        
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}    
Export-ModuleMember -Function Get-vSRIncomingStorageTraffic

Function Set-DRSolutionNetworkAdapter {
    <#
        .SYNOPSIS
        Configures an ethernet adapter on a DR solution via VAMI interface

        .DESCRIPTION
        The Set-DRSolutionNetworkAdapter cmdlet configures an ethernet adapter on a DR solution via VAMI interface

        .EXAMPLE
        Set-DRSolutionNetworkAdapter -fqdn sfo-m01-vrms01.sfo.rainpole.io -user admin -password VMw@re1! -interfaceName eth1 -defaultGateway 172.16.11.253 -cidrPrefix 24 -ipAddress 172.16.11.123
        This example configures the Site Recovery Manager appliance secondary ethernet adapter
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$interfaceName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$defaultGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$cidrPrefix,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ipAddress
    )

    Try {
        if (Test-VAMIConnection -server $fqdn) {
            if (Test-VAMIAuthentication -server $fqdn -user $username -pass $password) {
                $networkConfig = Get-DRSolutionNetworkConfig -fqdn $fqdn -username $username -password $password
                $ipv4 =  [PSCustomObject] @{
                    "interfaceName" = "$interfaceName"
                    "defaultGateway" = "$defaultGateway"
                    "prefix" = $cidrPrefix
                    "mode" = "STATICMODE"
                    "address" = "$ipAddress"
                }
                ($networkConfig.interfaces | Where-Object {$_.Name -eq $interfaceName}).ipv4 = $ipv4
                ($networkConfig.interfaces | Where-Object {$_.Name -eq $interfaceName}).ipv6 = $null
                $networkConfig = $networkConfig | ConvertTo-Json -Depth 10
                $uri = "https://"+$fqdn+":5480/configure/requestHandlers/editNetworking"
                $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $VAMIAuthheaders -Body $networkConfig
                $response
            }
        }        
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}    
Export-ModuleMember -Function Set-DRSolutionNetworkAdapter

Function Get-DRSolutionSummary {
    <#
        .SYNOPSIS
        Retrieves the Site Recovery Manager summary

        .DESCRIPTION
        The Get-DRSolutionSummary cmdlet retrieves the Site Recovery Manager summary

        .EXAMPLE
        Get-DRSolutionSummary -fqdn sfo-m01-srm01.sfo.rainpole.io -username admin -password VMw@re1!
        This example retrieves the Site Recovery Manager summary
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    Try {
        $sessionId = Request-VAMISessionId -fqdn $fqdn -username $username -password $password
        $VAMIAuthHeaders = createVAMIAuthHeader($sessionId)
        $uri = "https://" + $fqdn + ":5480/configure/requestHandlers/getSummaryInfo"
        $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $VAMIAuthheaders -body $body
        $response
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}    
Export-ModuleMember -Function Get-DRSolutionSummary

Function Get-DRSolutionNetworkConfig {
    <#
        .SYNOPSIS
        Retrieves the Site Recovery Manager appliance network configuration

        .DESCRIPTION
        The Get-DRSolutionNetworkConfig cmdlet retrieves the Site Recovery Manager appliance network configuration

        .EXAMPLE
        Get-DRSolutionNetworkConfig -fqdn sfo-m01-srm01.sfo.rainpole.io -username admin -password VMw@re1!
        This example retrieves the Site Recovery Manager appliance network configuration
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$fqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$username,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$password
    )

    Try {
        if (Test-VAMIConnection -server $fqdn) {
            if (Test-VAMIAuthentication -server $fqdn -user $username -pass $password) {
                $uri = "https://"+$fqdn+":5480/configure/requestHandlers/getNetworkingInfo"
                $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $VAMIAuthheaders -Body $body
                $response.data
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Get-DRSolutionNetworkConfig

Function Register-DRSolutionTovCenter {
    <#
        .SYNOPSIS
        Registers Site Recovery Manager & vSphere Replication with a given vCenter Server

        .DESCRIPTION
        The Register-DRSolutionTovCenter cmdlet registers Site Recovery Manager & vSphere Replication with a given vCenter Server

        .EXAMPLE
        Register-DRSolutionTovCenter -applianceFqdn sfo-m01-srm01.sfo.rainpole.io -vamiAdminPassword VMw@re1! -pscHost sfo-m01-vc01.sfo.rainpole.io -thumbprint EA:0F:24:7E:B4:4C:5E:ED:38:AE:79:A6:9E:A2:E8:8F:EE:54:D8:AF:18:6A:A2:57:DC:87:09:68:D4:76:36:DD -vcInstanceId 53cad28c-4160-4956-b7c1-c7bbc5185a39 -ssoAdminUser administrator@vsphere.local -ssoAdminPassword VMw@re1! -siteName SFO01 -adminEmail admin@rainpole.io -hostName sfo-m01-srm01.sfo.rainpole.io
        This example registers the Site Recovery Manager Virtual Appliance with vCenter
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$applianceFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vamiAdminPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pscHost,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$thumbprint,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vcInstanceId,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoAdminUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ssoAdminPassword,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$adminEmail,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$hostName,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$extensionKey
    )

    Try {
        $body = '{
            "connection": {
                "pscHost": "'
+$pscHost+'",
                "pscPort": 443,
                "thumbprint": "'
+$thumbprint+'",
                "vcInstanceId": "'
+$vcInstanceId+'",
                "vcThumbprint": "'
+$thumbprint+'"
            },
            "adminUser": "'
+$ssoAdminUser+'",
            "adminPassword": "'
+$ssoAdminPassword+'",
            "siteName": "'
+$siteName+'",
            "adminEmail": "'
+$adminEmail+'",
            "hostName": "'
+$hostName+'",
            "extensionKey": "'
+$extensionKey+'"
        }'

        $body
        $sessionId = Request-VAMISessionId -fqdn $applianceFqdn -username admin -password $vamiAdminPassword
        $VAMIAuthHeaders = createVAMIAuthHeader($sessionId)                    
        $uri = "https://"+$applianceFqdn+":5480/configure/requestHandlers/configureAppliance"
        $response = Invoke-RestMethod -Method POST -Uri $uri -Headers $VAMIAuthheaders -body $body
        $response
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Register-DRSolutionTovCenter

Function New-vSRPortGroup {
    <#
        .SYNOPSIS
        Create port groups for vSphere Replication appliances in the protected and recovery sites

        .DESCRIPTION
        The New-vSRPortGroup cmdlet creates port groups for vSphere Replication appliances in the protected and
        recovery sites. The cmdlet connects to SDDC Manager in both the protected and recovery sites using the
        -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and
        -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Creates port groups for vSphere Replication appliances in the protected and recovery sites defined in
        -siteAVLAN, -siteBVLAN, and suffix paramters.

        .EXAMPLE
        New-vSRPortGroup -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1 -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -siteAVLAN 2715 -siteBVLAN 2815 -suffix "vrms"
        This example creates a port group for VLAN ID 2715 named sfo-m01-cl01-vds01-pg-vrms in the protected vCenter Server instance and a port group for VLAN ID 2815 named lax-m01-cl01-vds01-pg-vrms in the recovery vCenter Server instance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteAVLAN,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteBVLAN,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$suffix
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $VDSwitchSiteA = Get-VDSwitch -Server $SiteAvCenterDetails.fqdn
                                                $existingPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteAVLAN) -or ($_.Name -match "$($VDSwitchSiteA)-pg-$suffix")}
                                                if ($existingPortGroupSiteA) {
                                                    Write-Warning "Distributed virtual port group name ($($existingPortGroupSiteA.Name)) or VLAN ID ($siteAVLAN) already exists: SKIPPING"
                                                } else {
                                                    Try {
                                                        $createVDPortGroupSiteA = New-VDPortGroup -Server $siteAvCenterDetails.fqdn -VDSwitch $VDSwitchSiteA -Name "$($VDSwitchSiteA)-pg-$suffix" -VlanId $siteAVLAN -ErrorAction Stop
                                                        $createVDPortGroupSiteA | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy LoadBalanceLoadBased | Out-Null
                                                        Try {
                                                            $validateVDPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $SiteAVLAN}
                                                        } Catch {
                                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                                        }
                                                        if (!$validateVDPortGroupSiteA) {
                                                            $PSCmdlet.ThrowTerminatingError(
                                                                [System.Management.Automation.ErrorRecord]::new(
                                                                    ([System.Management.Automation.GetValueException]"Create distributed virtual port group with VLAN ID ($siteAVLAN): POST_VALIDATION_FAILED"),
                                                                    'Get-VDPortGroup',
                                                                    [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                    ""
                                                                )
                                                            )
                                                        } else {
                                                            if ($validateVDPortGroupSiteA.VlanConfiguration.VlanId -eq $siteAVLAN) {
                                                                Write-Output "Create distributed virtual port group ($($validateVDPortGroupSiteA.Name)) with VLAN ID ($siteAVLAN): SUCCESSFUL"
                                                            } else {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.GetValueException]"Create virtual port group ($($createVDPortGroupSiteA.Name)) with VLAN ID ($siteAVLAN): POST_VALIDATION_FAILED"),
                                                                        'Get-VDPortGroup',
                                                                        [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                        ""
                                                                    )
                                                                )
                                                            }
                                                        }
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                }
                                                $VDSwitchSiteB = Get-VDSwitch -Server $SiteBvCenterDetails.fqdn
                                                $existingPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteBVLAN) -or ($_.Name -match "$($VDSwitchSiteB)-pg-$suffix")}
                                                if ($existingPortGroupSiteB) {
                                                    Write-Warning "Distributed virtual port group name ($($existingPortGroupSiteB.Name)) or VLAN ID ($siteBVLAN) already exists: SKIPPING"
                                                } else {
                                                    Try {
                                                        $createVDPortgroupSiteB = New-VDPortGroup -Server $siteBvCenterDetails.fqdn -VDSwitch $VDSwitchSiteB -Name "$($VDSwitchSiteB)-pg-$suffix" -VlanId $siteBVLAN -ErrorAction Stop
                                                        $createVDPortGroupSiteB | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy LoadBalanceLoadBased | Out-Null
                                                        Try {
                                                            $validateVDPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $SiteBVLAN}
                                                        } Catch {
                                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                                        }
                                                        if (!$validateVDPortGroupSiteB) {
                                                            $PSCmdlet.ThrowTerminatingError(
                                                                [System.Management.Automation.ErrorRecord]::new(
                                                                    ([System.Management.Automation.GetValueException]"Create distributed virtual port group with VLAN ID ($siteBVLAN): POST_VALIDATION_FAILED"),
                                                                    'Get-VDPortGroup',
                                                                    [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                    ""
                                                                    )
                                                                )
                                                        } else {
                                                            if ($validateVDPortGroupSiteB.VlanConfiguration.VlanId -eq $siteBVLAN) {
                                                                Write-Output "Create distributed virtual port group ($($validateVDPortGroupSiteB.Name)) with VLAN ID ($siteBVLAN): SUCCESSFUL"
                                                            } else {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.GetValueException]"Create virtual port group ($($validateVDPortGroupSiteB.Name)) with VLAN ID ($siteBVLAN): POST_VALIDATION_FAILED"),
                                                                        'Get-VDPortGroup',
                                                                        [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                        ""
                                                                    )
                                                                )
                                                            }
                                                        }
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vSRPortGroup

Function Undo-vSRPortGroup {
    <#
        .SYNOPSIS
        Removes port groups for vSphere Replication appliances in the protected and recovery sites

        .DESCRIPTION
        The Undo-vSRPortGroup cmdlet removes port groups for vSphere Replication appliances in the protected and
        recovery sites. The cmdlet connects to SDDC Manager in both the protected and recovery sites using the
        -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and
        -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Removes port groups for vSphere Replication appliances in the protected and recovery sites defined in
        -siteAVLAN and -siteBVLAN paramters.

        .EXAMPLE
        Undo-vSRPortGroup -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -SiteAVLAN 2715 -SiteBVLAN 2815
        This example removes a port group for VLAN ID 2715 in the protected vCenter Server instance and a port group for VLAN ID 2815 in the recovery vCenter Server instance
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteAVLAN,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteBVLAN
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $existingPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $SiteAVLAN}
                                                if (!$existingPortGroupSiteA) {
                                                    Write-Warning "A distributed virtual port group with VLAN ID ($siteAVLAN) does not exist: SKIPPING"
                                                } else {
                                                    Try {
                                                        $VDSwitchSiteA = Get-VDSwitch -Server $SiteAvCenterDetails.fqdn
                                                        $VDPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn -VDSwitch $VDSwitchSiteA -ErrorAction Stop
                                                        Foreach ($portGroup in $VDPortGroupSiteA) {
                                                            if ($portGroup.VlanConfiguration.VlanId -eq $SiteAVlan) {
                                                                Try {
                                                                    $VDPortGroupSiteAName = $portGroup.Name
                                                                    Remove-VDPortGroup -Server $SiteAvCenterDetails.fqdn -VDPortGroup $portGroup.Name -Confirm:$false -ErrorAction Stop -WarningAction SilentlyContinue | Out-Null
                                                                    Try {
                                                                        $validateVDPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn -VDSwitch $VDSwitchSiteA -Name $portGroup.Name -ErrorAction SilentlyContinue
                                                                    } Catch {
                                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                    }
                                                                    if ($validateVDPortGroupSiteA) {
                                                                        $PSCmdlet.ThrowTerminatingError(
                                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                                ([System.Management.Automation.GetValueException]"Remove virtual port group $($VDPortGroupSiteAName) with VLAN ID ($siteAVLAN): POST_VALIDATION_FAILED"),
                                                                                'Remove-VDPortGroup',
                                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                                ""
                                                                            )
                                                                        )
                                                                    } else {
                                                                        Write-Output "Remove distributed virtual port group ($($VDPortGroupSiteAName)) with VLAN ID ($siteAVLAN): SUCCESSFUL"
                                                                    }
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                            }
                                                        }
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                }
                                                $existingPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $SiteBVLAN}
                                                if (!$existingPortGroupSiteB) {
                                                    Write-Warning "A distributed virtual port group with VLAN ID ($siteBVLAN) does not exist: SKIPPING"
                                                } else {
                                                    Try {
                                                        $VDSwitchSiteB = Get-VDSwitch -Server $SiteBvCenterDetails.fqdn
                                                        $VDPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn -VDSwitch $VDSwitchSiteB -ErrorAction Stop
                                                        Foreach ($portGroup in $VDPortGroupSiteB) {
                                                            if ($portGroup.VlanConfiguration.VlanId -eq $SiteBVlan) {
                                                                Try {
                                                                    $VDPortGroupSiteBName = $portGroup.Name
                                                                    Remove-VDPortGroup -Server $SiteBvCenterDetails.fqdn -VDPortGroup $portGroup.Name -Confirm:$false -ErrorAction Stop -WarningAction SilentlyContinue | Out-Null
                                                                    Try {
                                                                        $validateVDPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn -VDSwitch $VDSwitchSiteB -Name $portGroup.Name -ErrorAction SilentlyContinue
                                                                    } Catch {
                                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                    }
                                                                    if ($validateVDPortGroupSiteB) {
                                                                        $PSCmdlet.ThrowTerminatingError(
                                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                                ([System.Management.Automation.GetValueException]"Remove virtual port group ($($VDPortGroupSiteBName)) with VLAN ID ($siteBVLAN): POST_VALIDATION_FAILED"),
                                                                                'Remove-VDPortGroup',
                                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                                ""
                                                                            )
                                                                        )
                                                                    } else {
                                                                        Write-Output "Remove distributed virtual port group ($($VDPortGroupSiteAName)) with VLAN ID ($siteBVLAN): SUCCESSFUL"
                                                                    }
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                            }
                                                        }
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vSRPortGroup

Function Set-vSRNetworkConfig {
    <#
        .SYNOPSIS
        Configure the secondary ethernet adapter and configures the required routing for vSphere Replication appliances
        in the protected and recovery sites

        .DESCRIPTION
        The Set-vSRNetworkConfig cmdlet configures the secondary ethernet adapter and configures the required routing
        for vSphere Replication appliances in the protected and recovery sites. The cmdlet connects to SDDC Manager in
        both the protected and recovery sites using the -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass,
        -sddcManagerBFqdn, -sddcManagerBUser, and -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both vSphere Replication instances
        - Configures the secondary ethernet adapter and configures the required routing for vSphere Replication
        appliances in the protected and recovery sites

        .EXAMPLE
        Set-vSRNetworkConfig -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -eth1VLANSiteA 2715 -eth1SubnetSiteA 172.27.15.0/24 -eth1IpAddressSiteA 172.27.15.123 -eth1GatewaySiteA 172.27.15.1 -vSRApplianceRootPassSiteA VMw@re1! -vSRApplianceAdminPassSiteA VMw@re1! -eth1VLANSiteB 2815 -eth1SubnetSiteB 172.28.15.0/24 -eth1IpAddressSiteB 172.28.15.123 -eth1GatewaySiteB 172.28.15.1 -vSRApplianceRootPassSiteB VMw@re1! -vSRApplianceAdminPassSiteB VMw@re1!
        This example configures the protected and recovery site vSphere Replication appliances to use a secondary ethernet adapter for vSphere Replication traffic.
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$eth1VLANSiteA,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$eth1SubnetSiteA,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$eth1IpAddressSiteA,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$eth1GatewaySiteA,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vSRApplianceRootPassSiteA,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vSRApplianceAdminPassSiteA,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$eth1VLANSiteB,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$eth1SubnetSiteB,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$eth1IpAddressSiteB,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$eth1GatewaySiteB,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vSRApplianceRootPassSiteB,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$vSRApplianceAdminPassSiteB
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $hmsAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcHms"}).Server.Url -Split "//" -Split ":")[2]
                                                $VDPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $eth1VLANSiteA}
                                                if (!$VDPortGroupSiteA) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"No distributed virtual port group with VLAN ID ($eth1VLANSiteA) exists: PRE_VALIDATION_FAILED"),
                                                            'Get-VDPortGroup',
                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                            ""
                                                        )
                                                    )                                                
                                                }
                                                if ($VDPortGroupSiteA.Count -gt 1) {
                                                    $VDPortGroupSiteA = $VDPortGRoupSiteA | Where-Object {$_.Name -match "vrms"}  
                                                }
                                                $hmsAVmName = $hmsAFqdn.Split(".")[0]
                                                $numEthAdaptersA = (Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName | Get-NetworkAdapter).Count
                                                if ($numEthAdaptersA -le 1) {
                                                    $addEth1 = Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName | New-NetworkAdapter -Server $siteAvCenterDetails.fqdn -NetworkName $VDPortGroupSiteA.Name -Type vmxnet3 -StartConnected:$true -Confirm:$false -WarningAction SilentlyContinue -ErrorAction Stop
                                                    if (!$addEth1) {
                                                        $PSCmdlet.ThrowTerminatingError(
                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                ([System.Management.Automation.SetValueException]"Create ethernet adapter on vSphere Replication appliance ($hmsAVmName): POST_VALIDATION_FAILED"),
                                                                'New-NetworkAdapter',
                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                ""
                                                            )
                                                        )       
                                                    }
                                                    [int]$hmsACidr = $eth1SubnetSiteA.Split("/")[1]
                                                    Set-DRSolutionNetworkAdapter -fqdn $hmsAFqdn -user admin -password $vSRApplianceAdminPassSiteA -interfaceName eth1 -defaultGateway $eth1GatewaySiteA -cidrPrefix $hmsACidr -ipAddress $eth1IpAddressSiteA -ErrorAction Stop | Out-Null
                                                    Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName | Restart-VMGuest -Confirm:$False | Out-Null                                                
                                                    Do {
                                                        Start-Sleep -Seconds 1
                                                        $vmRestart = Get-VMGuest -Server $siteAvCenterDetails.fqdn -VM $hmsAVmName
                                                        $vamiStatus = Test-VAMIAuthentication -server $hmsAFqdn -user admin -pass $vSRApplianceAdminPassSiteA -ErrorAction SilentlyContinue
                                                    }
                                                    Until (($vmRestart.State -eq "Running") -and ($vamiStatus -eq $true))
                                                    $hmsANetConfig = ((Get-DRSolutionNetworkConfig -fqdn $hmsAFqdn -user admin -password $vSRApplianceAdminPassSiteA).Interfaces | Where-Object {$_.Name -eq "eth1"}).ipv4
                                                    if (($hmsANetConfig.defaultGateway -ne $eth1GatewaySiteA) -or ($hmsANetConfig.prefix -ne $hmsACidr) -or ($hmsANetConfig.address -ne $eth1IpAddressSiteA) -or ($trySetHmsANetConfig.successful -eq $false)) {
                                                        $PSCmdlet.ThrowTerminatingError(
                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                ([System.Management.Automation.SetValueException]"Configure second ethernet adapter on vSphere Replication appliance ($hmsAVmName): POST_VALIDATION_FAILED"),
                                                                'Set-DRSolutionNetworkAdapter',
                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                ""
                                                            )
                                                        )     
                                                    }
                                                    Try {
                                                        $scriptCommand = "sed -i '/Gateway.*/a Metric=1024' /etc/systemd/network/10-eth1.network"
                                                        $output = Invoke-VMScript -ScriptType bash -VM $hmsAVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vSRApplianceRootPassSiteA -Server $siteAVcenterDetails.fqdn    
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                    Try {
                                                        $scriptCommand = "echo -e '[Route]\nGateway=$eth1GatewaySiteA\nDestination=$eth1SubnetSiteB' >> /etc/systemd/network/10-eth1.network | systemctl restart systemd-networkd"
                                                        $output = Invoke-VMScript -ScriptType bash -VM $hmsAVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vSRApplianceRootPassSiteA -Server $siteAVcenterDetails.fqdn    
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                    Try {
                                                        $scriptCommand = "cat /etc/systemd/network/10-eth1.network"
                                                        $output = Invoke-VMScript -ScriptType bash -VM $hmsAVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vSRApplianceRootPassSiteA -Server $siteAVcenterDetails.fqdn
                                                        if (!($output.ScriptOutput -match "Gateway=$eth1GatewaySiteA") -or !($output.ScriptOutput -match "Destination=$ethSubnetSiteB")) {                                                
                                                            $PSCmdlet.ThrowTerminatingError(
                                                                [System.Management.Automation.ErrorRecord]::new(
                                                                    ([System.Management.Automation.SetValueException]"Set static route for remote vSphere Replication network ($eth1SubnetSiteB): POST_VALIDATION_FAILED"),
                                                                    'Set-vSRNetworkConfig',
                                                                    [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                    ""
                                                                )
                                                            )
                                                        } 
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                    Set-vSRIncomingStorageTraffic -fqdn $hmsAFqdn -username admin -password $vSRApplianceAdminPassSiteA -ipAddress $eth1IpAddressSiteA -ErrorAction SilentlyContinue | Out-Null
                                                    $incomingStorageTrafficHmsA = Get-vSRIncomingStorageTraffic -fqdn $hmsAFqdn -username admin -password $vSRApplianceAdminPassSiteA
                                                    if (!($incomingStorageTrafficHmsA.filterIp -match $eth1IpAddressSiteA)) {                                                
                                                        $PSCmdlet.ThrowTerminatingError(
                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                ([System.Management.Automation.SetValueException]"Set incoming storage traffic IP address for vSphere Replication appliance ($hmsAVmName): POST_VALIDATION_FAILED"),
                                                                'Set-vSRIncomingStorageTraffic',
                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                ""
                                                            )
                                                        )
                                                    } else {
                                                        Write-Output "Configure vSphere Replication appliance ($hmsAVmName) secondary ethernet adapter: SUCCESSFUL"
                                                    }
                                                } else {
                                                    Write-Warning "vSphere Replication appliance ($hmsAVmName) has more than one ethernet adapter: SKIPPING"
                                                }
                                                $hmsBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcHms"}).Server.Url -Split "//" -Split ":")[2]
                                                $VDPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $eth1VLANSiteB}
                                                if (!$VDPortGroupSiteB) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"No distributed virtual port group with VLAN ID ($eth1VLANSiteB) exists: PRE_VALIDATION_FAILED"),
                                                            'Get-VDPortGroup',
                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                            ""
                                                        )
                                                    )                                                
                                                }
                                                if ($VDPortGroupSiteB.Count -gt 1) {
                                                    $VDPortGroupSiteB = $VDPortGRoupSiteB | Where-Object {$_.Name -match "vrms"}  
                                                }
                                                $hmsBVmName = $hmsBFqdn.Split(".")[0]
                                                $numEthAdaptersB = (Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName | Get-NetworkAdapter).Count
                                                if ($numEthAdaptersB -le 1) {
                                                    $addEth1 = Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName | New-NetworkAdapter -Server $siteBvCenterDetails.fqdn -NetworkName $VDPortGroupSiteB.Name -Type vmxnet3 -StartConnected:$true -Confirm:$false -WarningAction SilentlyContinue
                                                    if (!$addEth1) {
                                                        $PSCmdlet.ThrowTerminatingError(
                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                ([System.Management.Automation.SetValueException]"Create ethernet adapter on vSphere Replication appliance ($hmsBVmName): POST_VALIDATION_FAILED"),
                                                                'New-NetworkAdapter',
                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                ""
                                                            )
                                                        )       
                                                    }
                                                    [int]$hmsBCidr = $eth1SubnetSiteB.Split("/")[1]
                                                    Set-DRSolutionNetworkAdapter -fqdn $hmsBFqdn -user admin -password $vSRApplianceAdminPassSiteB -interfaceName eth1 -defaultGateway $eth1GatewaySiteB -cidrPrefix $hmsBCidr -ipAddress $eth1IpAddressSiteB -ErrorAction Stop | Out-Null
                                                    Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName | Restart-VMGuest -Confirm:$False | Out-Null
                                                    Do {
                                                        Start-Sleep -Seconds 1
                                                        $vmRestart = Get-VMGuest -Server $siteBvCenterDetails.fqdn -VM $hmsBVmName
                                                        $vamiStatus = Test-VAMIAuthentication -server $hmsBFqdn -user admin -pass $vSRApplianceAdminPassSiteB -ErrorAction SilentlyContinue
                                                    }
                                                    Until (($vmRestart.State -eq "Running") -and ($vamiStatus -eq $true))
                                                    $hmsBNetConfig = ((Get-DRSolutionNetworkConfig -fqdn $hmsBFqdn -user admin -password $vSRApplianceAdminPassSiteB).Interfaces | Where-Object {$_.Name -eq "eth1"}).ipv4
                                                    if (($hmsBNetConfig.defaultGateway -ne $eth1GatewaySiteB) -or ($hmsBNetConfig.prefix -ne $hmsBCidr) -or ($hmsBNetConfig.address -ne $eth1IpAddressSiteB) -or ($trySetHmsBNetConfig.successful -eq $false)) {
                                                        $PSCmdlet.ThrowTerminatingError(
                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                ([System.Management.Automation.SetValueException]"Configure second ethernet adapter on vSphere Replication appliance ($hmsBVmName): POST_VALIDATION_FAILED"),
                                                                'Set-DRSolutionNetworkAdapter',
                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                ""
                                                            )
                                                        )     
                                                    }
                                                    Try {
                                                        $scriptCommand = "sed -i '/Gateway.*/a Metric=1024' /etc/systemd/network/10-eth1.network"
                                                        $output = Invoke-VMScript -ScriptType bash -VM $hmsBVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vSRApplianceRootPassSiteB -Server $siteBVcenterDetails.fqdn  
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                    Try {
                                                        $scriptCommand = "echo -e '[Route]\nGateway=$eth1GatewaySiteB\nDestination=$eth1SubnetSiteA' >> /etc/systemd/network/10-eth1.network | systemctl restart systemd-networkd"
                                                        $output = Invoke-VMScript -ScriptType bash -VM $hmsBVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vSRApplianceRootPassSiteB -Server $siteBVcenterDetails.fqdn
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                    Try {
                                                        $scriptCommand = "cat /etc/systemd/network/10-eth1.network"
                                                        $output = Invoke-VMScript -ScriptType bash -VM $hmsBVmName -ScriptText $scriptCommand -GuestUser root -GuestPassword $vSRApplianceRootPassSiteB -Server $siteBVcenterDetails.fqdn
                                                        if (!($output.ScriptOutput -match "Gateway=$eth1GatewaySiteB") -or !($output.ScriptOutput -match "Destination=$ethSubnetSiteA")) {
                                                            $PSCmdlet.ThrowTerminatingError(
                                                                [System.Management.Automation.ErrorRecord]::new(
                                                                    ([System.Management.Automation.SetValueException]"Set static route for remote vSphere Replication network ($($eth1SubnetSiteA)): POST_VALIDATION_FAILED"),
                                                                    'Set-vSRNetworkConfig',
                                                                    [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                    ""
                                                                )
                                                            )
                                                        }
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                    Set-vSRIncomingStorageTraffic -fqdn $hmsBFqdn -username admin -password $vSRApplianceAdminPassSiteB -ipAddress $eth1IpAddressSiteB -ErrorAction SilentlyContinue | Out-Null
                                                    $incomingStorageTrafficHmsB = Get-vSRIncomingStorageTraffic -fqdn $hmsBFqdn -username admin -password $vSRApplianceAdminPassSiteB
                                                    if (!($incomingStorageTrafficHmsB.filterIp -match $eth1IpAddressSiteB)) {                                                
                                                        $PSCmdlet.ThrowTerminatingError(
                                                            [System.Management.Automation.ErrorRecord]::new(
                                                                ([System.Management.Automation.SetValueException]"Set incoming storage traffic IP address for vSphere Replication appliance ($hmsBVmName): POST_VALIDATION_FAILED"),
                                                                'Set-vSRIncomingStorageTraffic',
                                                                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                ""
                                                            )
                                                        )
                                                    } else {
                                                        Write-Output "Configure vSphere Replication appliance ($hmsBVmName) secondary ethernet adapter: SUCCESSFUL"
                                                    }
                                                } else {
                                                    Write-Warning "vSphere Replication appliance ($hmsBVmName) has more than one ethernet adapter: SKIPPING"
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Set-vSRNetworkConfig

Function Undo-vSRNetworkConfig {
    <#
        .SYNOPSIS
        Removes the secondary ethernet adapter and configures the required routing for vSphere Replication appliances
        in the protected and recovery sites

        .DESCRIPTION
        The Undo-vSRNetworkConfig cmdlet configures the secondary ethernet adapter and configures the required routing
        for vSphere Replication appliances in the protected and recovery sites. The cmdlet connects to SDDC Manager in
        both the protected and recovery sites using the -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass,
        -sddcManagerBFqdn, -sddcManagerBUser, and -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both vSphere Replication instances
        - Removes the secondary ethernet adapter and static routes for vSphere Replication appliances in the protected
        and recovery sites

        .EXAMPLE
        Undo-vSRNetworkConfig -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -siteAVLAN 2715 -siteBVLAN 2815
        This example removes the secondary ethernet adapter and static routes for vSphere Replication appliances in the protected and recovery sites
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteAVLAN,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteBVLAN
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            if (Test-VCFConnection -server $sddcManagerBFqdn) {
                                if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                                    if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                                        if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                                            if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                                                $hmsAFqdn = (((Get-View -server $siteAvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcHms"}).Server.Url -Split "//" -Split ":")[2]
                                                $VDPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $siteAVLAN}
                                                if (!$VDPortGroupSiteA) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"No distributed virtual port group with VLAN ID ($siteAVLAN) exists: PRE_VALIDATION_FAILED"),
                                                            'Get-VDPortGroup',
                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                            ""
                                                        )
                                                    )                                                
                                                } else {
                                                    Try {
                                                        $hmsAVmName = $hmsAFqdn.Split(".")[0]
                                                        $numEthAdaptersA = (Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName | Get-NetworkAdapter).Count
                                                        if ($numEthAdaptersA -gt 1) {
                                                            Try {
                                                                $managementIpA = ((Get-DRSolutionNetworkConfig -fqdn $hmsAFqdn -username admin -password $vSRApplianceAdminPassSiteA).Interfaces.Ipv4 | Where-Object {$_.InterfaceName -eq "eth0"}).address
                                                                Set-vSRIncomingStorageTraffic -fqdn $hmsAFqdn -username admin -password $vSRApplianceAdminPassSiteA -ipAddress $managementIpA -ErrorAction SilentlyContinue | Out-Null
                                                                $incomingStorageTrafficHmsA = Get-vSRIncomingStorageTraffic -fqdn $hmsAFqdn -username admin -password $vSRApplianceAdminPassSiteA
                                                                if (!($incomingStorageTrafficHmsA.filterIp -match $managementIpA)) {                                                
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.SetValueException]"Set incoming storage traffic IP address for vSphere Replication appliance ($hmsAVmName): POST_VALIDATION_FAILED"),
                                                                            'Set-vSRIncomingStorageTraffic',
                                                                            [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                            if ($VDPortGroupSiteA.Count -gt 1) {
                                                                $VDPortGroupSiteA = $VDPortGRoupSiteA | Where-Object {$_.Name -match "vrms"}  
                                                            }
                                                            $hmsAVmPowerState = (Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName).PowerState
                                                            if ($hmsAVmPowerState -eq "PoweredOn") {
                                                                Stop-VMGuest -Server $siteAvCenterDetails.fqdn -VM $hmsAVmName -Confirm:$false -ErrorAction Stop | Out-Null
                                                                Do {
                                                                    Start-Sleep -Seconds 1
                                                                    $hmsAVmState = Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName
                                                                }
                                                                Until ($hmsAVmState.PowerState -eq "PoweredOff")
                                                            }
                                                            Try {
                                                                Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName | Get-NetworkAdapter | Where-Object {$_.NetworkName -eq $VDPortGroupSiteA.Name} | Remove-NetworkAdapter -Confirm:$false -WarningAction SilentlyContinue | Out-Null
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                            $validateRemovedEth1SiteA = Get-VM -Server $siteAvCenterDetails.fqdn -Name $hmsAVmName | Get-NetworkAdapter | Where-Object {$_.NetworkName -eq $VDPortGroupSiteA}
                                                            if ($validateRemovedEth1SiteA) {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.SetValueException]"Remove ethernet adapter on vSphere Replication appliance ($hmsAVmName): POST_VALIDATION_FAILED"),
                                                                        'Remove-NetworkAdapter',
                                                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                                        ""
                                                                    )
                                                                )       
                                                            } else {
                                                                Try {
                                                                    Start-VM -Server $siteAvCenterDetails.fqdn -VM $hmsAVmName -Confirm:$false -ErrorAction Stop | Out-Null
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                            }
                                                            Write-Output "Remove secondary ethernet adapter from vSphere Replication appliance ($hmsAVmName): SUCCESSFUL"
                                                        } else {
                                                            Write-Warning "vSphere Replication appliance ($hmsAVmName) only has one ethernet adapter: SKIPPING"
                                                        }
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                }
                                                $hmsBFqdn = (((Get-View -server $siteBvCenterDetails.fqdn ExtensionManager).ExtensionList | Where-Object {$_.key -eq "com.vmware.vcHms"}).Server.Url -Split "//" -Split ":")[2]
                                                $VDPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {$_.VlanConfiguration.VlanId -eq $siteBVLAN}
                                                if (!$VDPortGroupSiteB) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"No distributed virtual port group with VLAN ID ($siteBVLAN) exists: PRE_VALIDATION_FAILED"),
                                                            'Get-VDPortGroup',
                                                            [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                                            ""
                                                        )
                                                    )                                                
                                                } else {
                                                    Try {
                                                        $hmsBVmName = $hmsBFqdn.Split(".")[0]
                                                        $numEthAdaptersB = (Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName | Get-NetworkAdapter).Count
                                                        if ($numEthAdaptersB -gt 1) {
                                                            Try {
                                                                $managementIpB = ((Get-DRSolutionNetworkConfig -fqdn $hmsBFqdn -username admin -password $vSRApplianceAdminPassSiteB).Interfaces.Ipv4 | Where-Object {$_.InterfaceName -eq "eth0"}).address
                                                                Set-vSRIncomingStorageTraffic -fqdn $hmsBFqdn -username admin -password $vSRApplianceAdminPassSiteB -ipAddress $managementIpB -ErrorAction SilentlyContinue | Out-Null
                                                                $incomingStorageTrafficHmsB = Get-vSRIncomingStorageTraffic -fqdn $hmsBFqdn -username admin -password $vSRApplianceAdminPassSiteB
                                                                if (!($incomingStorageTrafficHmsB.filterIp -match $managementIpB)) {                                                
                                                                    $PSCmdlet.ThrowTerminatingError(
                                                                        [System.Management.Automation.ErrorRecord]::new(
                                                                            ([System.Management.Automation.SetValueException]"Set incoming storage traffic IP address for vSphere Replication appliance ($hmsBVmName): POST_VALIDATION_FAILED"),
                                                                            'Set-vSRIncomingStorageTraffic',
                                                                            [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                            ""
                                                                        )
                                                                    )
                                                                }
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                            if ($VDPortGroupSiteB.Count -gt 1) {
                                                                $VDPortGroupSiteB = $VDPortGRoupSiteB | Where-Object {$_.Name -match "vrms"}  
                                                            }
                                                            $hmsBVmPowerState = (Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName).PowerState
                                                            if ($hmsBVmPowerState -eq "PoweredOn") {
                                                                Stop-VMGuest -Server $siteBvCenterDetails.fqdn -VM $hmsBVmName -Confirm:$false -ErrorAction Stop | Out-Null
                                                                Do {
                                                                    Start-Sleep -Seconds 1
                                                                    $hmsBVmState = Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName
                                                                }
                                                                Until ($hmsBVmState.PowerState -eq "PoweredOff")
                                                            }
                                                            Try {
                                                                Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName | Get-NetworkAdapter | Where-Object {$_.NetworkName -eq $VDPortGroupSiteB} | Remove-NetworkAdapter -Confirm:$false -WarningAction SilentlyContinue | Out-Null
                                                            } Catch {
                                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                                            }
                                                            $validateRemovedEth1SiteB = Get-VM -Server $siteBvCenterDetails.fqdn -Name $hmsBVmName | Get-NetworkAdapter | Where-Object {$_.NetworkName -eq $VDPortGroupSiteB}
                                                            if ($validateRemovedEth1SiteB) {
                                                                $PSCmdlet.ThrowTerminatingError(
                                                                    [System.Management.Automation.ErrorRecord]::new(
                                                                        ([System.Management.Automation.SetValueException]"Remove ethernet adapter on vSphere Replication appliance ($hmsBVmName): POST_VALIDATION_FAILED"),
                                                                        'Remove-NetworkAdapter',
                                                                        [System.Management.Automation.ErrorCategory]::InvalidOperation,
                                                                        ""
                                                                    )
                                                                )       
                                                            } else {
                                                                Try {
                                                                    Start-VM -Server $siteBvCenterDetails.fqdn -VM $hmsBVmName -Confirm:$false -ErrorAction Stop | Out-Null
                                                                } Catch {
                                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                                }
                                                            }
                                                            Write-Output "Remove secondary ethernet adapter from vSphere Replication appliance ($hmsBVmName): SUCCESSFUL"
                                                        } else {
                                                            Write-Warning "vSphere Replication appliance ($hmsBVmName) only has one ethernet adapter: SKIPPING"
                                                        }
                                                    } Catch {
                                                        $PSCmdlet.ThrowTerminatingError($PSItem)
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vSRNetworkConfig

Function New-vSRVMkernelPort {
    <#
        .SYNOPSIS
        Create VMkernel ports on ESXi hosts for vSphere Replication traffic in the protected and recovery sites

        .DESCRIPTION
        The New-vSRVMKernelPort cmdlet creates VMkernel ports on ESXi hosts for vSphere Replication traffic in the
        protected and recovery sites. The cmdlet connects to SDDC Manager in both the protected and recovery sites
        using the -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and
        -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Creates VMkernel ports on ESXi hosts for vSphere Replication traffic in the protected and recovery sites
        defined in -siteAVLAN, -siteBVLAN, -siteANetMask, -siteBNetMask, -siteAIpAddresses, and -siteBIpAddresses
        paramters.

        .EXAMPLE
        New-vSRVMkernelPort -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -siteAVLAN 2715 -siteBVLAN 2815 -siteANetMask 255.255.255.0 -siteBNetMask 255.255.255.0 -siteAIpAddresses @("172.27.15.101","172.27.15.102","172.27.15.103","172.27.15.104") -siteBIpAddresses @("172.28.15.101","172.28.15.102","172.28.15.103","172.28.15.104")
        This example creates a VMkernel port on VLAN ID 2715 for each ESXi host in the protected site VCF management domain and a VMkernel port on VLAN ID 2815 for each ESXi host in the recovery site VCF management domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteAVLAN,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteBVLAN,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteANetMask,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteBNetMask,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$siteAIpAddresses,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Array]$siteBIpAddresses
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteAVLAN)}
                            $existingVDSwitchSiteA = Get-VDSwitch -Server $siteAvCenterDetails.fqdn -Name $existingPortGroupSiteA.VDSwitch
                            if (!$existingPortGroupSiteA) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteAVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteA.Count -gt 1) {
                                    $existingPortGroupSiteA = $existingPortGroupSiteA | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteAVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                Foreach ($siteAVMhost in $siteAVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -VMHost $siteAVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if (!$existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteAVMhost.fqdn
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "All ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) already configured with VMkernel port for vSphere Replication traffic: SKIPPING"
                                } else {
                                    if ($vmHostsToConfigure.Count -ne $siteAIpAddresses.Count) {
                                        $PSCmdlet.ThrowTerminatingError(
                                            [System.Management.Automation.ErrorRecord]::new(
                                                ([System.Management.Automation.SetValueException]"The number of IP addresses supplied for VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) and the number of ESXi hosts to be configured do not match: PRE_VALIDATION_FAILED"),
                                                'Add-vSRVMkernelPort',
                                                [System.Management.Automation.ErrorCategory]::InvalidArgument,
                                                ""
                                            )
                                        )
                                    } else {
                                        For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                            Try {
                                                New-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i] -VirtualSwitch $existingVDSwitchSiteA.Name -PortGroup $existingPortGroupSiteA.Name -ErrorAction Stop | Set-VMHostNetworkAdapter -IP $siteAIpAddresses[$i] -SubnetMask $siteANetMask -vSphereReplicationEnabled:$true -vSphereReplicationNfcEnabled:$true -Confirm:$false -ErrorAction Stop | Out-Null
                                            } Catch {
                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                            }
                                        }
                                        $validateVMkernelCreated = @()
                                        $validateVMkernelCreated = Get-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -VirtualSwitch $existingVDSwitchSiteA.Name -PortGroup $existingPortGroupSiteA.Name | Where-Object {$_.VSphereReplicationEnabled -eq $true -and $_.VSphereReplicationNfcEnabled -eq $true}
                                        if ($validateVMkernelCreated.Count -ne $vmHostsToConfigure.Count) {
                                            $PSCmdlet.ThrowTerminatingError(
                                                [System.Management.Automation.ErrorRecord]::new(
                                                    ([System.Management.Automation.GetValueException]"Create VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) for vSphere Replication traffic: POST_VALIDATION_FAILED"),
                                                    'Add-vSRVMkernelPort',
                                                    [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                    ""
                                                )
                                            )
                                        } else {
                                            Write-Output "Create VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) for vSphere Replication traffic: SUCCESSFUL"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (Test-VCFConnection -server $sddcManagerBFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteBVLAN)}
                            $existingVDSwitchSiteB = Get-VDSwitch -Server $siteBvCenterDetails.fqdn -Name $existingPortGroupSiteB.VDSwitch
                            if (!$existingPortGroupSiteB) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteBVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteB.Count -gt 1) {
                                    $existingPortGroupSiteB = $existingPortGroupSiteB | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteBVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                Foreach ($siteBVMhost in $siteBVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $SiteBvCenterDetails.fqdn -VMHost $siteBVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if (!$existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteBVMhost.fqdn
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "All ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) already configured with VMkernel port for vSphere Replication traffic: SKIPPING"
                                } else {
                                    if ($vmHostsToConfigure.Count -ne $siteBIpAddresses.Count) {
                                        $PSCmdlet.ThrowTerminatingError(
                                            [System.Management.Automation.ErrorRecord]::new(
                                                ([System.Management.Automation.SetValueException]"The number of IP addresses supplied for VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) and the number of ESXi hosts to be configured do not match: PRE_VALIDATION_FAILED"),
                                                'Add-vSRVMkernelPort',
                                                [System.Management.Automation.ErrorCategory]::InvalidArgument,
                                                ""
                                            )
                                        )
                                    } else {
                                        For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                            Try {
                                                New-VMHostNetworkAdapter -Server $siteBvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i] -VirtualSwitch $existingVDSwitchSiteB.Name -PortGroup $existingPortGroupSiteB.Name -ErrorAction Stop | Set-VMHostNetworkAdapter -IP $siteBIpAddresses[$i] -SubnetMask $siteBNetMask -vSphereReplicationEnabled:$true -vSphereReplicationNfcEnabled:$true -Confirm:$false -ErrorAction Stop | Out-Null
                                            } Catch {
                                                $PSCmdlet.ThrowTerminatingError($PSItem)
                                            }
                                        }
                                        $validateVMkernelCreated = @()
                                        $validateVMkernelCreated = Get-VMHostNetworkAdapter -Server $SiteBvCenterDetails.fqdn -VirtualSwitch $existingVDSwitchSiteB.Name -PortGroup $existingPortGroupSiteB.Name | Where-Object {$_.VSphereReplicationEnabled -eq $true -and $_.VSphereReplicationNfcEnabled -eq $true}
                                        if ($validateVMkernelCreated.Count -ne $vmHostsToConfigure.Count) {
                                            $PSCmdlet.ThrowTerminatingError(
                                                [System.Management.Automation.ErrorRecord]::new(
                                                    ([System.Management.Automation.GetValueException]"Create VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) for vSphere Replication traffic: POST_VALIDATION_FAILED"),
                                                    'Add-vSRVMkernelPort',
                                                    [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                    ""
                                                )
                                            )
                                        } else {
                                            Write-Output "Create VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) for vSphere Replication traffic: SUCCESSFUL"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vSRVMKernelPort

Function Undo-vSRVMkernelPort {
    <#
        .SYNOPSIS
        Remove VMkernel ports on ESXi hosts for vSphere Replication traffic in the protected and recovery sites

        .DESCRIPTION
        The Undo-vSRVMKernelPort cmdlet removes VMkernel ports on ESXi hosts for vSphere Replication traffic in the
        protected and recovery sites. The cmdlet connects to SDDC Manager in both the protected and recovery sites
        using the -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and
        -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Removes VMkernel ports on ESXi hosts for vSphere Replication traffic in the protected and recovery sites that
        match the VLAN IDs defined in -siteAVLAN and -siteBVLAN paramters.

        .EXAMPLE
        Undo-vSRVMkernelPort -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -siteAVLAN 2715 -siteBVLAN 2815
        This example removes VMkernel ports on VLAN ID 2715 in the protected site VCF management domain and VMkernel ports on VLAN ID 2815 in the recovery site VCF management domain
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteAVLAN,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteBVLAN
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteAVLAN)}
                            $existingVDSwitchSiteA = Get-VDSwitch -Server $siteAvCenterDetails.fqdn -Name $existingPortGroupSiteA.VDSwitch
                            if (!$existingPortGroupSiteA) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteAVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteA.Count -gt 1) {
                                    $existingPortGroupSiteA = $existingPortGroupSiteA | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteAVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                foreach ($siteAVMhost in $siteAVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -VMHost $siteAVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if ($existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteAVMhost.fqdn
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) do not have a VMkernel port configured for vSphere Replication traffic on VLAN ID ($siteAVLAN): SKIPPING"
                                } else {
                                    For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                        Try {
                                            Get-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i] -PortGroup $existingPortGroupSiteA -ErrorAction Stop | Remove-VMHostNetworkAdapter -Confirm:$false -ErrorAction Stop
                                        } Catch {
                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                        }
                                    }
                                    $validateVMkernelRemoved = @()
                                    $validateVMkernelRemoved = Get-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -PortGroup $existingPortGroupSiteA | Where-Object {$_.VSphereReplicationEnabled -eq $true -or $_.VSphereReplicationNfcEnabled -eq $true}
                                    if ($validateVMkernelRemoved.Count -gt 0) {
                                        $PSCmdlet.ThrowTerminatingError(
                                            [System.Management.Automation.ErrorRecord]::new(
                                                ([System.Management.Automation.GetValueException]"Remove VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) for vSphere Replication traffic: POST_VALIDATION_FAILED"),
                                                'Undo-vSRVMkernelPort',
                                                [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                ""
                                            )
                                        )
                                    } else {
                                        Write-Output "Remove VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) for vSphere Replication traffic: SUCCESSFUL"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (Test-VCFConnection -server $sddcManagerBFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteBVLAN)}
                            if (!$existingPortGroupSiteB) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteBVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteB.Count -gt 1) {
                                    $existingPortGroupSiteB = $existingPortGroupSiteB | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteBVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                Foreach ($siteBVMhost in $siteBVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $siteBvCenterDetails.fqdn -VMHost $siteBVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if ($existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteBVMhost.fqdn
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) do not have a VMkernel port configured for vSphere Replication traffic on VLAN ID ($siteBVLAN): SKIPPING"
                                } else {
                                    For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                        Try {
                                            Get-VMHostNetworkAdapter -Server $SiteBvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i] -PortGroup $existingPortGroupSiteB -ErrorAction Stop | Remove-VMHostNetworkAdapter -Confirm:$false -ErrorAction Stop
                                        } Catch {
                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                        }
                                    }
                                    $validateVMkernelRemoved = @()
                                    $validateVMkernelRemoved = Get-VMHostNetworkAdapter -Server $SiteBvCenterDetails.fqdn -PortGroup $existingPortGroupSiteB | Where-Object {$_.VSphereReplicationEnabled -eq $true -or $_.VSphereReplicationNfcEnabled -eq $true}
                                    if ($validateVMkernelRemoved.Count -gt 0) {
                                        $PSCmdlet.ThrowTerminatingError(
                                            [System.Management.Automation.ErrorRecord]::new(
                                                ([System.Management.Automation.GetValueException]"Remove VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) for vSphere Replication traffic: POST_VALIDATION_FAILED"),
                                                'Undo-vSRVMkernelPort',
                                                [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                ""
                                            )
                                        )
                                    } else {
                                        Write-Output "Remove VMkernel ports for ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) for vSphere Replication traffic: SUCCESSFUL"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vSRVMKernelPort

Function New-vSREsxiStaticRoute {
    <#
        .SYNOPSIS
        Create a static route on ESXi hosts for vSphere Replication traffic in the protected and recovery sites

        .DESCRIPTION
        The New-vSREsxiStaticRoute cmdlet creates a static route on ESXi hosts for vSphere Replication traffic in the
        protected and recovery sites. The cmdlet connects to SDDC Manager in both the protected and recovery sites
        using the -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and
        -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Creates static routes on ESXi hosts for vSphere Replication traffic in the protected and recovery sites
        defined in -siteAVLAN, -siteBVLAN, -siteASubnet, -siteBSubnet, -siteAGateway, and -siteBGateway paramters.

        .EXAMPLE
        New-vSREsxiStaticRoute -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -siteAVLAN 2715 -siteBVLAN 2815 -siteASubnet 172.27.15.0/24 -siteBSubnet 172.28.15.0/24 -siteAGateway 172.27.15.1 -siteBGateway 172.28.15.1
        This example adds a static route to each ESXi host in the protected site VCF Management Domain to the recovery site vSphere Replication subnet (172.28.15.0/24) via the protected site vSphere Replication network gateway (172.27.15.1).
        This example also adds a static route to each ESXi host in the recovery site VCF Management Domain to the protected site vSphere Replication subnet (172.27.15.0/24) via the recovery site vSphere Replication network gateway (172.28.15.1).
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteAVLAN,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteBVLAN,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteASubnet,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteBSubnet,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteAGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteBGateway
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteAVLAN)}
                            $siteANetwork = $siteASubnet.Split("/")[0]
                            $siteACidr = $siteASubnet.Split("/")[1]
                            [ipaddress] $siteANetmaskStub = 0
                            $siteANetmaskStub.Address = ([UInt32]::MaxValue) -shl (32 - $siteACidr) -shr (32 - $siteACidr)
                            $siteANetmask = $siteANetmaskStub.IPAddressToString
                            $siteBNetwork = $siteBSubnet.Split("/")[0]
                            $siteBCidr = $siteBSubnet.Split("/")[1]
                            [ipaddress] $siteBNetmaskStub = 0
                            $siteBNetmaskStub.Address = ([UInt32]::MaxValue) -shl (32 - $siteBCidr) -shr (32 - $siteBCidr)
                            $siteBNetmask = $siteBNetmaskStub.IPAddressToString
                            if (!$existingPortGroupSiteA) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteAVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteA.Count -gt 1) {
                                    $existingPortGroupSiteA = $existingPortGroupSiteA | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteAVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                Foreach ($siteAVMhost in $siteAVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -VMHost $siteAVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if ($existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteAVMhost
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) are not configured with a VMkernel port for vSphere Replication traffic: SKIPPING"
                                } else {
                                    For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                        Try {
                                            $esxcli = Get-EsxCli -Server $SiteAvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i].fqdn -V2 -ErrorAction Stop
                                            $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                            $skipAdd = $null
                                            Foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                if (($existingStaticRoute.gateway -eq $siteAGateway) -and ($existingStaticRoute.network -eq $siteBNetwork) -and ($existingStaticRoute.netmask -eq $siteBNetmask)) {
                                                    $skipAdd = $true
                                                    $skipCountSiteA++
                                                }
                                            }
                                            if (!$skipAdd) {
                                                Try {
                                                    $newStaticRouteArgs = $null
                                                    $newStaticRouteArgs = $esxcli.network.ip.route.ipv4.add.CreateArgs()
                                                    $newStaticRouteArgs.gateway = $siteAGateway
                                                    $newStaticRouteArgs.network = $siteBSubnet
                                                    $esxcli.network.ip.route.ipv4.add.Invoke($newStaticRouteArgs) | Out-Null
                                                } Catch {
                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                }
                                                $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                                $staticRouteValidated = $null
                                                Foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                    if (($existingStaticRoute.gateway -eq $siteAGateway) -and ($existingStaticRoute.network -eq $siteBNetwork) -and ($existingStaticRoute.netmask -eq $siteBNetmask)) {
                                                        $staticRouteValidated = $true
                                                    }
                                                }
                                                if (!$staticRouteValidated) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"Unable to validate static route for vSphere Replication has been added to ESXi host ($($vmHostsToConfigure[$i].fqdn)): POST_VALIDATION_FAILED"),
                                                            'New-vSREsxiStaticRoute',
                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                            ""
                                                        )
                                                    )
                                                } else {
                                                    Write-Output "Add static route vSphere Replication traffic on ESXi host ($($vmHostsToConfigure[$i].fqdn)): SUCCESSFUL"
                                                }
                                            } else {
                                                Write-Warning "Static route for vSphere Replication traffic already exists on ESXi host ($($vmHostsToConfigure[$i].fqdn)): SKIPPING"
                                            }
                                        }
                                        Catch {
                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (Test-VCFConnection -server $sddcManagerBFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteBVLAN)}
                            if (!$existingPortGroupSiteB) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteBVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteB.Count -gt 1) {
                                    $existingPortGroupSiteB = $existingPortGroupSiteB | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteBVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                Foreach ($siteBVMhost in $siteBVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $SiteBvCenterDetails.fqdn -VMHost $siteBVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if ($existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteBVMhost
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) are not configured with a VMkernel port for vSphere Replication traffic: SKIPPING"
                                } else {
                                    For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                        Try {
                                            $esxcli = Get-EsxCli -Server $SiteBvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i].fqdn -V2 -ErrorAction Stop
                                            $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                            $skipAdd = $null
                                            Foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                if (($existingStaticRoute.gateway -eq $siteBGateway) -and ($existingStaticRoute.network -eq $siteANetwork) -and ($existingStaticRoute.netmask -eq $siteANetmask)) {
                                                    $skipAdd = $true
                                                }
                                            }
                                            if (!$skipAdd) {
                                                Try {
                                                    $newStaticRouteArgs = $null
                                                    $newStaticRouteArgs = $esxcli.network.ip.route.ipv4.add.CreateArgs()
                                                    $newStaticRouteArgs.gateway = $siteBGateway
                                                    $newStaticRouteArgs.network = $siteASubnet
                                                    $esxcli.network.ip.route.ipv4.add.Invoke($newStaticRouteArgs) | Out-Null
                                                } Catch {
                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                }
                                                $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                                $staticRouteValidated = $null
                                                Foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                    if (($existingStaticRoute.gateway -eq $siteBGateway) -and ($existingStaticRoute.network -eq $siteANetwork) -and ($existingStaticRoute.netmask -eq $siteANetmask)) {
                                                        $staticRouteValidated = $true
                                                    }
                                                }
                                                if (!$staticRouteValidated) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"Unable to validate static route for vSphere Replication has been added to ESXi host ($($vmHostsToConfigure[$i])): POST_VALIDATION_FAILED"),
                                                            'New-vSREsxiStaticRoute',
                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                            ""
                                                        )
                                                    )
                                                } else {
                                                    Write-Output "Add static route vSphere Replication traffic on ESXi host ($($vmHostsToConfigure[$i].fqdn)): SUCCESSFUL"
                                                }
                                            } else {
                                                Write-Warning "Static route for vSphere Replication traffic already exists on ESXi host ($($vmHostsToConfigure[$i].fqdn)): SKIPPING"
                                            }
                                        } Catch {
                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                        } 
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function New-vSREsxiStaticRoute

Function Undo-vSREsxiStaticRoute {
    <#
        .SYNOPSIS
        Remove a static route from ESXi hosts for vSphere Replication traffic in the protected and recovery sites

        .DESCRIPTION
        The Undo-vSREsxiStaticRoute cmdlet removes a static route from ESXi hosts for vSphere Replication traffic in the
        protected and recovery sites. The cmdlet connects to SDDC Manager in both the protected and recovery sites
        using the -sddcManagerAFqdn, -sddcManagerAUser, -sddcManagerAPass, -sddcManagerBFqdn, -sddcManagerBUser, and
        -sddcManagerBPass values:
        - Validates that network connectivity and authentication is possible to both SDDC Manager instances
        - Validates that network connectivity and authentication is possible to both vCenter Server instances
        - Validates that network connectivity and authentication are possible to both Site Recovery Manager instances
        - Removes a static route on ESXi hosts for vSphere Replication traffic in the protected and recovery sites
        defined in -siteAVLAN, -siteBVLAN, -siteASubnet, -siteBSubnet, -siteAGateway, and -siteBGateway paramters.

        .EXAMPLE
        Undo-vSREsxiStaticRoute -sddcManagerAFqdn sfo-vcf01.sfo.rainpole.io -sddcManagerAUser administrator@vsphere.local -sddcManagerAPass VMw@re1! -sddcManagerBFqdn lax-vcf01.lax.rainpole.io -sddcManagerBUser administrator@vsphere.local -sddcManagerBPass VMw@re1! -siteAVLAN 2715 -siteBVLAN 2815 -siteASubnet 172.27.15.0/24 -siteBSubnet 172.28.15.0/24 -siteAGateway 172.27.15.1 -siteBGateway 172.28.15.1
        This example removes a static route, if present, from each ESXi host in the protected site VCF Management Domain from the protected site to the recovery site vSphere Replication subnet (172.28.15.0/24) via the protected site vSphere Replication network gateway (172.27.15.1).
        This example also removes a static route, if present, from each ESXi host in the recovery site VCF Management Domain from the recovery site to the protected site vSphere Replication subnet (172.27.15.0/24) via the recovery site vSphere Replication network gateway (172.28.15.1).
    #>


    Param (
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerAPass,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBFqdn,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBUser,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$sddcManagerBPass,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteAVLAN,
        [Parameter (Mandatory = $true)] [ValidateRange(0,4094)] [Int]$siteBVLAN,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteASubnet,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteBSubnet,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteAGateway,
        [Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$siteBGateway
    )

    Try {
        if (Test-VCFConnection -server $sddcManagerAFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass) {
                if (($siteAvCenterDetails = Get-vCenterServerDetail -server $sddcManagerAFqdn -user $sddcManagerAUser -pass $sddcManagerAPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteAvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteAvCenterDetails.fqdn -user $siteAvCenterDetails.ssoAdmin -pass $siteAvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteA = Get-VDPortGroup -Server $siteAvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteAVLAN)}
                            $siteANetwork = $siteASubnet.Split("/")[0]
                            $siteACidr = $siteASubnet.Split("/")[1]
                            [ipaddress] $siteANetmaskStub = 0
                            $siteANetmaskStub.Address = ([UInt32]::MaxValue) -shl (32 - $siteACidr) -shr (32 - $siteACidr)
                            $siteANetmask = $siteANetmaskStub.IPAddressToString
                            $siteBNetwork = $siteBSubnet.Split("/")[0]
                            $siteBCidr = $siteBSubnet.Split("/")[1]
                            [ipaddress] $siteBNetmaskStub = 0
                            $siteBNetmaskStub.Address = ([UInt32]::MaxValue) -shl (32 - $siteBCidr) -shr (32 - $siteBCidr)
                            $siteBNetmask = $siteBNetmaskStub.IPAddressToString
                            if (!$existingPortGroupSiteA) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteAVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteA.Count -gt 1) {
                                    $existingPortGroupSiteA = $existingPortGroupSiteA | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteAVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                Foreach ($siteAVMhost in $siteAVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $SiteAvCenterDetails.fqdn -VMHost $siteAVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if ($existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteAVMhost
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteAvCenterDetails.fqdn}).name)) are not configured with a VMkernel port for vSphere Replication traffic: SKIPPING"
                                } else {
                                    For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                        Try {
                                            $esxcli = Get-EsxCli -Server $SiteAvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i].fqdn -V2 -ErrorAction Stop
                                            $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                            $existingRouteToRemove = $null
                                            foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                if (($existingStaticRoute.gateway -eq $siteAGateway) -and ($existingStaticRoute.network -eq $siteBNetwork) -and ($existingStaticRoute.netmask -eq $siteBNetmask)) {
                                                    $existingRouteToRemove = $true
                                                }
                                            }
                                            if ($existingRouteToRemove) {
                                                Try {
                                                    $removeStaticRouteArgs = $null
                                                    $removeStaticRouteArgs = $esxcli.network.ip.route.ipv4.remove.CreateArgs()
                                                    $removeStaticRouteArgs.gateway = $siteAGateway
                                                    $removeStaticRouteArgs.network = $siteBSubnet
                                                    $esxcli.network.ip.route.ipv4.remove.Invoke($removeStaticRouteArgs) | Out-Null
                                                } Catch {
                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                }
                                                $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                                $staticRouteStillExists = $null
                                                foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                    if (($existingStaticRoute.gateway -eq $siteAGateway) -and ($existingStaticRoute.network -eq $siteBNetwork) -and ($existingStaticRoute.netmask -eq $siteBNetmask)) {
                                                        $staticRouteStillExists = $true
                                                    }
                                                }
                                                if ($staticRouteStillExists) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"Unable to validate static route for vSphere Replication has been removed from ESXi host ($($vmHostsToConfigure[$i].fqdn)): POST_VALIDATION_FAILED"),
                                                            'Undo-vSREsxiStaticRoute',
                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                            ""
                                                        )
                                                    )
                                                } else {
                                                    Write-Output "Remove static route vSphere Replication traffic on ESXi host ($($vmHostsToConfigure[$i].fqdn)): SUCCESSFUL"
                                                }
                                            } else {
                                                Write-Warning "Static route for vSphere Replication traffic does not exist on ESXi host ($($vmHostsToConfigure[$i].fqdn)): SKIPPING"
                                            }
                                        } Catch {
                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (Test-VCFConnection -server $sddcManagerBFqdn) {
            if (Test-VCFAuthentication -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass) {
                if (($siteBvCenterDetails = Get-vCenterServerDetail -server $sddcManagerBFqdn -user $sddcManagerBUser -pass $sddcManagerBPass -domainType MANAGEMENT)) {
                    if (Test-VsphereConnection -server $($siteBvCenterDetails.fqdn)) {
                        if (Test-VsphereAuthentication -server $siteBvCenterDetails.fqdn -user $siteBvCenterDetails.ssoAdmin -pass $siteBvCenterDetails.ssoAdminPass) {
                            $existingPortGroupSiteB = Get-VDPortGroup -Server $siteBvCenterDetails.fqdn | Where-Object {($_.VlanConfiguration.VlanId -eq $SiteBVLAN)}
                            if (!$existingPortGroupSiteB) {
                                $PSCmdlet.ThrowTerminatingError(
                                    [System.Management.Automation.ErrorRecord]::new(
                                        ([System.Management.Automation.GetValueException]"No Distributed Virtual PortGroup with the defined VLAN ID ($SiteBVLAN) found: PRE_VALIDATION_FAILED"),
                                        'Get-VDPortGroup',
                                        [System.Management.Automation.ErrorCategory]::ObjectNotFound,
                                        ""
                                    )
                                )                                                
                            } else {
                                if ($existingPortGroupSiteB.Count -gt 1) {
                                    $existingPortGroupSiteB = $existingPortGroupSiteB | Where-Object {$_.Name -match "vrms"}  
                                }
                                $siteBVMhosts =  Get-VCFHost | Where-Object {$_.cluster.id -eq ((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).clusters.id)}
                                $vmHostsToConfigure = @()
                                Foreach ($siteBVMhost in $siteBVMhosts) {
                                    $existingvSrVmkernel = $null
                                    $existingvSrVmkernel = Get-VMHostNetworkAdapter -Server $SiteBvCenterDetails.fqdn -VMHost $siteBVMhost.fqdn | Where-Object {$_.vSphereReplicationEnabled -eq $true}
                                    if ($existingvSrVmkernel) {
                                        $vmHostsToConfigure += $siteBVMhost
                                    }
                                }
                                if ($vmHostsToConfigure.Count -eq 0) {
                                    Write-Warning "ESXi hosts in VCF Management Domain ($((Get-VCFWorkloadDomain | Where-Object {$_.type -eq "MANAGEMENT" -and $_.vcenters.fqdn -eq $siteBvCenterDetails.fqdn}).name)) are not configured with a VMkernel port for vSphere Replication traffic: SKIPPING"
                                } else {
                                    For ($i=0; $i -lt $vmHostsToConfigure.Count; $i++) {
                                        Try {
                                            $esxcli = Get-EsxCli -Server $SiteBvCenterDetails.fqdn -VMHost $vmHostsToConfigure[$i].fqdn -V2 -ErrorAction Stop
                                            $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                            $existingRouteToRemove = $null
                                            Foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                if (($existingStaticRoute.gateway -eq $siteBGateway) -and ($existingStaticRoute.network -eq $siteANetwork) -and ($existingStaticRoute.netmask -eq $siteANetmask)) {
                                                    $existingRouteToRemove = $true
                                                }
                                            }
                                            if ($existingRouteToRemove) {
                                                Try {
                                                    $removeStaticRouteArgs = $null
                                                    $removeStaticRouteArgs = $esxcli.network.ip.route.ipv4.remove.CreateArgs()
                                                    $removeStaticRouteArgs.gateway = $siteBGateway
                                                    $removeStaticRouteArgs.network = $siteASubnet
                                                    $esxcli.network.ip.route.ipv4.remove.Invoke($removeStaticRouteArgs) | Out-Null
                                                } Catch {
                                                    $PSCmdlet.ThrowTerminatingError($PSItem)
                                                }
                                                $existingStaticRoutes = $esxcli.network.ip.route.ipv4.list.Invoke()
                                                $staticRouteStillExists = $null
                                                Foreach ($existingStaticRoute in $existingStaticRoutes) {
                                                    if (($existingStaticRoute.gateway -eq $siteBGateway) -and ($existingStaticRoute.network -eq $siteANetwork) -and ($existingStaticRoute.netmask -eq $siteANetmask)) {
                                                        $staticRouteStillExists = $true
                                                    }
                                                }
                                                if ($staticRouteStillExists) {
                                                    $PSCmdlet.ThrowTerminatingError(
                                                        [System.Management.Automation.ErrorRecord]::new(
                                                            ([System.Management.Automation.GetValueException]"Unable to validate static route for vSphere Replication has been removed from ESXi host ($($vmHostsToConfigure[$i])): POST_VALIDATION_FAILED"),
                                                            'Undo-vSREsxiStaticRoute',
                                                            [System.Management.Automation.ErrorCategory]::InvalidResult,
                                                            ""
                                                        )
                                                    )
                                                } else {
                                                    Write-Output "Remove static route vSphere Replication traffic from ESXi host ($($vmHostsToConfigure[$i].fqdn)): SUCCESSFUL"
                                                }
                                            } else {
                                                Write-Warning "Static route for vSphere Replication traffic does not exist on ESXi host ($($vmHostsToConfigure[$i].fqdn)): SKIPPING"
                                            }
                                        } Catch {
                                            $PSCmdlet.ThrowTerminatingError($PSItem)
                                        } 
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } Catch {
        Debug-ExceptionWriter -object $_
    }
}
Export-ModuleMember -Function Undo-vSREsxiStaticRoute

#EndRegion E N D O F F U N C T I O N S ###########
#######################################################################################################################