Get-ADComputerSiteName.ps1

<#PSScriptInfo
 
.VERSION
    1.0
.GUID
    aa16f836-627c-4369-82f5-2a52e71cb80d
.AUTHOR
    Thomas J. Malkewitz @dotps1
 
#>


<#
 
.SYNOPSIS
    Gets the ADSiteName for a computer.
.DESCRIPTION
    Queries DNS to get the computers IPAddress then, returns the ADSiteName base on AD Sites and Services.'
.INPUTS
    System.String.
.OUTPUTS
    System.Management.Automation.PSCustomObject.
.PARAMETER Name
    The name of the system to get the ADSiteName for.
.EXAMPLE
    PS C:\> Get-ADComputerSiteName
     
    PSComputerName ADSiteName
    -------------- ----------
    MyComputer Default-First-Site
.EXAMPLE
    PS C:\> Get-ADComputer -Filter { Name -like '*Computer*' } | Get-ADComputerSiteName
 
    PSComputerName ADSiteName
    -------------- ----------
    MyComputer Default-First-Site
.NOTES
    Domain Connectivity is required.
.LINK
    http://www.powershellmagazine.com/2013/04/23/pstip-get-the-ad-site-name-of-a-computer/
.LINK
    http://dotps1.github.io
 
#>


[OutputType(
    [PSCustomObject]
)]

Param (
    [Parameter(
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true
    )]
    [Alias(
        'ComputerName'
    )]
    [String[]]
    $Name = $env:COMPUTERNAME
)

Process {
    foreach ($item in $Name) {
        try {
            $adSiteName = nltest /server:${item} /dsgetsite 2>$null

            if ($LASTEXITCODE -eq 0) {
                [PSCustomObject] @{
                    PSComputerName = $item
                    ADSiteName = $adSiteName[0]
                }
            } else {
                Write-Warning -Message "No ADSiteName found for: '$item'."

                continue
            }
        } catch {
            Write-Error -Message $_.ToString()
        }
    }
}