Jump to content

Recommended Posts

Posted (edited)

Hi All

 

I need to create 300 AD user accounts. I have created the accounts and work folders using AccountManagement_release13072011.xls which still seems to work but I cannot change folder permissions as a required DLL is no longer available.

 

The work folder name is the account name so Joe Bloggs has the account name 25Joe and his work folder is called 25Joe. There are no subfolders so recursion is not necessary. There is just a top level folder like this.

test|_25Joe
      |_25Sid
      |_25Mary

 

I am testing a simple batch script.

 

echo off
for /D %%a in ("C:\Users\user\Desktop\test\*.*") do (
echo %%a

REM use icacls here
)
pause

 

Echo %%a gives the expected result "C:\Users\user\Desktop\test\25Joe" but I just cannot find the correct command to get the folder name 25Joe off the end and stored to a variable.
 

Edited by Caffeine11
Posted

What is the name of the missing dll?

 

Searching for "AccountManagement_release13072011" leads to a PDF that describes using WiseSoft User Management Tool.

 

This page:

 

Link: Bulk AD Users - wiseDATAman

 

Includes a download link for "WiseSoftBulkADUsers.zip" 

 

The Zip file includes the dlls:

 

WiseSoftDLLs.thumb.png.098fc49bdd7dadd22687b0603ce8b966.png

 

Could one of these be your missing dll?

Posted

Hi 6Foot2

 

Thank you for taking the time to reply. The missing dll is ADsSecurity.dll. It is part of the ADSI SDK (version 2.5) which is no longer available.

 

I looked at Bulk AD Users but the documentation suggests it is to modify existing user accounts, not to create new ones.

 

I was rather surprised when the only options for creating AD user accounts appeared to be paid for products or a powershell script and a csv file. The example powershell scripts don't add users to groups or create work folders etc which is why I am using the Account Management Excel spreadsheet. It does the lot. 

 

I am just irritated that I cannot seem to get the right syntax to get the folder name out of the path. 

  

 

 

Posted

You can do this using powershell.

 

Something similar to this?

 

$parentPath = "C:\Users\user\Desktop\test"

# Loop through each folder
Get-ChildItem -Path $parentPath -Directory | ForEach-Object {
    $folder = $_.FullName       # Full path, e.g., C:\Users\user\Desktop\test\25Joe
    $user = $_.Name             # Folder name, e.g., 25Joe

    Write-Host "Setting permissions for $user on $folder"

    # Grant Modify rights to the user
    icacls $folder /grant "$user:(OI)(CI)M" /T
}

Posted
18 hours ago, Caffeine11 said:

Hi All

 

I need to create 300 AD user accounts. I have created the accounts and work folders using AccountManagement_release13072011.xls which still seems to work but I cannot change folder permissions as a required DLL is no longer available.

 

The work folder name is the account name so Joe Bloggs has the account name 25Joe and his work folder is called 25Joe. There are no subfolders so recursion is not necessary. There is just a top level folder like this.

test|_25Joe
      |_25Sid
      |_25Mary

 

I am testing a simple batch script.

 

echo off
for /D %%a in ("C:\Users\user\Desktop\test\*.*") do (
echo %%a

REM use icacls here
)
pause

 

Echo %%a gives the expected result "C:\Users\user\Desktop\test\25Joe" but I just cannot find the correct command to get the folder name 25Joe off the end and stored to a variable.
 

 

Try this:

 

@echo off
setlocal enabledelayedexpansion
for /D %%a in ("C:\Users\user\Desktop\test\*") do (
	set folderPath=%%a
	for %%b in (!folderPath!) do (
		set username=%%~nxb
	)
	echo !username!
	REM use icacls here
)
endlocal

 

As an aside, I can say from my own experience that user account provisioning/deprovisioning is a great 'in' for learning PowerShell

 

Posted

I couldn't tell if you already have created the AD accounts or you just wanted folders created and permissions set correctly, I wrote this a fair few years ago (and probably got some from a forum) but this is what i use to find and fix permission issues on home folders, it will create the folder and a desktop/documents/fav subfolder if it doesn't exist which you can commented out if not needed. Its not the prettiest and was written in circa 2018 so don't judge! use at your own risk! You just need to amend the fields in the variable section  

 

<#############################################################################
Script: Set-ACL_HomeFolders.ps1
Author: Ben Drew
Date: 14.11.2018
Keywords:Permissions
Comments:
Pre-Requisites: Admin rights to AD.

+------------+-----+---------------------------------------------------------+
|       Date | Usr | Description                                             |
+------------+-----+---------------------------------------------------------+
| 14/11/2018 | BD  | Initial Script                                          |
+------------+-----+---------------------------------------------------------+
| 07/06/2019 | BD  | Rewritten to include setting owner and subfolder        |
|            |     | creation.                                               |
+------------+-----+---------------------------------------------------------+

DISCLAIMER
==========
THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
  
Notes
=====
This script will look to the OU defined in $searchbase and pull every username it finds, 
it will then check in the directory defined in $searchbase to see if theres a folder and create
if they're not already there and then set the permission.

This script is to be used on the Folder Redirection Folder and/or Home folders

!!!!! RUN FROM THE C:\Scripts FOLDER !!!!!

#############################################################################>

# =====================================
# Variables - ONLY EDIT IN THIS SECTION
# =====================================
#
$Right = "Modify"
$domain = "999"
$searchbase = "OU=Users,OU=!9990,DC=999,DC=com"
$HomeDirPath = "D:\FolderRedirection"
$logpath = "C:\Scripts\Logs\Set-Create-HomeFolders-Log.txt"
$DC = 'DC01.999.com'
#
#>
$AdjustTokenPrivileges = @"
using System;
using System.Runtime.InteropServices;

 public class TokenManipulator
 {
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
  ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
  [DllImport("kernel32.dll", ExactSpelling = true)]
  internal static extern IntPtr GetCurrentProcess();
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr
  phtok);
  [DllImport("advapi32.dll", SetLastError = true)]
  internal static extern bool LookupPrivilegeValue(string host, string name,
  ref long pluid);
  [StructLayout(LayoutKind.Sequential, Pack = 1)]
  internal struct TokPriv1Luid
  {
   public int Count;
   public long Luid;
   public int Attr;
  }
  internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
  internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
  internal const int TOKEN_QUERY = 0x00000008;
  internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
  public static bool AddPrivilege(string privilege)
  {
   try
   {
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_ENABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
  public static bool RemovePrivilege(string privilege)
  {
   try
   {
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_DISABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
 }
"@

#### Lets start to do some actual work - Don't edit below unless you want to unlease hell ####

# Check to see if the Powershell AD module is available otherwise connect to the DC 
if (Get-Module -ListAvailable -Name ActiveDirectory -ErrorAction silentlycontinue) {
    Write-Host -ForegroundColor Magenta "AD module available locally, no need to connect to a DC"
    Import-Module ActiveDirectory
  } #End the IF statement
  else {
          Write-Host -ForegroundColor Cyan "Creating a PS Session to a DC"
          $S = New-PSSession -ComputerName $DC
          Import-Module -PSsession $S -Name ActiveDirectory
  } #End the Else Statement

# Automatic Variable to get ad user list
$ADUsers = Get-ADUser -Searchbase $searchbase -Filter * | Select-Object samaccountname

# Performing loop
foreach ($Account in $ADUsers)
{
    $user = $account.samaccountname
    $principal = "$domain\$user"
    Write-Host -ForegroundColor Cyan "Testing Home dir path for $user account"
    $pathtest = Test-Path $HomeDirPath\$user
    if ($pathtest -eq $true)
    {
        # Path is true, defining the right ACL to the right folder
        $path = "$HomeDirPath\$user"
        Write-Host -ForegroundColor Green "Ok, path exists on $pathtest for $user"
        $rule = new-object System.Security.AccessControl.FileSystemAccessRule($Principal, $Right, "ContainerInherit,ObjectInherit", "none", "Allow")
        $ACL = Get-Acl $path
        $ACL.setaccessrule($rule)
        Set-Acl $path $ACL
        Write-Host -ForegroundColor Green "Succesfully set permissions for $user"
        # Try and set the user as the owner of the Folder

        Add-Type $AdjustTokenPrivileges
        $Folder = Get-Item $Path
        [void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
        [void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
        [void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
        $NewOwnerACL = New-Object System.Security.AccessControl.DirectorySecurity
        $NewOwner = New-Object System.Security.Principal.NTAccount($domain, $user)
        $NewOwnerACL.SetOwner($NewOwner)
        $Folder.SetAccessControl($NewOwnerACL)
        Write-Host -ForegroundColor Green "Succesfully set the owner for $Path to $user"
    } #End the If Statement
    Else
    {
        # Path is false, logging to the log file
        Write-Host -ForegroundColor Cyan "Path for $user does not exist on destination path"
        Write-Output "$pathtest does not exist for $user" >> $logpath
        $path = "$HomeDirPath\$user"
        New-Item -Path "$path" -ItemType directory
        Write-Host -ForegroundColor Green "Created root user directory for $user in $HomeDirPath"

        # Create Desktop path if it doesn't already exist
        If(!(Test-Path -path "$path\Desktop")) 
        {
            New-Item -Path "$path\Desktop" -ItemType directory
            
            #Set the Owner for Desktop
            Add-Type $AdjustTokenPrivileges
            $Folder = Get-Item "$path\Desktop"
            [void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
            [void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
            [void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
            $NewOwnerACL = New-Object System.Security.AccessControl.DirectorySecurity
            $NewOwner = New-Object System.Security.Principal.NTAccount($domain, $user)
            $NewOwnerACL.SetOwner($NewOwner)
            $Folder.SetAccessControl($NewOwnerACL) 
        } #End the If Statement

        # Create Documents path if it doesn't already exist
        If(!(Test-Path -path "$path\Documents")) 
        {
            New-Item -Path "$path\Documents" -ItemType directory

            #Set the Owner for Documents
            Add-Type $AdjustTokenPrivileges
            $Folder = Get-Item "$Path\Documents"
            [void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
            [void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
            [void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
            $NewOwnerACL = New-Object System.Security.AccessControl.DirectorySecurity
            $NewOwner = New-Object System.Security.Principal.NTAccount($domain, $user)
            $NewOwnerACL.SetOwner($NewOwner)
            $Folder.SetAccessControl($NewOwnerACL) 
        } #End the If Statement

        # Create Favorites path if it doesn't already exist
        If(!(Test-Path -Path "$path\Favorites")) 
        {
            New-Item -Path "$path\Favorites" -ItemType directory
            
            #Set the Owner for Favorites
            Add-Type $AdjustTokenPrivileges
            $Folder = Get-Item "$Path\Favorites"
            [void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
            [void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
            [void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
            $NewOwnerACL = New-Object System.Security.AccessControl.DirectorySecurity
            $NewOwner = New-Object System.Security.Principal.NTAccount($domain, $user)
            $NewOwnerACL.SetOwner($NewOwner)
            $Folder.SetAccessControl($NewOwnerACL) 
        } #End the Else Statement

        # Path is true, defining the right ACL to the right folder
        $path = "$HomeDirPath\$user"
        Write-Host -ForegroundColor Green "Ok, path exists on $path for $user"
        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Principal, $Right, "ContainerInherit,ObjectInherit", "none", "Allow")
        $ACL = Get-Acl $path
        $ACL.SetAccessRule($rule)
        Set-Acl $path $ACL
        Write-Host -ForegroundColor Green "Succesfully set permissions for $user"
        # Try and set the user as the owner of the Folder

        Add-Type $AdjustTokenPrivileges
        $Folder = Get-Item $Path
        [void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
        [void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
        [void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
        $NewOwnerACL = New-Object System.Security.AccessControl.DirectorySecurity
        $NewOwner = New-Object System.Security.Principal.NTAccount($domain, $user)
        $NewOwnerACL.SetOwner($NewOwner)
        $Folder.SetAccessControl($NewOwnerACL)
    } #End the Else Statement
    Write-Host -ForegroundColor Magenta "The script had a problem as $user didn't have a folder, but we've created it now and set the correct permissions."         
} #End the Loop

#####################################
###   Stop PS Session to the DC   ###
#####################################

Remove-PSSession -ComputerName $DC -ErrorAction SilentlyContinue

#####################################
###        Clear Variables        ###
#####################################

Remove-Variable -Name * -ErrorAction SilentlyContinue

#####################################
###      Post Completion Msg      ###
#####################################
Write-Host -ForegroundColor White -BackgroundColor DarkGreen  "***************************************************************************************************************" 
Write-Host -ForegroundColor White -BackgroundColor DarkGreen  "       Script has now completed, please check all Folders and permissions have been created as expected!       "
Write-Host -ForegroundColor White -BackgroundColor DarkGreen  "***************************************************************************************************************"
[Console]::ResetColor()

 

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 account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...