Common/Get-DomainName.ps1

#region Main Functions
<#
    .SYNOPSIS
        Enforces the behavior of getting the domain name.
        If a domain name is provided, it will be used.
        If a domain name is not provided, the domain name of the generating system will be used.
 
    .PARAMETER Name
        The FQDN on the domain PowerStig will be running against
 
    .PARAMETER Format
        Determines the format in which to convert the FQDN provided into and return back
 
    .RETURN
        string
 
    .EXAMPLE
        Get-DomainName -Name "contoso.com" -Format FQDN
        Get-DomainName -Name "contoso.com" -Format NetbiosName
        Get-DomainName -Name "contoso.com" -Format DistinguishedName
#>

Function Get-DomainName
{
    [outputtype([string])]
    param
    (
        [Parameter()]
        [string]
        $Name,

        [Parameter()]
        [ValidateSet('FQDN','NetbiosName','DistinguishedName')]
        [string]
        $Format
    )

    $domain = [string]::Empty

    if ( [string]::IsNullOrEmpty( $Name ) )
    {
        $domain = $env:USERDNSDOMAIN
    }
    else
    {
        $domain = $Name
    }

    switch ($Format) 
    {
        'FQDN'
        {
            return $domain
        }
        'NetbiosName'
        {
            return Get-NetbiosName $domain
        }
        'DistinguishedName'
        {
            return Get-DistinguishedName $domain
        }
        Default 
        {
            return $domain
        }
    }

    return $domain
}


#endregion Main Functions
#region Support Functions
Function Get-NetbiosName
{
    [outputtype([string])]
    param
    (
        [string]
        $FQDN
    )

    $parts = Get-DomainParts $FQDN
    return $parts[0]
}

Function Get-DistinguishedName
{
    [outputtype([string])]
    param
    (
        [string]
        $FQDN
    )

    $parts = Get-DomainParts $FQDN
    return Format-DistinguishedName $parts
}

Function Format-DistinguishedName
{
    [outputtype([string])]
    param
    (
        [string[]]
        $Parts
    )

    $distinguishedName = ""
    $lastIndex = $Parts.Count - 1

    foreach ($part in $Parts)
    {
        if ($part -eq $Parts[$lastIndex])
        {
            $distinguishedName += 'DC=' + $part.ToString()
        }
        else
        {
            $distinguishedName += 'DC=' + $part.ToString() + ','
        }
    }

    return $distinguishedName.ToString()
}

Function Get-DomainParts
{
    [outputtype([string[]])]
    param
    (
        [string]
        $FQDN
    )

    return $FQDN.Split('{.}')
}
#endregion Support Functions