+ Post New Thread
Results 1 to 10 of 10
Scripts Thread, Powershell AD / Homedir / Profiledir / Mailbox? in Coding and Web Development; Have had a nose around several different posts to do with powershell and creating users from a CSV. I think ...
  1. #1
    mdench's Avatar
    Join Date
    Oct 2011
    Location
    West Sussex
    Posts
    819
    Thank Post
    40
    Thanked 106 Times in 96 Posts
    Rep Power
    39

    Powershell AD / Homedir / Profiledir / Mailbox?

    Have had a nose around several different posts to do with powershell and creating users from a CSV. I think i got the basic sorted ie Name, Surname, Username, Password, Enabled account. I'm wondering if i can use powershell to populate the home directory and profile directory along with the employee ID attribute? then after all that is it possible to have the script create exchange mailboxes or is that pushing it to far?

    Cheers for the help

  2. #2
    old_n07's Avatar
    Join Date
    Jun 2012
    Location
    North Staffordshire
    Posts
    99
    Thank Post
    10
    Thanked 17 Times in 15 Posts
    Rep Power
    8
    You can use the script to create the folder and set the path and drive letter in AD

    We use this to create the users home folder with a hidden "redirected" folder in the home folder ($userhomfolder is a variable for the folder path)

    Code:
                # Create folders ------
    
    
                if(Test-Path $userhomefolder){}
    
                else
    
                {
                New-Item $userhomefolder -type directory
                New-Item $redirected -type directory
                Set-ItemProperty -path $redirected -name Attributes -Value ([system.IO.FileAttributes]::Hidden)
                }
    To set the folder path and drive letter in AD

    Code:
                Set-ADUser $username `
                           -HomeDirectory $userhomefolder `
                           -HomeDrive "H:" `
                           -ProfilePath $userprofilefolder `
    Setting permissions on the created folders

    Code:
    # Set folder permissions ----------------------------------------------------------------------------------------
    
                $FC = "FullControl"
                $Mod = "Modify"
    
                #Users--
    
                $domAdmin = $Shortdom + "domain admins"
                $locadmin = "builtin\Administrators"
                $sys = "NT Authority\System"
                $user = $Shortdom + $username
    
                # Permissions on Home folder ---
                        
                $acl = Get-Acl $userhomefolder
                if ($acl.AreAccessRulesProtected) { $acl.Access | % {$acl.purgeaccessrules($_.IdentityReference)} }
                else {
                		$isProtected = $true 
                		$preserveInheritance = $false
                		$acl.SetAccessRuleProtection($isProtected, $preserveInheritance) 
                	 }
    
                $account1 = $domadmin
                $rights1=[System.Security.AccessControl.FileSystemRights]::$FC
                $inheritance1=[System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
                $propagation1=[System.Security.AccessControl.PropagationFlags]::None
                $allowdeny1=[System.Security.AccessControl.AccessControlType]::Allow
                $dirACE1=New-Object System.Security.AccessControl.FileSystemAccessRule ($account1,$rights1,$inheritance1,$propagation1,$allowdeny1)
                $ACL.AddAccessRule($dirACE1)
    
                $account2 = $locadmin
                $rights2=[System.Security.AccessControl.FileSystemRights]::$FC
                $dirACE2=New-Object System.Security.AccessControl.FileSystemAccessRule ($account2,$rights2,$inheritance1,$propagation1,$allowdeny1)
                $ACL.AddAccessRule($dirACE2)
    
                $account3 = $sys
                $rights3=[System.Security.AccessControl.FileSystemRights]::$FC
                $dirACE3=New-Object System.Security.AccessControl.FileSystemAccessRule ($account3,$rights3,$inheritance1,$propagation1,$allowdeny1)
                $ACL.AddAccessRule($dirACE3)
    
                $account4 = $user
                $rights4=[System.Security.AccessControl.FileSystemRights]::$Mod
                $dirACE4=New-Object System.Security.AccessControl.FileSystemAccessRule ($account4,$rights4,$inheritance1,$propagation1,$allowdeny1)
                $ACL.AddAccessRule($dirACE4)
    
                Set-Acl -aclobject $ACL -Path $userhomefolder
                # Write-Host $userhomefolder Permissions added
    
                # Permissions on redirected folder ---
    
                $Racl = Get-Acl $redirected
    
                $account = $user
                $rights=[System.Security.AccessControl.FileSystemRights]::TakeOwnership
                $allowdeny=[System.Security.AccessControl.AccessControlType]::Allow
                $dirACE=New-Object System.Security.AccessControl.FileSystemAccessRule ($account,$rights,$allowdeny)
                $ACL.AddAccessRule($dirACE)
    
                Set-Acl -aclobject $ACL -Path $redirected
                # Write-Host $redirected Permissions added
    To create the mailbox

    Code:
                # Create Mailbox ----
    
                Enable-mailbox -Identity $username `
                                       -Alias $username `
    Last edited by old_n07; 23rd August 2012 at 09:48 PM.

  3. Thanks to old_n07 from:

    pcstru (24th August 2012)

  4. #3
    mdench's Avatar
    Join Date
    Oct 2011
    Location
    West Sussex
    Posts
    819
    Thank Post
    40
    Thanked 106 Times in 96 Posts
    Rep Power
    39
    Is this all within one script?

  5. #4
    old_n07's Avatar
    Join Date
    Jun 2012
    Location
    North Staffordshire
    Posts
    99
    Thank Post
    10
    Thanked 17 Times in 15 Posts
    Rep Power
    8
    Yes, they are parts taken from one script

  6. #5
    mdench's Avatar
    Join Date
    Oct 2011
    Location
    West Sussex
    Posts
    819
    Thank Post
    40
    Thanked 106 Times in 96 Posts
    Rep Power
    39
    Just been working on this some more so im hoping that i have got below will take the details out of a CSV and create our new intake users in AD. Does this look correct so far?

    Code:
    import-Csv \\martha\intake07\mdench\intake12\one.csv | foreach-object {
    
    $userhomefolder = '\\matrix\intake12\'+$_.SamAccoutName
    $userprofilefolder = '\\matrix\profiles\intake12\'+$_.SamAccountName
    
    New-ADUser  
                -SamAccountName $_.SamAccountName
                -DisplayName $_.SamAccountName 
                -GivenName $_.FirstName 
                -Surname $_.LastName 
                -EmployeeID $_.EmployeeID
                -Path "OU=Users,DC=domain,DC=internal" 
                -AccountPassword (ConvertTo-SecureString "google" -AsPlainText -force) 
                -Enabled $True 
                -ChangePasswordAtLogon $True -PassThru
                -HomeDirectory $userhomefolder
                -HomeDrive "N:"
                -ProfilePath $userprofilefolder                
                 }

    How do you use the enable-mailbox to create a new mailbox for each user? Does it need any extra code to connect to an exchange etc? or does it do something entirely different?

  7. #6
    old_n07's Avatar
    Join Date
    Jun 2012
    Location
    North Staffordshire
    Posts
    99
    Thank Post
    10
    Thanked 17 Times in 15 Posts
    Rep Power
    8
    Are you running your code on the DC or remotely?

    If you want to run it remotely add this to the top of the script to create remote sessions to your DC and \ or exchange server

    Code:
    # Connect to exchange server
    if ( (Get-PSSession -ComputerName email.someschool.ac.uk -ErrorAction SilentlyContinue) -eq $null)
    {
    $Sessemail = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://email.someschool.ac.uk/PowerShell/ -Authentication Kerberos
    Import-PSSession $Sessemail
    }
    
    # Connect to DC
    if ( (Get-PSSession -ComputerName DC.someschool.ac.uk -ErrorAction SilentlyContinue) -eq $null)
    {
    $SessDC02 = New-PSSession  -computername DC.someschool.ac.uk -Authentication Kerberos
    Import-Module ActiveDirectory
    }
    The enable-mailbox commandlet needs Exchange 2007 or newer, as long as you have created a powershell session to the exchange server with your script you can run the command as part of the main script, you may need to put a 5 or 10 second wait into the script so the new account replicates to the exchange server or you may get an account not found error

    Code:
    Start-Sleep -s 5
    Enable-mailbox -Identity $_.SamAccountName -Alias $_.SamAccountName -Database "ExchangeDatabaseName"  #creates the exchange account in the named exchange database.

  8. #7
    mdench's Avatar
    Join Date
    Oct 2011
    Location
    West Sussex
    Posts
    819
    Thank Post
    40
    Thanked 106 Times in 96 Posts
    Rep Power
    39
    This is now what we have for our Script but it is throwing up an error when connecting to the exchange

    Code:
    # Connect to exchange server
    if ( (Get-PSSession -ComputerName exchange.domain.internal) -eq $null)
    {
    $Sessemail = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.domain.internal/PowerShell/ -Authentication Kerberos
    Import-PSSession $Sessemail
    }
    
    # Connect to DC
    if ( (Get-PSSession -ComputerName bex.domain.internal) -eq $null)
    {
    $SessDC02 = New-PSSession  -computername bex.domain.internal -Authentication Kerberos
    Import-Module ActiveDirectory
    }
    
    import-Csv one.csv | foreach-object {
    
    $UserName   = $_.SamAccountName
    $FirstName  = $_.FirstName
    $LastName   = $_.LastName
    $EmployeeID = $_.EmployeeID
    
    echo $UserName
    echo $FirstName
    echo $LastName
    echo $EmployeeID
    
    $userhomefolder = '\\matrix\intake12\'+$UserName
    $userprofilefolder = '\\matrix\profiles\intake12\'+$UserName
    
    New-ADUser -SamAccountName $UserName `
                -DisplayName $UserName  `
                -Name $UserName `
                -GivenName $FirstName  `
                -Surname $LastName  `
                -EmployeeID $EmployeeID `
                -AccountPassword (ConvertTo-SecureString "google" -AsPlainText -force)  `
                -Enabled $True  `
                -ChangePasswordAtLogon $True -PassThru `
                -HomeDirectory $userhomefolder `
                -HomeDrive "N:" `
                -ProfilePath $userprofilefolder `
    
    
    #   -Path "OU=Users,DC=domain,DC=internal"  `
    }
    #Start-Sleep -s 5
    #Enable-mailbox 
    #            -Identity $_.SamAccountName 
    #            -Alias $_.SamAccountName 
    #            -Database "The Weald Exchange - Students Db1"  #creates the exchange account in the named exchange database.
    This is the error

    Code:
    Get-PSSession : Remote Session is not available for exchange.domain.internal.
    At C:\Users\msweet\memememememe.ps1:2 char:20
    + if ( (Get-PSSession <<<<  -ComputerName exchange.domain.internal) -eq $null)
        + CategoryInfo          : InvalidArgument: (exchange.domain.internal:String) [Get-PSSession], ArgumentException
        + FullyQualifiedErrorId : RemoteRunspaceNotAvailableForSpecifiedComputer,Microsoft.PowerShell.Commands.GetPSSessionCommand
    
    [exchange.domain.internal] Connecting to remote server failed with the following error message : The WinRM client received an HTTP status code of 403 from the remote WS-Management service. For m
    ore information, see the about_Remote_Troubleshooting Help topic.
        + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
        + FullyQualifiedErrorId : PSSessionOpenFailed
    Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Supply a non-null argument and try the command again.
    At C:\Users\msweet\memememememe.ps1:5 char:17
    + Import-PSSession <<<<  $Sessemail
        + CategoryInfo          : InvalidData: (:) [Import-PSSession], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSessionCommand
    Is there something really stupid I am missing? Powershell Novice... A quick google gave me this link Connect Remote Exchange Management Shell to an Exchange Server: Exchange 2010 Help

  9. #8
    old_n07's Avatar
    Join Date
    Jun 2012
    Location
    North Staffordshire
    Posts
    99
    Thank Post
    10
    Thanked 17 Times in 15 Posts
    Rep Power
    8
    That is basically the guide we followed, have you installe The Windows management framework on exchange and allowed port 80 through the firewall?

    Is "exchange.domain.internal" the FQDN of your exchange server?

    Edit:

    As a test try disabling the server firewall and try running the script to see if it is a port issue.
    Last edited by old_n07; 3rd September 2012 at 01:30 PM.

  10. #9

    glennda's Avatar
    Join Date
    Jun 2009
    Location
    Sussex
    Posts
    7,821
    Thank Post
    272
    Thanked 1,140 Times in 1,036 Posts
    Rep Power
    351
    Exchange is easy for bulk creating from the console - all you need to do is select new and find all the users which havn't been given a mailbox yet (you can filter to whatever) and the just hit go

  11. #10

    Join Date
    Jun 2013
    Posts
    15
    Thank Post
    0
    Thanked 0 Times in 0 Posts
    Rep Power
    0
    Code:
    Import-Module ActiveDirectory
    import-csv "c:\aduser3.csv"
    
    # Import list of Users From CSV into $Userlist
    $userlist=import-csv "c:\aduser3.csv"
    
    # Step through Each Item in the List
    FOREACH ($user in $UserList) { 
    $user.GivenName
    $user.Surname
    
    # Build Username from First name and Last name
    $Username=$user.GivenName + $user.Surname.substring(0)
    $Username 
    
    # Put our Domain name into a Placeholder
    $Domain=’@sintvictor.local’
    
    #specify the homefolder
    $homedirectory="\\SVSERVER\Home$\$username"
    $redirected="\\SVSERVER\Home$\redirected"
    
    # Build the User Principal Name Username with Domain added to it
    $UPN=$Username+$Domain
    
    # Create the Displayname
    $Name=$user.GivenName + ” “ + $user.Surname
    
    if(Test-Path $homedirectory){}
                else
    
                {
                New-Item $homedirectory -type directory
                New-Item $redirected -type directory
                Set-ItemProperty -path $redirected -name Attributes -Value ([system.IO.FileAttributes]::Hidden)
                }
    
    # Create User in Active Directory$($user.samaccountname)
    new-ADUser –GivenName $user.GivenName –Surname $user.Surname –Name $Name –SamAccountName $Username –AccountPassword (ConvertTo-SecureString "abc123+" -AsPlaintext -Force) –UserPrincipalName $UPN –Path ‘OU=SVA,DC=sintvictor,DC=local’ -enabled $true -ChangePasswordAtLogon $true -Homedrive H: -HomeDirectory $homedirectory
    
    }



    Why isn't my H drive visible on the client? All the folders are getting created correctly....
    thx



SHARE:
+ Post New Thread

Similar Threads

  1. Replies: 2
    Last Post: 2nd March 2011, 01:35 PM
  2. Replies: 0
    Last Post: 10th February 2011, 08:57 AM
  3. Replies: 2
    Last Post: 12th August 2010, 01:15 PM
  4. Powershell modify multi-string values in AD
    By maf_001 in forum Scripts
    Replies: 1
    Last Post: 28th August 2009, 02:12 PM
  5. Creating mailboxes in exchange 2007 when a user is created in AD on another server
    By thesk8rjesus in forum Network and Classroom Management
    Replies: 2
    Last Post: 5th September 2008, 03:53 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
  •