Link to home
Start Free TrialLog in
Avatar of Islandr
Islandr

asked on

Query AD based on a users list, Create a folder in a Share based on usernames and set permissions

Hi Experts,

I pull the following script from the script repository, but that is the closest that I can get to what I am looking for, What I would like to do is to:

1. Query the AD based on a specific list of users (they just provided with regular first name and last names NOT username)
2. Pull those specific users from the AD and create folders for every user based on their usernames.
3. Set permissions (Full Admin rights) for every folders created.

Here is what I found that is closed to what I am looking for, in the following, this add a home directory, I do not want HOME directories because I already have it.  So, basically is:
Query AD based on a users list, Create a folder in a Share based on usernames and set permissions.

Script:

' Create HomeDir.vbs, 3:32 PM 1/4/2006
'
' File purpose: Add home directories for users on \\HOME\USER dfs share
'   Create File with list of users (userlist.txt)
'   Test if user account active
'   Test if Home directory exists
'   If home directory doesn't exist
'     Create Home Directory
'     Apply permissions using CACLS.EXE (v5.1.2600.0 or newer) may need to download from
'           (Microsoft or get from Windows 2003 Resource kit)
'     Set Home directory location in drive letter
'   Get next user until end of file (userlist.txt)
'
' To create "UserList.txt" file that the program reads execute the following command.
'   DSQUERY USER OU=IS,OU=PDX,DC=corp,DC=edu-resources,DC=com -LIMIT 0 >UserList.txt
' This creates a DN list with each user in quotes.
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
          'clear file for next report
Set RepFile = objFso.OpenTextFile("HomeDirReport.txt", 2, True)

Const USER_ROOT_UNC = "\\pdx23\home"
Const USER_HOME_UNC = "\\Corp\Home"

Set objArgs = WScript.Arguments
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("userlist.txt", 1)       '1 is for reading file only
Set WshShell = Wscript.CreateObject("Wscript.Shell")
 
        ' Read file line by line until end is reached
Do While objTextFile.AtEndOfStream <> True
  strNextLine = objTextFile.Readline
  wscript.echo strNextLine

          ' Check to see if user account is disabled
          ' Remove qoutes from text file          
  TrimUser = "LDAP://" & replace(strNextLine, chr(34),"")      ' Remove qoutes to use GetObject
  Set objUser = GetObject(TrimUser)

  if objuser.AccountDisabled = False then          ' True when Account Disabled is False
    WScript.Echo "The account is enabled."
    HomeDir = objuser.SamAccountName          
    ' Use mailNickName or SamAccountName, logon name doesn't work

         ' Does Home directory exist?
    if objFSO.FolderExists(USER_ROOT_UNC & "\" & HomeDir) Then
           ' Do nothing, directory already exists.
    Else
         ' Create User directory on \\corp\home\....
        Set objFS = CreateObject("Scripting.FileSystemObject")
        Call objFS.CreateFolder(USER_HOME_UNC & "\" & HomeDir)    ' Create home directory

           ' Set NTFS permissions on Home directory, use external program xcacls
        Call SetUserDirPerm()

    End If
         'Folder and home entries completed
  Else
           ' The account is disabled.
  End If
         ' No more users in file
wrtToFile()
Loop
'
'
'          ' Set NTFS permissions on Home directory, use external program xcacls
Sub SetUserDirPerm()
   Call WshShell.Run("Cacls " & USER_ROOT_UNC & "\" & HomeDir & _
   " /E /G " & "CORP\" & HomeDir & ":C", Hide_window, Wait_on_Return)
End Sub

'
'      Save user information to text file "HomeDirReport.txt"
Sub WrtToFile()
 Set RepFile = objFso.OpenTextFile("HomeDirReport.txt", 8, True)
             ' Open file for appending, create if needed
 RepFile.writeLine
 RepFile.writeLine(objuser.SamAccountName & " Disabled:" & objuser.AccountDisabled & _
    " "& USER_HOME_UNC & "\" & HomeDir)
 RepFile.close
End Sub

Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

I have a script that does a very similar thing for my environment, I've adapted it to potentially fit here.

I've used the Quest AD CmdLets because it simplifies things. Those are optional, we can use the MS AD CmdLets or just base PowerShell if necessarily.
Add-PsSnapIn Quest.ActiveRoles.ADManagement

$FileServer = "YourServer"

# Read from a list of users
Get-Content "User List.txt" | ForEach-Object {

  # Attempt to grab the user by name
  $User = Get-QADUser  -Name $_

  # If the user exists and the home directory does not
  If ($User -And !(Test-Path \\$FileServer\Users\$($User.SamAccountName)) {

    # Directory does not exist, creating
    $Directory = New-Item -Name $User.SamAccountName -Path "\\$FileServer\Users" -ItemType Directory

    # Disable inheritance
    $Acl = Get-Acl $Directory.FullName
    $Acl.SetAccessRuleProtection($True, $True)
    Set-Acl $Directory.FullName -AclObject $Acl    

    # Clean up the ACL (removes a group granting access to the parent folder in my case)
    $Acl = Get-Acl $Directory.FullName
    $AccessRule = $ACl.Access | Where-Object { $_.IdentityReference -Match 'Some Group' }
    $Acl.RemoveAccessRuleSpecific($AccessRule)

    # Create and apply an access rule to give the user some access
    $AccessRule = New-Object Security.AccessControl.FileSystemAccessRule(
      "YOUR-DOMAIN\$($User.SamAccountName)",
      "Modify", 
      @("ObjectInherit", "ContainerInherit"), 
      "None", 
      "Allow")
    $Acl.AddAccessRule($AccessRule)
    Set-Acl $Directory.FullName -AclObject $Acl
  }
}

Open in new window

HTH

Chris
Avatar of Islandr
Islandr

ASKER

Chris-Dent,

Thank you for replying, but when ran the script, I am getting the following:

Unexpected token '{' in expression or statement.
At C:\AD_Create_user.PS1:12 char:76
+   If ($User -And !(Test-Path \\$FileServer\Users\$($User.SamAccountName)) { <<<<
    + CategoryInfo          : ParserError: ({:String) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

Please let me know what this might be.

Thanks,
ASKER CERTIFIED SOLUTION
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Islandr

ASKER

Chris,

This is what I a got:

# Add-PsSnapIn Quest.ActiveRoles.ADManagement

$FileServer = "DCADL-W-1"

# Read from a list of users
Get-Content "UserList.txt" | ForEach-Object {

  # Attempt to grab the user by name
  $User = Get-QADUser  -Name $_

  # If the user exists and the home directory does not
  If ($User -And !(Test-Path "\\$FileServer\Users\$($User.SamAccountName)")) {

    # Directory does not exist, creating
    $Directory = New-Item -Name $User.SamAccountName -Path "\\$FileServer\Users" -ItemType Directory

    # Disable inheritance
    $Acl = Get-Acl $Directory.FullName
    $Acl.SetAccessRuleProtection($True, $True)
    Set-Acl $Directory.FullName -AclObject $Acl    

    # Clean up the ACL (removes a group granting access to the parent folder in my case)
    $Acl = Get-Acl $Directory.FullName
    $AccessRule = $ACl.Access | Where-Object { $_.IdentityReference -Match 'Some Group' }
    $Acl.RemoveAccessRuleSpecific($AccessRule)

    # Create and apply an access rule to give the user some access
    $AccessRule = New-Object Security.AccessControl.FileSystemAccessRule(
      "DCA\$($User.SamAccountName)",
      "Modify",
      @("ObjectInherit", "ContainerInherit"),
      "None",
      "Allow")
    $Acl.AddAccessRule($AccessRule)
    Set-Acl $Directory.FullName -AclObject $Acl
  }
}

I commented the very first line because I already added that role, but when I ran the script it does not do anything.  

Any ideas?
What do you have in UserList.txt?

At the moment we're grabbing an entry from the file and doing this for each of them:

Get-QADUser  -Name "That User"

Name is the name as you see it in AD Users and Computers. We might change that to look at DisplayName instead for example.

Chris
Avatar of Islandr

ASKER

Chris,

Do you meant Get-QADUser  -Name "That User"  OR Get-QADUser  -Identity "That User" because I am using Quest AD CmdLets.

Get-QADUser  -Name "That User" is not working.

Thanks,



Avatar of Islandr

ASKER

Chris,

Any Ideas?
Sorry for the delay, I was a bit busy last night.

I used "Get-QADUesr -Name <Some Name>" because the results it can return are more limited than "Get-QADUser -Identity <Some Name>". And I did that because I always try to build searches that will capture the smallest number of users (ideally just one).

If you find mine doesn't work, you might have more luck with "Get-QADUser -DisplayName <Some Name>". It's still a very limited search, which means we have more chance of getting it right, but like the first search it's dependent on how you've arranged AD.

That said, if you prefer to go with "Get-QADUser -Identity <Some User>" then by all means do so, as long as the results you're getting are accurate enough for your purposes.

Chris
Avatar of Islandr

ASKER

Chris-Dent,

I'll get back to you soon.
Avatar of Islandr

ASKER

Chris-Dent,

I would like to apologized for not getting back to you, but I am here now, and I would like to finish the script where we started, I just want to point that using the Get-QADUser -Name did not worked and when I look on the help by typing "help Get-QADUser -Example" did not get an entry for that particular line, however, I'll grant you the 500 points, because that was the only issue that I found.   Please let me know if any other modifications.

Thanks,
Avatar of Islandr

ASKER

The script was helpful, with some modifications.