Home » Articles posted by Mark Vale (Page 23)

Author Archives: Mark Vale

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>

Performing an Offline Domain Join

Sometimes it is necessary to perform an Offline Domain join of a computer. This is usually for a remote computer with no immediate access to the domain network. You can use DJOIN to perform and offline domain join and force the machine to apply group policies that would normally be applied whilst connected to the network.

First you need to prepare the offline domain join request by logging on to a domain joined machine and opening command prompt. We create the request by stating the computername to join and any policy names (GPOs) you want to apply immediately.

Example Direct Access

On the windows joined machine enter the following command to prepare the offline domain join

djoin.exe /provision /domain <domain.local> /machine <machinenametojoin> /savefile c:\<machinename>.txt /POLICYNAMES "Direct Access Settings, User Restrictions GPO"

The Policy names are the names of the GPOs you want to apply. Copy the file it created to the root of C:\ on the remote workstation

Open command prompt on the remote workstation and issue this command

djoin.exe /requestODJ /loadfile: c:\<machinename>.txt /windowspath %systemroot% /localos

Restart the machine and it will be domain joined with policies applied

Resetting Office 365 Password using Powershell

To reset an office 365 user’s password you need the Windows Azure Active Directory Module installed http://msdn.microsoft.com/en-us/library/azure/jj151815.aspx

Open the console and enter


Press Enter, enter your admin Office 365 account username and password in the logon box

Then issue this command

Set-MsolUserPassword -UserPrincipalName cphillip@domain.com -NewPassword London1234 -ForceChangePassword $false

Resetting User’s Password in Active Directory Using Powershell

This command and script was created for ease of convenience, simplicity and speed during a recent job


Set-ADAccountPassword <username> -Reset -NewPassword (ConvertTo-SecureString -AsPlainText <password> -Force)

And to prevent them from changing or changing at logon

Set-AdUser -Identity <username> -CannotChangePassword:$true -ChangePasswordAtLogon:$false

Adding Locations to Lync 2013 without using E911

Automatic setting of users location in Lync is controlled by the users subnet and the lync location database. The location database can only be accessed using Lync Management Shell. Microsoft supported process is to configure location policies with E911. However, if you are not in the USA like me E911 is pretty much useless. Fortunately, you can use the location database independently and without any location policies in Lync. By entering subnet and site data directly into the database you will ensure that if the subnet the lync client is on is listed in the location database this will be automatically updated when the user signs in.

To achieve this create a csv file called subnets.csv with column headers of Location, Subnet, City and CompanyName

Fill out the location column with the site location name you want e.g “HQ”, the Subnet will be (it only works with /24), City Name and the Company Name

UPDATE FEB 2015 – I have created a simple webpage that will generate the CSV file for you. Working on large deployments with /8 subnets can be quite tedious to display all the /24 subnets within this range. So 10 minutes of PHP coding I was able to save hours of pain. http://www.hostedhouse.co.uk/subnets.php 

Then use this Powershell Script to update the Lis Database

$File = "C:\subnets.csv" $Log = New-Item -ItemType File -Path "C:\subnetlog.txt" -Force
#Import csv $sitecsv = Import-Csv -path $file -Delimiter ','
#Check if user file is empty. if ($sitecsv -eq $null) {  write-host "No subnets Found in Input File"  exit 0 }
#Get total number of users in CSV file and begin processing.
$count = $sitecsv | Measure-Object | Select-Object -expand count
Write-Host "Found " $count "subnets to import." Write-Host "Processing subnets.....`n" $index = 1
ForEach ($site in $sitecsv)
Write-Host "Processing subnet " $index " of " $count -ForegroundColor Cyan $location = $site.Location $subnet = $site.Subnet $city = $site.City $company = $site.CompanyName
#Check subnet exists. Log if they are NOT.
$checksubnet = Get-CsLisSubnet | Where-Object {$_.Subnet -eq "$subnet"}
if ($checsubnet -eq $null) { $notinad = $true
Set-CsLisSubnet -Subnet "$subnet" -Location "$location" -City "$city" -CompanyName "$company"  Write-Host "Location Added Successfully" -ForegroundColor Green
else { $notinad = $false
Write-Host "User " $subnet " is is already added to database." -Foregroundcolor white -BackgroundColor Red Add-Content -Path $Log -Value "$($subnet) is already added to database."
$index++ }
Write-Host "Importing of subnets from CSV completed! Now publishing Dataabase Config"
Write-Host "Completed"

Adding Pictures to Active Directory

I came across this challenge when installing Lync 2013 where a customer did not have Exchange 2013 and therefore unable to us HD pictures in Lync and Exchange. Prior to Exchange 2013 the only way to import pictures is to use Active Directory to store the image. Storing images in AD have specific requirements. The format must be .jpg or .gif and the image size must be no more than 48×48 pixels. There is a cool image resizer tool that someone has made compatible with windows 7 (it works for windows 8 too) https://imageresizer.codeplex.com/releases/view/30247 Anyway to achiever my goal I created a CSV file which includes the column headers ADUserName and Picture. In the ADUserName column add the samAccountName of the user and in the Picture column add the literal location of the picture you want to use e.g c:\pictures\user.one.jpg

The rest is done by PowerShell

#change parameters here
 $Log = New-Item -ItemType File -Path "C:\ADPictureLog.txt" -Force
 $File = "C:\ADPictures.csv"
 #Import csv
 $usercsv = Import-Csv -path $file -Delimiter ','
#Check if user file is empty.
 if ($Usercsv -eq $null)
  write-host "No Users Found in Input File"
  exit 0
$count = $Usercsv | Measure-Object | Select-Object -expand count
Write-Host "Found " $count "Users to import."
 Write-Host "Processing Users.....`n"
 $index = 1
ForEach ($User in $Usercsv)
 Write-Host "Processing User " $index " of " $count
 $ADUserName = $User.ADUserName
  $UserPicture = $User.Picture
 $CheckAD = Get-ADUser -Identity $ADUserName
 if ($CheckAD -eq $null) {
  $notinad = $true
  Write-Host "User " $ADUserName " is not found in AD. Double check spelling, etc." -Foregroundcolor Red
  Add-Content -Path $Log -Value "$($ADUserName) is not found in AD. Double check spelling, etc."
else {
  #import photograph
  $Photo = [byte[]](Get-Content $UserPicture -Encoding byte)
  Set-ADUser -Identity $ADUserName -Replace @{thumbnailPhoto=$Photo}
  Write-Host "User: " $ADUserName " Photo has been updated with " $UserPicture " Ok"
  Add-Content -Path $Log -Value "$($ADUserName) has been updated with a photograph $($UserPicture)"
 Write-Host "Picture Updates have been Completed"
 Add-Content -Path $Log -Value "End of Log"
%d bloggers like this: