Powershell Tutorial Part 2: How to Create new Directory Share For AD users with Powershell

Powershell Tutorial
Get AD user Home Drive with Powershell

Powershell Tutorial Part 2: How to Create new network home folder for  AD users with Powershell

Round 2 Fight

So once I founded out which users had network shares and which one didn’t I decided to create new shares for the users without  based on the OU they are part of.

 

Tasks:

  • Ask for OU to query
  • Search OU and get users
  • Assigned Drive Letter to Users
  • Assigned Home directory Path
  • Create New-Item(i.e Folder)
  • Give user full permission to folder

 

## Read OU name from users

$OU= Read-Host "Please Enter an OU"

 

## Get User information based on the OU provided above
$users = Get-ADUser -Filter * -SearchBase "OU=$OU,DC=mydomain,DC=loc"

 

## Loop the $users variable and do the following: Assigned Path and Drive

foreach ($user in $users)
{

$username = $user.SamAccountName

#Directory Path

$path ='\\DC01\users\'

#Drive Letter

$homeDrive='H:'

$HDrive=$path+$username

#if Folder doesn't exist, create new one

if(!Test-Path -Path $HDrive){

 

#Command to create new folder

New-Item -Name $username -ItemType Directory -Path $Path
}

##ACL NTFS permission

$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [system.security.accesscontrol.PropagationFlags]"None"

#Get the Directory
$Acl = Get-Acl $HDrive

$obj = new-object system.security.AccessControl.FileSystemAccessRule("$username","FullControl","$inherit","$propagation","Allow")

 

$Acl.AddAccessRule($obj)

# Set Permission
Set-Acl $HDrive $Acl

 

set-aduser $user.samAccountName -HomeDrive $homeDrive -HomeDirectory $HDrive

Get-Acl $HDrive

}

 

 This is how I got the user information: 

Be the first to comment

Leave a Reply

Your email address will not be published.


*