Public/New-ADSIDirectoryEntry.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
69
70
71
72
73
74
75
76
77
78
79
80
81
function New-ADSIDirectoryEntry
{
<#
.SYNOPSIS
    Function to create a DirectoryEntry instance
 
.DESCRIPTION
 Function to create a DirectoryEntry instance
  
 This function is typically a helper function used by some of the other functions
 in the module ADSIPS
  
.PARAMETER Path
    The path of this DirectoryEntry.
    Default is $(([adsisearcher]"").Searchroot.path)
 
    https://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.path.aspx
 
.PARAMETER Credential
 Specifies alternative credential to use
  
.PARAMETER AuthenticationType
 Specifies the optional AuthenticationType secure flag(s) to use
  
 The Secure flag can be used in combination with other flags such as ReadonlyServer, FastBind.
  
 See the full detailed list here:
 https://msdn.microsoft.com/en-us/library/system.directoryservices.authenticationtypes(v=vs.110).aspx
  
.EXAMPLE
 New-ADSIDirectoryEntry
  
 Create a new DirectoryEntry object for the current domain
  
.EXAMPLE
 New-ADSIDirectoryEntry -Path "LDAP://DC=FX,DC=lab"
  
 Create a new DirectoryEntry object for the domain FX.Lab
 
.EXAMPLE
 New-ADSIDirectoryEntry -Path "LDAP://DC=FX,DC=lab" -Credential (Get-Credential)
  
 Create a new DirectoryEntry object for the domain FX.Lab with the specified credential
  
.LINK
    https://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.aspx
 
.LINK
    http://www.lazywinadmin.com/2013/10/powershell-using-adsi-with-alternate.html
  
.NOTES
    Francois-Xavier Cat
 www.lazywinadmin.com
 @lazywinadm
 github.com/lazywinadmin
#>

    [CmdletBinding()]
    PARAM (
        $Path = $(([adsisearcher]"").Searchroot.path),

        [Alias("RunAs")]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = [System.Management.Automation.PSCredential]::Empty,
        
        [System.DirectoryServices.AuthenticationTypes[]]$AuthenticationType
    )
    #Building Argument
    IF ($PSBoundParameters['Credential'])
    {
        $ArgumentList = $Path, $($Credential.UserName), $($Credential.GetNetworkCredential().password)
    }
    
    IF ($PSBoundParameters['AuthenticationType'])
    {
        $ArgumentList += $AuthenticationType
    }
    
    # Create object
    New-Object -TypeName DirectoryServices.DirectoryEntry -ArgumentList $ArgumentList
}