Public/Get-ADSIDomain.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Function Get-ADSIDomain
{
<#
    .SYNOPSIS
        Function to retrieve the current or specified domain
     
    .DESCRIPTION
        Function to retrieve the current or specified domain
     
    .PARAMETER Credential
        Specifies alternative credential to use
     
    .PARAMETER ForestName
        Specifies the DomainName to query
     
    .EXAMPLE
        Get-ADSIForest
    .EXAMPLE
        Get-ADSIForest -DomainName lazywinadmin.com
    .EXAMPLE
        Get-ADSIForest -Credential (Get-Credential superAdmin) -Verbose
    .EXAMPLE
        Get-ADSIForest -DomainName lazywinadmin.com -Credential (Get-Credential superAdmin) -Verbose
     
    .NOTES
        Francois-Xavier Cat
        LazyWinAdmin.com
        @lazywinadm
     
    .OUTPUTS
        System.DirectoryServices.ActiveDirectory.Domain
#>

    [cmdletbinding()]
    PARAM (
        [Alias("RunAs")]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = [System.Management.Automation.PSCredential]::Empty,
        
        $DomainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    )
    PROCESS
    {
        TRY
        {
            IF ($PSBoundParameters['Credential'] -or $PSBoundParameters['DomainName'])
            {
                Write-Verbose '[PROCESS] Credential or DomainName specified'
                $Splatting = @{ }
                IF ($PSBoundParameters['Credential']) { $Splatting.Credential = $Credential }
                IF ($PSBoundParameters['DomainName']) { $Splatting.DomainName = $DomainName }
                
                $DomainContext = New-ADSIDirectoryContext @splatting -contextType Domain
                [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
            }
            ELSE
            {
                [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
            }
            
        }
        CATCH
        {
            Write-Warning -Message '[PROCESS] Something wrong happened!'
            Write-Warning -Message $error[0].Exception.Message
        }
    }
}