Home » Posts tagged 'active directory'

Tag Archives: active directory

Remove User From AzureAD Group Script

Just a quick post to share a simple PowerShell script that will allow administrators to remove a User from an AzureAD Group.

Script will prompt for the UPN of the user that you want to manage and produce a menu list of all their group memberships

Simply enter the number in the square brackets [] when prompted by the script

$user = Read-Host "Please enter the UPN of the user you want to remove"
$azureUser = Get-AzureADUser -ObjectId $user
$groupMembership = Get-AzureADUserMembership -ObjectId $azureUser.ObjectId
$x = 1
$groupArray = @()
ForEach($grp in $groupMembership){
Write-Host "[$($x)] - $($grp.DisplayName)"
$groupArray += New-Object -TypeName psobject -Property @{Id = $x; GroupId = $grp.ObjectId; GroupName = $grp.DisplayName}
$removeFromGroup = Read-Host "Please enter the ID of the Group you want to remove the user from"
$GroupId = $groupArray | where {$_.Id -eq $removeFromGroup}
Write-Host "Removing $($user) From Group $($GroupId.GroupName)" -ForegroundColor Yellow
$confirm = Read-Host "Are you sure you want to proceed (y/n)?"
if ($confirm -ieq "y"){
Remove-AzureADGroupMember -ObjectId $GroupId.GroupId -MemberId $azureUser.ObjectId
Write-Host "User $($user) has been removed from the group" -ForegroundColor Green
Write-Host "Process Cancelled, no changes have been made" -ForegroundColor Red

Managing SIP Identities in Skype for Business Online

As we prepare for the migration from on-premises Skype for Business to Skype for Business Online, there are a few important considerations to bear in mind before you take the leap. I will be covering these in a series of posts (hopefully), today I want to share with you a common scenario we will face while preparing for migration.

We are well aware of the pre-requisite for Office 365 that demands an Active Directory synchronised user must have a publically routable User Principal Name (UPN). So critical is this requirement that it is now engrained in every consultant’s mind and increasingly customers are becoming more aware of this without us even mentioning it. However, this can often produce its own unique challenges.


Forcing SYSVOL Replication using DFS-R

To force SYSVOL replication between domain controllers you can use DFSR (DFS Replication tools feature required)

dfsrdiag syncnow /RGName:”Domain System Volume” /Partner:<partner dc> /Time:15 /v

Add Security Groups from Trusted Domain to Trusting Domain Local Groups

I needed a quick way to add domain global groups from a trusting domain to domain local groups in the trusting domain with the same name for a project I was undertaking. The trusting domain was Windows 2003 and we did not have access to any AD Powershell module in the trusting domain so the only way to do this is using DSMOD. Here is the powershell script I made and ran from the trusted domain side to quickly add the trusted groups to the domain local groups of the trusting domain. It produces a batch file you run on the trusting domain DC so that it gives you a chance to review the commands being executed.

$bat = New-Item -Path C:\legacygroupadd.bat -ItemType File -Force
Import-Module ActiveDirectory
$newgroups = Get-ADGroup -searchbase "ou=groups,ou=rs,dc=ad,dc=domain,dc=com" -Filter *
Foreach ($g in $newgroups){ 
 $legacyquery = cmd.exe /c dsquery group -name $g.Name -d legacydomain.local -u legacyndomain\mvale -p MyP@ssw0rd
 if ($legacyquery){
 $write = "dsmod group $($legacyquery) -addmbr $($g.DistinguishedName) -d legacydomain.local -u legacydomain\mvale -p MyP@ssw0rd" 
 Add-Content -Path $bat -Value $write


Removing Foreign Security Principals from Groups

Today I had a requirement to migrate users and groups from a legacy domain to a new domain using ADMT. All legacy groups were domain local with members from other groups on other domains via existing trusts. Performing a migration of a Domain local groups using ADMT also migrates across members who have no user accounts in the new domain. These are called Foreign Security Principals.

I needed to convert these groups into Global groups in the new domain, but before I could do this I needed to remove these foreign security principals as members. I looked at Powershell and the Get-ADGroupMember Commandlet and this does not work with FSP’s as members producing an “Unspecified Error”. I looked at the old dsmod command and this could achieve what I was looking for. However DSMOD required the full LDAP canonical name of the group and member to remove. This is a real pain when you have to modify over 2000 values!

I looked at piping a dsquery command into a dsget and then into a dsmod command which would have worked, but there is no filter or where clause in these commands where I could remove the FSPs but leave migrated user accounts.

The solution I came up with took 5 minutes to build and 1 minute to execute. I realised I could use a mixture of powershell and DS commands to achieve what I wanted. The Powershell I would use for looping and writing out content and DS commands to do the work.

The PS script I came up with basically queries AD using DSQUERY collecting the results into a array variable. I then loop through the array and peform a DSGET command to grab the members of that group. Then there is an IF command that says if the member of the group is an FSP issue a DSMOD command to remove it. It also converts the group to Domain Global from Local. The other script is based on the same principal but produces a batch file to run separately. I chose this because I can double check the commands built.

Anyway here are both scripts, you will see the differences (albeit slight)

Script to Output to Batch File

$bat = New-Item -Path c:\groupmod.bat -ItemType File -Force
$group = cmd.exe /c dsquery group "ou=groups,ou=rs,dc=ad,dc=domain,dc=com"
foreach ($g in $group){ 
 $members = cmd.exe /c dsget group $g -members 
 Foreach ($m in $members){ 
 if ($m -like "*CN=ForeignSecurityPrincipals*"){ 
 $write = "dsmod group $($g) -rmmbr $($m)"
 Add-Content -Path $bat -Value $write
 Add-Content -Path $bat -Value "dsmod group $($g) -scope u"
 Add-Content -Path $bat -Value "dsmod group $($g) -scope g"

Script to execute on the fly

$group = cmd.exe /c dsquery group "ou=groups,ou=rs,dc=ad,dc=domain,dc=com"
foreach ($g in $group){ 
 $members = cmd.exe /c dsget group $g -members 
 Foreach ($m in $members){ 
 if ($m -like "*CN=ForeignSecurityPrincipals*"){ 
 cmd.exe /c dsmod group $($g) -rmmbr $($m)
cmd.exe /c dsmod group $($g) -scope u 
cmd.exe /c dsmod group $($g) -scope g



Copy users from on Active Directory to another (no trust/ADMT)

I had a scenario whereby a customer wanted to migrate from SBS2003 to Server 2012 and Exchange 2013 in one hop. There was not enough resources to install and exchange 2010 migration server to move mailboxes over EWS and due to SBS constraints we cannot use ADMT to migrate as Domain Trusts cannot be made between SBS and any other domain. The solution we opted for was to build a new domain with exchange 2013 installed and then migrate the users over using a mixture of export scripts from the SBS domain and PST files for their email.

As we were migrating to an independent domain we don’t really need to worry about SID History as we are not accessing resources in the old domain after migration. What we do need to worry about is the X500 address of the user. I have another blog post about the importance of this attribute when moving between exchange servers on different domains.

First I exported all the users from the old domain using CSVDE, because AD Powershell was not available on SBS2003

CSVDE -f c:\users.csv -d “OU=users,OU=SBS Company,DC=domain,DC=local” – r (objectClass=user)

This produced the required CSV with all the attributes we need and more!

I then copied this file to the new domain and created a powershell script to read through these users, enable their mailboxes (if required) and add them to or create and add them to security groups they were members of in the old domain. In order to achieve this the script reads the memberOf field of the user and splits the groups into an array. It then checks the groups exists in new domain. if it does it will add the user to the group. If it doesn’t it will create the group and add the user to it. There is a limitation in using this script in this way. It will not discriminate between distribution or security groups. What I mean is that when it creates a group it will be a security group regardless whether the group was a distribution group in the old domain. But this was OK for me to do it this way.

The script allows you to add the destination location of the users and groups OU as well as choosing whether to enable a mailbox or not. If you choose to enable a mailbox then you must supply the PowerShell URL of the exchange server e.g http://exchangeserver.domain.com/powershell

Log files are written to C:\ADMigration folder which will be created. During the user import, a random password will be generated for the user. These passwords are stored in a folder called userpasswords.txt located in C:\ADMigration folder.


Ensure Exchange is installed before running this script if you are migrating mailboxes, otherwise it will create the exchange groups and may cause issues

Turn off Password history and complexity requirements temporarily in the domain as I have had weird issues with this script when it is enabled


Here is the script, copy this into notepad or PS ISE and save with the ps1 extension



Random Password Function Powershell

To generate a random password for Active directory you can use this function

Function Get-RandomPassword(){
Param (
$alphabet=$NULL;For ($a=65;$a –le 90;$a++) {$alphabet+=,[char][byte]$a }
$ascii=$NULL;For ($a=33;$a –le 126;$a++) {$ascii+=,[char][byte]$a }
For ($l=1; $l -le $length; $l++){ 
 $tempPassword += ($alphabet | Get-Random)
 $tempPassword += ($ascii | Get-Random)
return $tempPassword


Even though the length is 5, it will actually produce a 10 character password because it will use UPPERCASE letters x 5 and ASCII characters x 5

Add Users Home Folder and Set Permissions Powershell

By now most admins are Ok creating new user accounts in Active Directory. However, one thing the New-ADUser commandlet does not do is create a home folder for the user. The preferred way by me is always let group policy handle this but on occasions companies still use active directory for home folders.

Here is the script to create a home folder on the home shared drive and set the correct permissions

 $NewFolder = New-Item -Path "\\serverfqdn\userhome" -Name <username> -ItemType "Directory"
 $Rights = [System.Security.AccessControl.FileSystemRights]"FullControl,Modify,ReadAndExecute,ListDirectory,Read,Write"
 $InheritanceFlag = @([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
 $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
 $objType =[System.Security.AccessControl.AccessControlType]::Allow
 $objUser = New-Object System.Security.Principal.NTAccount "<domain>\<username>"
 $objACE = New-Object System.Security.AccessControl.FileSystemAccessRule ($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
 $ACL = Get-Acl -Path $NewFolder
 Set-ACL -Path $NewFolder.FullName -AclObject $ACL

Recover Bitlocker Recovery Password Powershell

If you use Bitlocker with Active Directory Recovery, then you can quickly recover the recovery password from AD using Powershell. Yes there is an RSAT plugin that will do the same thing, but I have been on servers that do not have this and I needed the password quick.

$Bitlocker = Get-ADObject -Filter {name -like <first 8 characters of recovery key> -and ObjectClass -eq 'msFVE-RecoveryInformation'} -Properties msFVE-RecoveryPassword | Select-Object msFVE-RecoveryPassword | Out-String
$keyString = $Bitlocker
 $keyString = $keyString.replace('msFVE-RecoveryPassword', '')
 $keyString = $keyString.replace('--', '')
 $keyString = $keyString.replace('
 ', '')
Write-Host $keyString

Renaming a Domain Controller

Contrary to some people’s beliefs, it is actually possible to rename a domain controller! For this to work you must have at least 2 domain controllers already in your domain. This WILL NOT work if you have a single domain controller.

Before you start if the domain controller you are renaming holds any FSMO roles, you must migrate these to the other domain controller before you start.

  1. Open Command Prompt and type in netdom computername <current computer name> /add:<new computer name>
  2. then netdom computername <current computer name> /makeprimary:<new computer name>
  3. Restart domain controller
  4. Then open command prompt and type netdom computername <new computer name> /remove:<old computer name>
%d bloggers like this: