PS > Add-DirectAccessClient

DirectAccess deployments on Windows Server 2012++ requires clients to be members of a predefined security group. I wanted to automate adding computers to this group. Run this script as a scheduled task every x minutes, and let the problem solve itself!

function Add-DirectAccessClient
{
    [CmdletBinding()]
    Param
    (
        $DirectAccessGroup   = (Get-ADGroup -Identity "DirectAccess"), #Gets the DistinguishedName of your DirectAccess security group.
        $DirectAccessMembers = ($DirectAccessGroup | Get-ADGroupMember | select -ExpandProperty name), #Stores a list of all computer names currently added to your DirectAccess security group
        $SearchBaseOU        = (Get-ADComputer -Properties MemberOf -SearchBase "OU=Laptops,OU=Computers,OU=Division,DC=Company,DC=com") #Point this towards your Computer OU
    )

    Begin
    {
        try
        {
            $null = Get-Module ActiveDirectory -ErrorAction Stop
        }
        catch
        {
            Write-Error -Message "Module ActiveDirectory was not found. Install RSAT, or run the script on a DC/Remote PS Session"
        }
    }

    Process
    {
        foreach ($Computer in $SearchBaseOU)
        {
            if($Computer.Name -notin $DirectAccessMembers)
            {
                try
                {
                    Add-ADGroupMember -Identity $DirectAccessGroup -Members $Computer.DistinguishedName -ErrorAction Stop
                    Write-Output "Added: $($Computer.Name)"
                }
                catch
                {
                    Write-Error -Message "Unable to add computer to group. Missing permissions?"
                }
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s