September 22, 2014

PowerShell - Creating Active Directory account in multiple forests

Here is example how to provision Active Directory account in multiple forests using powershell. I will use variables and import-session. Before you can do anything in trusting AD forest you have to grant apropriate permissions through the Set-PSSessionConfiguration cmdlet. It needs to be done beacuse by default you have to be a member of local administrators group to run remote powershell.

Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI 
To check use: Get-PSSessionConfiguration | fl Permission

# Start script here
# Provide credentials
$Cred = get-credential
# Enter user name, surname, department and other contact information
$UserName = Read-Host "Enter user name"
$UserLastName = Read-Host "Enter user last name"
$UserDisplayName = "$UserLastName, $UserName"
$UserSAN = $UserName.substring(0,1) + $UserLastName
$UserDepartment = Read-Host "Enter user department"
$UserTitle = Read-Host "Enter user title"
$UserOffice = Read-Host "Enter user office location"
$UserPhoneNumber = Read-Host "Enter user phone number"

# Here is location OU for local and remote Active Directory
$UserOU = "OU=Users,DC=example,DC=local"
$UserOURemote = "OU=Users,DC=example,DC=remote"
# Local and remote UPN's
$UserUPN = $UserSAN + "@example.local"
$UserUPNRemote = $UserSAN + "@example.remote"

# Import remote PowerShell session into current one
$AD = New-PSSession -ComputerName DC1.example.local -Credential $Cred
Invoke-Command -Session $AD -scriptblock {Import-module ActiveDirectory}
Import-PSSession -Session $AD -Module ActiveDirectory

# User creation process. In my example title is a description
New-AdUser -Name $UserDisplayName -DisplayName $UserDisplayName -Path $UserOU -GivenName $UserName -Surname $UserLastName -SamAccountName $UserSAN -UserPrincipalName $UserUPN -Department $UserDepartment -Title $UserTitle -Description $UserTitle -Office $UserOffice -Company "Company Name" -OtherAttributes @{telephoneNumber=$UserPhoneNumber}

# Remove current session
Get-PSSession | Remove-PSSession

# Import PowerShell session for remote forest
$ADRemote = New-PSSession -ComputerName DC1.example.remote -Credential $Cred
Invoke-Command -Session $ADRemote -scriptblock {Import-module ActiveDirectory}
Import-PSSession -Session $ADRemote -Module ActiveDirectory

# Create user in remote domain
New-AdUser -Name $UserDisplayName -DisplayName $UserDisplayName -Path $UserOURemote -GivenName $UserName -Surname $UserLastName -SamAccountName $UserSAN -UserPrincipalName $UserUPNRemote -Department $UserDepartment -Title $UserTitle -Description $UserTitle -Office $UserOffice -Company "Company Name" -OtherAttributes @{telephoneNumber=$UserPhoneNumber}

# End remote PowerShell Session
Get-PSSession | Remove-PSSession

No comments:

Post a Comment