Home > Mobile >  Create Multiple users in AD and assign a home directory
Create Multiple users in AD and assign a home directory

Time:01-07

I am relitively new to using powershell and all scripting languages so apologies if this is a silly question.

My script is as follows:

$pw = read-host "Password" -AsSecureString 
Import-CSV D:\powershell_create_bulk_users\bulk_users1_Modified.csv | foreach {
New-ADUser -Name $_.Name -SamAccountName $_.SamAccountName -Surname $_.Surname - 
DisplayName $_.DisplayName -Path $_.Path -AccountPassword $pw  -ChangePasswordAtLogon 
$false  -Enabled $true 
$fullPath = '\\NAS\student\'
$driveLetter = "Z:"
$user = Get-ADUser $_.SamAccountName
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath -ea Stop
$homeShare = New-Item -Path $fullPath -ItemType Directory -force -ea Stop
$acl = Get-Acl $homeShare
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, 
ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, 
$FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ErrorAction Stop
}

It creates the user fine and also the drive but only \NAS\student\ and not the what I ideally want which is for E.g \NAS2\student\Tsmith.

I also get an error:

`New-Item : The path is not of a legal form.
 At D:\powershell_create_bulk_users\bulk_users1_Modified.ps1:8 char:14
   ... homeShare = New-Item -Path $fullPath -ItemType Directory -force -ea S ...
                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   CategoryInfo          : InvalidArgument: (\\NAS\student\:String) [New-Item], 
 ArgumentException
   FullyQualifiedErrorId : 
 CreateDirectoryArgumentError,Microsoft.PowerShell.Commands.NewItemCommand`

Was hoping someone could point me in the right direction?

CodePudding user response:

This happens because you forgot to specify the name of the new home directory - New-Item tries to be helpful, and goes "the caller probably wants me to create a folder named student at the path \\NAS" - But \\NAS is not a directory, and the attempt to open it as such results in the error you see.

Change this lines:

$fullPath = '\\NAS\student\'

to:

$basePath = '\\NAS\student\'
# construct full home directory path for user to basepath username
$fullPath = Join-Path $basePath -ChildPath $_.SamAccountName

The subsequent calls to Set-ADUser and New-Item will now create and set the home directory to \\NAS\student\username correctly

  •  Tags:  
  • Related