+ Post New Thread
Results 1 to 4 of 4
Windows Server 2008 R2 Thread, Powershell for User Creation - Creating a User Network Drive in Technical; Hi, I have the following powershell script to create users. What I need to do is get it to create ...
  1. #1
    jdell's Avatar
    Join Date
    Mar 2012
    Location
    Swindon
    Posts
    82
    Thank Post
    5
    Thanked 4 Times in 3 Posts
    Rep Power
    5

    Question Powershell for User Creation - Creating a User Network Drive

    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 "-------------------------------------------------------------------"


    }


    }

  2. #2

    sonofsanta's Avatar
    Join Date
    Dec 2009
    Location
    Lincolnshire, UK
    Posts
    4,466
    Thank Post
    750
    Thanked 1,210 Times in 852 Posts
    Blog Entries
    45
    Rep Power
    533
    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:
    Code:
    ./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)

  3. #3

    Join Date
    Jul 2012
    Location
    Boerne Texas USA
    Posts
    41
    Thank Post
    0
    Thanked 9 Times in 9 Posts
    Rep Power
    5

    My script

    A bit of a mess but maybe you can get what you need out of it!

    Code:
    #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
    	}

  4. #4

    Join Date
    Nov 2011
    Location
    Manchester
    Posts
    47
    Thank Post
    2
    Thanked 10 Times in 9 Posts
    Rep Power
    6
    Code:
    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

SHARE:
+ Post New Thread

Similar Threads

  1. Users can create shortcuts to network locations??? Any way to sort this?
    By burgemaster in forum Windows Server 2000/2003
    Replies: 15
    Last Post: 3rd August 2011, 12:06 PM
  2. Replies: 4
    Last Post: 20th April 2010, 04:31 PM
  3. Ad Infinitum file format for user creation?
    By tazz in forum How do you do....it?
    Replies: 1
    Last Post: 28th August 2009, 05:26 PM
  4. Active Directory-Script for Creating Bulk Users
    By calapso in forum How do you do....it?
    Replies: 8
    Last Post: 14th January 2009, 06:32 PM
  5. Replies: 0
    Last Post: 17th February 2007, 04:43 PM

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •