jdell Posted October 8, 2013 Posted October 8, 2013 Hi, I have the following powershell script to create users. What I need to do is get it to create a network share on the server \\server\(username - $SAM) and give that user control over the share, I am importing hundreds of users and don't really want to manually provision shares. My full code I am using is below and this works apart from creating the users home drive on a specific server. Any Help would be appreciated. $date = Get-Date #Set up Log files for output $ErrorLog = "C:\PS\Errorlog.txt" $SuccessLog = "C:\PS\Successlog.txt" Add-Content $SuccessLog "-----------------------------------------------------------------" Add-Content $SuccessLog $date Add-Content $SuccessLog "-----------------------------------------------------------------" Add-Content $ErrorLog "-------------------------------------------------------------------" Add-Content $ErrorLog $date Add-Content $ErrorLog "-------------------------------------------------------------------" ## Create Session with Exchange 2010 change your URI address $s=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeserver/powershell -Authentication Kerberos ## Add AD Cmdlets Import-Module ActiveDirectory #Import CSV $csv = @() $csv = Import-Csv -Delimiter "," -Path "C:\PS\JD\newADuserList.csv" #Get Domain Base $searchbase = Get-ADDomain | ForEach { $_.DistinguishedName } #Loop through all items in the CSV ForEach ($user In $csv) { ## change your OU with your own OU $OU = $User.'OU' $Password = $User.Password $title= $user.'Title' $lastname= ($user.'LastName'.Substring(0,1).toupper() + $User.'LastName'.Substring(1).tolower()) $Detailedname = $User.'FirstName' + " " + $lastname $UserFirstname = $User.'FirstName' $SAM = $User.'Username' $UPN= $SAM + "@domain" $Displayname= $User.'Username' $Dis= $User.'title' + " " + "$Detailedname" $group= "StudentsSiteA" $homedrive= $user.'Home Drive'+ $SAM $logonscript= "KIX32.EXE STUDENT.KIX" $database= $User.'Database' #Check if the User exists $NameID = $user.'Username' $User = Get-ADUser -LDAPFilter "(SamAccountName=$NameID)" If ($User -eq $Null) { #Create the User if it doesn't exist $create = New-ADUser -Name $SAM -SamAccountName $SAM -UserPrincipalName $UPN -DisplayName $Displayname -Path $OU -GivenName $UserFirstname -Surname $lastname -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Description $Dis -HomeDrive Z: -HomeDirectory $homedrive -ScriptPath "KIX32.EXE STUDENT.KIX" -ChangePasswordAtLogon $true ; do { sleep -seconds 3 $accountExists = get-ADUser -LDAPFilter "(SamAccountName=$SAM)" Write-Host "." -nonewline } while ($accountExists -eq !$Null) Write-Host "AD Account $Detailedname created!" add-content $SuccessLog "User $SAM created Sucessfully." ## Adding User to Group Add-ADPrincipalGroupMembership -Identity $SAM -MemberOf $group Write-Host " Added to Groups Needed" add-content $SuccessLog "AD User $SAM Added to groups Sucessfully." Write-Host -ForegroundColor Green $SAM ## Creating Mailbox on EX2010 Enable-Mailbox -Identity $SAM -Alias $SAM -Database $database ## Set Dial in Properties set-aduser $SAM -replace @{msnpallowdialin=$true} Add-Content $SuccessLog "-------------------------------------------------------------------" } Else { ## If user already exists unlock and enable user account and log message in error log. Unlock-ADAccount -Identity $SAM Enable-ADAccount -Identity $SAM Write-Host -ForegroundColor Red "AD User $SAM already exists. Account unlocked." add-content $ErrorLog " User Already exist : $Detailedname. Account unlocked" Add-Content $ErrorLog "-------------------------------------------------------------------" } }
sonofsanta Posted October 8, 2013 Posted October 8, 2013 Download this PowerShell script into the same folder as your existing script, removing the .txt extension: setfolderpermission.ps1.txt Then use the following line to create the directory with the relevant permissions: ./SetFolderPermission.ps1 -Path $line.hmdir -Access $user -Permission FullControl (change the $line.hmdir and $user variables to what you need - those are the variables in my user provisioning script that runs from a CSV)
jklight Posted October 8, 2013 Posted October 8, 2013 A bit of a mess but maybe you can get what you need out of it! #CREATE USER DIRECTORY try { $homeDir=$UsersDir+"\"+$User if (!(Test-Path -path $homeDir)) { New-Item $homeDir -type directory | Out-Null Set-ItemProperty $homeDir -name attributes -value ([system.IO.FileAttributes]::Hidden) } } catch [Exception] { write-host $_.Exception.ToString()+" "+$homeDir+$Logon+"ERROR 700"; ExitWithCode (700) } $LocalPath="M:\"+$School+"\students" $Sharename = $Logon+"$" $checkShare = Get-WmiObject Win32_Share -computername $HomeSrv -Filter "Name='$ShareName'" if ($checkShare -ne $null) { # "Share exists and will now be deleted!!!" write-host "Share exists and will now be deleted!!!"+$ShareName get-WmiObject Win32_Share -computername $HomeSrv -Filter "Name='$ShareName'" | foreach-object { $_.Delete() } | Out-Null } try { #share the new home directory $Class = "Win32_Share" $Method = "Create" $description = "Home drive for:"+$User $sd = ([WMIClass] "\\$HomeSrv\root\cimv2:Win32_SecurityDescriptor").CreateInstance() $ACE = ([WMIClass] "\\$HomeSrv\root\cimv2:Win32_ACE").CreateInstance() $Trustee = ([WMIClass] "\\$HomeSrv\root\cimv2:Win32_Trustee").CreateInstance() $Trustee.Name = "EVERYONE" $Trustee.Domain = $Null $Trustee.SID = @(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0) $ace.AccessMask = 2032127 $ace.AceFlags = 3 $ace.AceType = 0 $ACE.Trustee = $Trustee $sd.DACL += $ACE.psObject.baseobject $mc = [WmiClass]"\\$HomeSrv\ROOT\CIMV2:$Class" $InParams = $mc.psbase.GetMethodParameters($Method) $InParams.Access = $sd $InParams.Description = $description $InParams.MaximumAllowed = 4 $InParams.Name = $Sharename $InParams.Password = $Null $InParams.Path = $LocalPath+"\"+$user $InParams.Type = [uint32]0 $R = $mc.PSBase.InvokeMethod($Method, $InParams, $Null) switch ($($R.ReturnValue)) { 0 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Success"; break} 2 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Access Denied" -foregroundcolor red -backgroundcolor yellow;break} 8 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Unknown Failure" -foregroundcolor red -backgroundcolor yellow;break} 9 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Invalid Name" -foregroundcolor red -backgroundcolor yellow;break} 10 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Invalid Level" -foregroundcolor red -backgroundcolor yellow;break} 21 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Invalid Parameter" -foregroundcolor red -backgroundcolor yellow;break} 22 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Duplicate Share" -foregroundcolor red -backgroundcolor yellow;break} 23 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Reedirected Path" -foregroundcolor red -backgroundcolor yellow;break} 24 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Unknown Device or Directory" -foregroundcolor red -backgroundcolor yellow;break} 25 {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:Network Name Not Found" -foregroundcolor red -backgroundcolor yellow;break} default {Write-Host "Share:$Sharename Path:$LocalPath\$user Result:*** Unknown Error ***" -foregroundcolor red -backgroundcolor yellow;break} } } catch [Exception] { write-host $_.Exception.ToString()+$Logon+"$ "+$LocalPath+"\"+$user+"ERROR 800"; ExitWithCode (800) } try { # set access permissions $acl = Get-Acl $homeDir $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Logon,"ReadData,ReadAttributes,ReadExtendedAttributes,ReadPermissions,WriteData,AppendData,WriteExtendedAttributes,DeleteSubdirectoriesAndFiles,Delete,Synchronize,Traverse,TakeOwnership", "ContainerInherit", "None", "Allow") $acl.AddAccessRule($rule) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Logon,"ReadData,ReadAttributes,ReadExtendedAttributes,ReadPermissions,WriteData,AppendData,WriteAttributes,WriteExtendedAttributes,DeleteSubdirectoriesAndFiles,Delete,Synchronize,TakeOwnership", "ObjectInherit", "InheritOnly ", "Allow") $acl.AddAccessRule($rule) $acl.SetOwner([system.Security.Principal.NTAccount] $Logon) Set-Acl $homeDir $acl } catch [Exception] { Start-Sleep -Seconds 60 # WAIT AND TRY AGAIN $acl = Get-Acl $homeDir $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Logon,"ReadData,ReadAttributes,ReadExtendedAttributes,ReadPermissions,WriteData,AppendData,WriteExtendedAttributes,DeleteSubdirectoriesAndFiles,Delete,Synchronize,Traverse,TakeOwnership", "ContainerInherit", "None", "Allow") $acl.AddAccessRule($rule) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Logon,"ReadData,ReadAttributes,ReadExtendedAttributes,ReadPermissions,WriteData,AppendData,WriteAttributes,WriteExtendedAttributes,DeleteSubdirectoriesAndFiles,Delete,Synchronize,TakeOwnership", "ObjectInherit", "InheritOnly ", "Allow") $acl.AddAccessRule($rule) $acl.SetOwner([system.Security.Principal.NTAccount] $Logon) Set-Acl $homeDir $acl }
Jonah Posted October 8, 2013 Posted October 8, 2013 New-Item \\server\path\$student_login\ -type directory Start-Sleep -s 6 $stuacl = Get-Acl \\server\path\$student_login\ Start-Sleep -s 6 $stuperms = New-Object system.security.accesscontrol.filesystemaccessrule($student_login,"FullControl","ContainerInherit, ObjectInherit","None","Allow") $stuacl.SetAccessRule($stuperms) Set-Acl \\server\path\$student_login $stuacl
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now