PowerShell Active Directory People Picker

This post contains a PowerShell Active Directory people picker, which is useful when we develop PowerShell forms that require searching for Active Directory users via their display name or username.

It’s a very similar concept to our PowerShell Active Directory Group Picker.  You can probably speed the search up by specifying an ADSI SearchRoot, this way it will only search a specific organisation unit in Active Directory as opposed to everywhere!  But for this example we’ll search everywhere.

We’ve also limited the results to 30 to speed up the search too.

cls
Add-Type -AssemblyName PresentationCore,PresentationFramework


function Select-ADObject
{  
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "Active Directory Search"
    $form.Size = New-Object System.Drawing.Size(340,320)
    $form.StartPosition = "CenterScreen"
        
    $SearchButton = New-Object System.Windows.Forms.Button
    $SearchButton.Location = New-Object System.Drawing.Point(260,10)
    $SearchButton.Size = New-Object System.Drawing.Size(50,23)
    $SearchButton.Cursor = [System.Windows.Forms.Cursors]::Hand
    $SearchButton.Text = 'Search'
    $SearchButton.Add_Click({

        $SearchButton.Enabled = $false
        $CancelButton.Enabled = $false

        #start progress bar
        $ProgressBar.Style="Marquee"
        $ProgressBar.MarqueeAnimationSpeed = 10;
      
        $searchVal = $SearchText.Text

        $job = Start-Job -ArgumentList $searchVal -ScriptBlock  {
            param($searchVal)                      
            if ($searchVal -ne $null -and $searchVal -ne "") {
                $objSearcher=[adsisearcher]"(&(objectCategory=person)(|(name=*$searchVal*)(samaccountname=*$searchVal*)))"
                $objSearcher.SizeLimit = 30

                $colProplist = "name"
                foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
                $colResults = $objSearcher.FindAll()
            }
            return $colResults
        }
    
        while($job.State -eq 'Running') {
            [System.Windows.Forms.Application]::DoEvents()
        }
        $results = $job | Receive-Job -AutoRemoveJob -Wait
              
        $ListBox.Items.Clear()                

        if ($results -eq $null -or $results.Count -eq 0) {
            $SearchButton.Enabled = $true
            $CancelButton.Enabled = $true
            #needed to reset marquee to 0
            $ProgressBar.Style="Blocks"
            $ProgressBar.MarqueeAnimationSpeed = 0;
            $ProgressBar.Value = 0;
            $SelectButton.Enabled = $false
            [System.Windows.MessageBox]::Show("Search returned no results.")
            return
        }

        
        foreach ($objResult in $results)
        {          
            [void] $ListBox.Items.Add(($objResult.Properties).name[0])	
        }

        $SearchButton.Enabled = $true
        $CancelButton.Enabled = $true
        #needed to reset marquee to 0
        $ProgressBar.Style="Blocks"
        $ProgressBar.MarqueeAnimationSpeed = 0;
        $ProgressBar.Value = 0;
        return
    })

    $form.Controls.Add($SearchButton)

    $SearchText = New-Object System.Windows.Forms.TextBox
    $SearchText.Location = New-Object System.Drawing.Point(10,11)
    $SearchText.Size = New-Object System.Drawing.Size(245,20)
    $SearchText.Multiline = $false   
    $SearchText.AcceptsReturn = $true 
    $SearchText.Add_KeyUp({
        if ($_.KeyCode -eq [System.Windows.Forms.Keys]::Enter) {
            $SearchButton.PerformClick()
        }
    })

    $form.Controls.Add($SearchText)

    $SelectButton = New-Object System.Windows.Forms.Button
    $SelectButton.Location = New-Object System.Drawing.Point(205,245)
    $SelectButton.Size = New-Object System.Drawing.Size(50,23)
    $SelectButton.Text = "Select"
    $SelectButton.Cursor = [System.Windows.Forms.Cursors]::Hand
    $SelectButton.Add_Click({ 
        if ($ListBox.SelectedItems.Count -eq 0) {
            [System.Windows.MessageBox]::Show("No item selected.")
            return
        }
        $script:selectedADGroup = $ListBox.SelectedItem; 
        write-host $ListBox.SelectedText; 
        $form.Close() 
    })
    $SelectButton.Enabled = $false
    $form.Controls.Add($SelectButton)

    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Point(260,245)
    $CancelButton.Size = New-Object System.Drawing.Size(50,23)
    $CancelButton.Text = "Cancel"
    $CancelButton.Cursor = [System.Windows.Forms.Cursors]::Hand
    $CancelButton.Add_Click({ $script:selectedADGroup = $null; $form.Close()})
    $form.Controls.Add($CancelButton)
      
    $ListBox = New-Object System.Windows.Forms.ListBox
    $ListBox.Location = New-Object System.Drawing.Point(10,40)
    $ListBox.Size = New-Object System.Drawing.Size(300, 20)
    $ListBox.Height = 200
    $ListBox.Add_SelectedIndexChanged({
        if ($ListBox.SelectedItems.Count -eq 1) {
            $SelectButton.Enabled = $true
        }
    })
    $form.Controls.Add($ListBox)

 
    $ProgressBar = New-Object System.Windows.Forms.ProgressBar
    $ProgressBar.Location = New-Object System.Drawing.Point(10, 246)
    $ProgressBar.Size = New-Object System.Drawing.Size(190, 21)
    $ProgressBar.Value = 0
    $ProgressBar.Style="Marquee"
    $ProgressBar.MarqueeAnimationSpeed = 0;
    $form.Controls.Add($ProgressBar)

    $form.TopMost = $true
    $form.Add_Shown({$form.Activate(); $SearchText.focus()})
    [void] $form.ShowDialog()

    return $script:selectedADGroup
}

$selectedObject = Select-ADObject

write-host $selectedObject

PowerShell Active Directory Group Picker

This post provides an example of a PowerShell Active Directory Group Picker.  You can also find a similar example of our PowerShell Active Directory People Picker.

When using one of my PowerShell GUI tools, we needed to select a valid Active Directory group.  I use the word ‘valid’ because merely prompting the user to enter free text created too much margin for error, so I needed to return a group that definitely existed.

There are ways to do this via PowerShell using the Remote Server Administration Tools (RSAT), but I don’t like my scripts relying on external tools and I like them to remain portable, whilst keeping the host machine clean.

Ultimately I ended up interfacing with Active Directory using PowerShell and ADSI.  The script basically invokes a function that launches a Windows Form.  It has a textbox to search for a group, and a ListBox to display them.  It then sets a variable in the script’s context with the selected group, which is accessible from the initial call.

cls
Add-Type -AssemblyName PresentationCore,PresentationFramework


function Select-ADObject
{  
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "Active Directory Search"
    $form.Size = New-Object System.Drawing.Size(340,320)
    $form.StartPosition = "CenterScreen"
        
    $SearchButton = New-Object System.Windows.Forms.Button
    $SearchButton.Location = New-Object System.Drawing.Point(260,10)
    $SearchButton.Size = New-Object System.Drawing.Size(50,23)
    $SearchButton.Cursor = [System.Windows.Forms.Cursors]::Hand
    $SearchButton.Text = 'Search'
    $SearchButton.Add_Click({

        $SearchButton.Enabled = $false
        $CancelButton.Enabled = $false

        #start progress bar
        $ProgressBar.Style="Marquee"
        $ProgressBar.MarqueeAnimationSpeed = 10;
      
        $searchVal = $SearchText.Text

        $job = Start-Job -ArgumentList $searchVal -ScriptBlock  {
            param($searchVal)                      
            if ($searchVal -ne $null -and $searchVal -ne "") {
                $objSearcher=[adsisearcher]"(&(objectCategory=group)(name=*$searchVal*))"
                $objSearcher.SizeLimit = 30

                $colProplist = "name"
                foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
                $colResults = $objSearcher.FindAll()
            }
            return $colResults
        }
    
        while($job.State -eq 'Running') {
            [System.Windows.Forms.Application]::DoEvents()
        }
        $results = $job | Receive-Job -AutoRemoveJob -Wait
              
        $ListBox.Items.Clear()                

        if ($results -eq $null -or $results.Count -eq 0) {
            $SearchButton.Enabled = $true
            $CancelButton.Enabled = $true
            #needed to reset marquee to 0
            $ProgressBar.Style="Blocks"
            $ProgressBar.MarqueeAnimationSpeed = 0;
            $ProgressBar.Value = 0;
            $SelectButton.Enabled = $false
            [System.Windows.MessageBox]::Show("Search returned no results.")
            return
        }

        
        foreach ($objResult in $results)
        {          
            [void] $ListBox.Items.Add(($objResult.Properties).name[0])	
        }

        $SearchButton.Enabled = $true
        $CancelButton.Enabled = $true
        #needed to reset marquee to 0
        $ProgressBar.Style="Blocks"
        $ProgressBar.MarqueeAnimationSpeed = 0;
        $ProgressBar.Value = 0;
        return
    })

    $form.Controls.Add($SearchButton)

    $SearchText = New-Object System.Windows.Forms.TextBox
    $SearchText.Location = New-Object System.Drawing.Point(10,11)
    $SearchText.Size = New-Object System.Drawing.Size(245,20)
    $SearchText.Multiline = $false   
    $SearchText.AcceptsReturn = $true 
    $SearchText.Add_KeyUp({
        if ($_.KeyCode -eq [System.Windows.Forms.Keys]::Enter) {
            $SearchButton.PerformClick()
        }
    })

    $form.Controls.Add($SearchText)

    $SelectButton = New-Object System.Windows.Forms.Button
    $SelectButton.Location = New-Object System.Drawing.Point(205,245)
    $SelectButton.Size = New-Object System.Drawing.Size(50,23)
    $SelectButton.Text = "Select"
    $SelectButton.Cursor = [System.Windows.Forms.Cursors]::Hand
    $SelectButton.Add_Click({ 
        if ($ListBox.SelectedItems.Count -eq 0) {
            [System.Windows.MessageBox]::Show("No item selected.")
            return
        }
        $script:selectedADGroup = $ListBox.SelectedItem; 
        write-host $ListBox.SelectedText; 
        $form.Close() 
    })
    $SelectButton.Enabled = $false
    $form.Controls.Add($SelectButton)

    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Point(260,245)
    $CancelButton.Size = New-Object System.Drawing.Size(50,23)
    $CancelButton.Text = "Cancel"
    $CancelButton.Cursor = [System.Windows.Forms.Cursors]::Hand
    $CancelButton.Add_Click({ $script:selectedADGroup = $null; $form.Close()})
    $form.Controls.Add($CancelButton)
      
    $ListBox = New-Object System.Windows.Forms.ListBox
    $ListBox.Location = New-Object System.Drawing.Point(10,40)
    $ListBox.Size = New-Object System.Drawing.Size(300, 20)
    $ListBox.Height = 200
    $ListBox.Add_SelectedIndexChanged({
        if ($ListBox.SelectedItems.Count -eq 1) {
            $SelectButton.Enabled = $true
        }
    })
    $form.Controls.Add($ListBox)

 
    $ProgressBar = New-Object System.Windows.Forms.ProgressBar
    $ProgressBar.Location = New-Object System.Drawing.Point(10, 246)
    $ProgressBar.Size = New-Object System.Drawing.Size(190, 21)
    $ProgressBar.Value = 0
    $ProgressBar.Style="Marquee"
    $ProgressBar.MarqueeAnimationSpeed = 0;
    $form.Controls.Add($ProgressBar)

    $form.TopMost = $true
    $form.Add_Shown({$form.Activate(); $SearchText.focus()})
    [void] $form.ShowDialog()

    return $script:selectedADGroup
}

$selectedObject = Select-ADObject

write-host $selectedObject

List All User and Computer LDAP Attributes using PowerShell and ADSI

Other Posts in this Series:

There comes a time when we want to read or write an Active Directory attribute, yet we don’t know the name of the attribute we’re looking for!  This handy script will list all user and computer LDAP attributes using PowerShell and ADSI.

In order to do this we need an example user and computer to find the AD attributes for.  You will need to change those strings at the top of the script below.

$exampleUser = "exampleuser"
$exampleComputer = "examplecomputer"

$searcher=[adsisearcher]"(&(objectCategory=person)(objectClass=user)(SamAccountName=$exampleUser))"
$searcher.PageSize = 1
        
$user = $searcher.FindOne()
if ($user -ne $null) {
    write-host "********All user LDAP attributes********"
    $user.Properties.PropertyNames | Sort | foreach { new-object psobject -Property @{ AttributeName=$_;AttributeValue=$(($user.Properties).$_) }} | Format-Table AttributeName,AttributeValue
} else {
    write-host "Cannot find user"
}  

$searcher=[adsisearcher]"(&(objectClass=computer)(Name=$exampleComputer))"
$searcher.PageSize = 1
       
$computer = $searcher.FindOne()
if ($computer -ne $null) {
    write-host "********All comptuer LDAP attributes********"
    $computer.Properties.PropertyNames | Sort | foreach { new-object psobject -Property @{ AttributeName=$_;AttributeValue=$(($computer.Properties).$_) }} | Format-Table AttributeName,AttributeValue
} else {
    write-host "Cannot find computer"
} 

Once you’ve found what you’re looking for, you may want to look at other posts in this series such as how to use ADSI to set and clear Active Directory attributes.

Use PowerShell ADSI to Search Users in Active Directory

Other Posts in this Series:

This post provides a simple example of how we can use PowerShell ADSI to search users in Active Directory.  You may wish to further optimise this by using LDAP filters.

$searcher=[adsisearcher]'(&(objectCategory=person)(objectClass=user))'
$searcher.PageSize = 200

$colProplist = "samaccountname"
foreach ($i in $colPropList) { $searcher.PropertiesToLoad.Add($i) | out-null } 
        
$Users = $searcher.findall()
foreach ($user in $Users) {
       write-host ($user.Properties).samaccountname
}      

Use PowerShell and ADSI to Add, Update, Clear and Append Active Directory Attributes

Other Posts in this Series:

This post provides an example of how we can use PowerShell and ADSI to add, update, clear and append Active Directory attributes.

Use Put() to Set an Active Directory Attribute using PowerShell

In its simplest form, we can use the Put() method to simply set an Active Directory attribute (in this case on a user record) using PowerShell like so:

$objSearcher=[adsisearcher]'(&(objectCategory=person)(objectClass=user)(sAMAccountName=alkaneuser))'
	
$colProplist = "department"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
$colResults = $objSearcher.FindOne()	
 
if ($colResults -ne $null)
{   	  
    $user = [adsi]($colResults.Properties).adspath[0]

    #set attribute
    $user.Put("department", "Example department2"); 
    $user.setinfo();    	
}

Use PutEx() to Update and Append to an Active Directory Attribute using PowerShell

We can also use the Put() method to update an Active Directory attribute in similar fashion.  But using PutEx() gives us more flexibility, since we can use it to update, append (for multi-string attribute types), delete and completely clear Active Directory attributes.

$ADS_PROPERTY_CLEAR = 1
$ADS_PROPERTY_UPDATE = 2
$ADS_PROPERTY_APPEND = 3
$ADS_PROPERTY_DELETE = 4

$objSearcher=[adsisearcher]'(&(objectCategory=person)(objectClass=user)(sAMAccountName=alkaneuser))'
	
$colProplist = "department"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
$colResults = $objSearcher.FindOne()	
 
if ($colResults -ne $null)
{   	  
  
    $user = [adsi]($colResults.Properties).adspath[0]

    #set attribute
    $user.Put("department", "Example1"); 
    $user.setinfo();   

    #update attribute - uncomment as required
    $user.PutEx($ADS_PROPERTY_UPDATE, "department", @("Example2")); 
    $user.setinfo();     
  
    #update attribute - uncomment as required
    $user.PutEx($ADS_PROPERTY_DELETE, "department", @("Example2")); 
    $user.setinfo();             
   
    #append attribute - uncomment as required
    $user.PutEx($ADS_PROPERTY_APPEND, "department", @("Example3")); 
    $user.setinfo(); 
    	
}

Note in the above example that we are updating the department attribute, which is a single string attribute. Hence if we try and append to it when it is already set, we will see an error (we can’t append to singular strings, only multi-string arrays).  So in the example above we delete the attribute first to prevent this from happening.  Otherwise we can simply update the attribute instead.

Contrast this with the otherhomephone attribute, which is a multi-string attribute (essentially an array of strings) that we can append to:

$ADS_PROPERTY_CLEAR = 1
$ADS_PROPERTY_UPDATE = 2
$ADS_PROPERTY_APPEND = 3
$ADS_PROPERTY_DELETE = 4

$objSearcher=[adsisearcher]'(&(objectCategory=person)(objectClass=user)(sAMAccountName=alkaneuser))'
	
$colProplist = "otherhomephone"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
$colResults = $objSearcher.FindOne()	
 
if ($colResults -ne $null)
{   	  
  
    $user = [adsi]($colResults.Properties).adspath[0]

    #set attribute
    $user.Put("otherhomephone", "Example1"); 
    $user.setinfo();   

    #update attribute - uncomment as required
    $user.PutEx($ADS_PROPERTY_UPDATE, "otherhomephone", @("Example2")); 
    $user.setinfo();    
   
    #append attribute - uncomment as required
    $user.PutEx($ADS_PROPERTY_APPEND, "otherhomephone", @("Example3")); 
    $user.setinfo(); 	
}

Use PutEx() to Clear an Active Directory Attribute using PowerShell

Finally we can clear an Active Directory attribute like so:

$ADS_PROPERTY_CLEAR = 1
$ADS_PROPERTY_UPDATE = 2
$ADS_PROPERTY_APPEND = 3
$ADS_PROPERTY_DELETE = 4

$objSearcher=[adsisearcher]'(&(objectCategory=person)(objectClass=user)(sAMAccountName=alkaneuser))'
	
$colProplist = "department"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
$colResults = $objSearcher.FindOne()	
 
if ($colResults -ne $null)
{   	  
    $user = [adsi]($colResults.Properties).adspath[0]
   
    #clear attribute - uncomment as required
    $user.PutEx($ADS_PROPERTY_CLEAR, "department", $null); 
    $user.setinfo();   	
}

Use ADSI and FromFileTime to Convert Datetime Attributes in Active Directory

Other Posts in this Series:

This post explains how we can use ADSI and FromFileTime to convert datetime attributes in Active Directory to a human-readable date and time.

You’ll notice when you return attributes such as lastlogon, lastlogontimestamp and lastpwdset that the format of the results is something like: 132586443741396519

What the heck does that mean??  Well it’s known as the ‘Windows NT time format’ and represents the Universal Time Coordinated (UTC) of the number of 100-nanosecond intervals that have elapsed since the 0 hour on January 1, 1601.

In this post we search for all enabled users in AD and print out their lastlogontimestamp value, in the format dd/MM/yyyy.

$objSearcher=[adsisearcher]'(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))'
$objSearcher.PageSize = 200
	
$colProplist = "samaccountname","lastlogontimestamp"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
$colResults = $objSearcher.FindAll()
	
$count = 0

foreach ($objResult in $colResults)
{
   $username = ($objResult.Properties).samaccountname     
   $tdt = [int64]($objResult.Properties).lastlogontimestamp[0].ToString()
   $dt = [datetime]::FromFileTime($tdt).ToString('dd/MM/yyyy')
   write-host $dt
}

 

 

Use ADSI to List Nested Members of an AD Group (Updated)

Other Posts in this Series:

This post includes an example of how we can use ADSI to list nested members of an AD group.  In other words, if the group contains nested groups, it will iteratively search all the members of those nested groups too.

I’ve filtered this first example to only find enabled objects for those organisations that don’t do good housekeeping!

function Find-Enabled-Members
{
    Param
    (
       [string]$DN
    )

    if (!([adsi]::Exists("LDAP://$DN"))) {
        write-host "$DN does not exist"
        return     
    }
        
    $foundCount = 0
    $group = [adsi]("LDAP://$DN")

    ($group).member | ForEach-Object {

        $groupObject = [adsisearcher]"(&(distinguishedname=$($_)))"  
        $groupObjectProps = $groupObject.FindOne().Properties
             
        if ($groupObjectProps.objectcategory -like "CN=group*") { 
            #search nested group
            $foundCount += Find-Enabled-Members "$_"            
        } else {
            $objenabled = ($groupObjectProps.useraccountcontrol[0] -band 2) -ne 2

            if ($objenabled) {
                write-host "Found $($groupObjectProps.samaccountname) in $($group.Name)"
                $foundCount += 1
            }              
        }
    }
    return $foundCount
}

#group to search for
$groupName = "Alkane_AD_Group"

$objSearcher=[adsisearcher]"(&(objectCategory=group)(name=$groupName))"
$objSearcher.PageSize = 200

#specify properties to include
$colProplist = "name","distinguishedname"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
$group = $objSearcher.FindOne()

if ($group -ne $null)
{
    #if group found

    $name = ($group.Properties).name
    $distinguishedName = ($group.Properties).distinguishedname
    
    write-host "Found group $name.  Searching members..."
    
    #find members
    $members = Find-Enabled-Members $distinguishedName
    write-host "Total enabled members including nested members is $members"
}

Since it’s checking if each member is enabled or not, it does take slightly longer to run.  If you just wanted to check the member count whether it’s disabled or enabled, you can use the following example:

function Find-Members
{
    Param
    (
       [string]$DN
    )

    if (!([adsi]::Exists("LDAP://$DN"))) {
        write-host "$DN does not exist"
        return     
    }
        
    $group = [adsi]("LDAP://$DN")

    $foundCount = $group.Member.Count

    ($group).member | ForEach-Object {

        $groupObject = [adsisearcher]"(&(distinguishedname=$($_)))"  
        $groupObj = $groupObject.FindOne()

        if ($groupObj -ne $null) {

            $groupObjectProps = $groupObj.Properties
             
            if ($groupObjectProps.objectcategory -like "CN=group*") { 

                #get path of the object from search result
                $pathToObject = ($groupObjectProps).adspath[0]

                #convert/cast search result object path to an ADSI object
                $obj = [adsi]($pathToObject)
                
                #subtract one to deduct group object (we only want to count the members)
                $foundCount = $foundCount - 1
               
                $foundCount += Find-Members "$_"         
            }
        }
    }
    return $foundCount
}

#group to search for
$groupName = "Alkane_AD_Group"

$objSearcher=[adsisearcher]"(&(objectCategory=group)(name=$groupName))"
$objSearcher.PageSize = 200

#specify properties to include
$colProplist = "name","distinguishedname"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
	
$group = $objSearcher.FindOne()

if ($group -ne $null)
{
    #if group found

    $name = ($group.Properties).name
    $distinguishedName = ($group.Properties).distinguishedname
    
    $members = Find-Members $distinguishedName
    write-host "Total members including nested members is $members"
}

Use PowerShell ADSI to Modify an AD Group

Other Posts in this Series:

This post provides a simple example of how we can use PowerShell ADSI to modify an AD group.  In this example, we modify the description attribute of an AD group.  You can also use ADSI to clear the attributes for an AD group.

#OU containing the AD group
$adGroupOU="OU=Application,OU=Groups,DC=alkanesolutions,DC=co,DC=uk"

#AD group name
$addADGroup = "CN=alkane_ad_group"

#Full distinguished name of AD group		
$distinguishedName = "$addADGroup,$adGroupOU"

#check if exists
$group = ([ADSISearcher] "(distinguishedName=$distinguishedName)").FindOne()

if ($group -ne $null)
{		
    #modify AD group description
    $adGroupObj = [ADSI]("LDAP://$($group.Properties.distinguishedname)")
    $adGroupObj.put('description',"Alkane description") 
    $adGroupObj.SetInfo()
}

Use PowerShell ADSI to Create an AD Group

Other Posts in this Series:

This post provides a simple example of how we can use PowerShell ADSI to create an AD group.

$adGroupType = @{
    Global      = 0x00000002
    DomainLocal = 0x00000004
    Universal   = 0x00000008
    Security    = 0x80000000
}

#OU containing the AD group
$adGroupOU="OU=Application,OU=Groups,DC=alkanesolutions,DC=co,DC=uk"

#AD group name
$addADGroupName = "alkane_group"

#Full distinguished name of AD group		
$distinguishedName = "CN=$addADGroupName,$adGroupOU"

#check if exists
$group = ([ADSISearcher] "(distinguishedName=$distinguishedName)").FindOne()

if ($group -eq $null)
{	
    #group doesn't exist

    #get OU
    $adsiADGroup = [adsi]("LDAP://$adGroupOU")

    #create group in OU
    $newGroup = $adsiADGroup.Create('group', "CN=$addADGroupName")

    #Make it a global security group
    $newGroup.put('grouptype',($adGroupType.Global -bor $adGroupType.Security))
    $newGroup.put('samaccountname',$addADGroupName)
    $newGroup.SetInfo()	
   
}

Use PowerShell ADSI to Delete an AD Group

Other Posts in this Series:

This post provides a simple example of how we can use PowerShell ADSI to delete an AD group.

#OU containing the AD group
$adGroupOU="OU=Application,OU=Groups,DC=alkanesolutions,DC=co,DC=uk"

#AD group name
$addADGroup = "CN=alkane_ad_group"

#Full distinguished name of AD group		
$distinguishedName = "$addADGroup,$adGroupOU"

#check if exists
$group = ([ADSISearcher] "(distinguishedName=$distinguishedName)").FindOne()

if ($group -ne $null)
{		
    #delete AD group
    $adGroupObj = [ADSI]"LDAP://$adGroupOU"
    $adGroupObj.Delete("Group",$addADGroup)
}