Public/Get-ADComputerSite.ps1

Function Get-ADComputerSite() {
    <#
        .SYNOPSIS
        This function will attempt to discover the Active Directory site for the computer calling the function
 
        .DESCRIPTION
        This function uses the .net class System.DirectoryServices.ActiveDirectory.ActiveDirectorySite to request the AD site. The returned data is then validated before being returned.
 
        .INPUTS
        No inputs are required
 
        .OUTPUTS
        This function will return a string containing the AD site name for the requesting machine or will throw an error if this cannot be discovered.
 
        .EXAMPLE
        ps_Module_ActiveDirectoryTools
 
        $sDomainController = Get-ADComputerSite
 
        .NOTES
        MVogwell - October 2022 - Version 1.0
 
        Version history:
            1.0 - Initial tested release
    #>


    [CmdletBinding()]
    param ()

    # This function attempts to discover the AD site of the local computer. It will throw an error if the AD site could not be found

    $ErrorActionPreference = "Stop"
    $sRtnSite = ""

    try {
        Write-Verbose "*** Attempting to discover computer site"

        # Request the information using System.DirectoryServices.ActiveDirectory
        $sRtnSite = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Name

        Write-Verbose "`t+++ SUCCESS :: Site - $sRtnSite"
    }
    catch { # on error throw another error with more information
        $sErrMsg = ("Failed to discover computer site. Error: " + (($Global:Error[0].exception).toString()).replace("`r"," ").replace("`n"," "))

        Write-Verbose "`t--- FAILED :: $sErrMsg"

        throw $sErrMsg
    }

    # Check that a site value was discovered
    if ([string]::IsNullOrEmpty($sRtnSite) -eq $true) {
        throw "No site has been discovered. No error was returned"
    }

    return $sRtnSite
}