Tuesday, August 4, 2015

Creating file directories based on AD OrganisationalUnits names

This script creates data folders based on OU/Group names and adding user rights for correct groups.

Customer had a linux based file server on a MS Remote Desktop environment. They replaced it with Windows server, but they wanted to have the Windows server to act just like the old linux server. RD farm is locked down, and users cannot browse network or map drives on their own.  I have few other post how to map drives with login script with powershell. To make things a bit more tricky, they are using project-001 syntax on group and OU names, but 001 on folder names.


#Set Variables
$ou = "Users"
$project = "project*"
$HomePath = "C:\temp\test"
$temppath = "c:\temp"
$groupprefix = "project-"

#Get domain name
get-addomain | select distinguishedname -OutVariable Domainname

#Filter unneeded information from variable
foreach ($DN in $Domainname)
{

$domain = $Domainname.distinguishedname
}

# Create searchpath combining OU and domain name in correct format
$Oupathe="OU=$OU,$Domain"

#Set-Location to $TempPath
Set-Location $temppath 

# Get OU names to CSV file
Get-ADOrganizationalUnit -filter * -SearchBase:"$oupath" | Select-Object -Property Name | Where {$_.name -Match $project} | export-csv $temppath\projectfolder.csv

#Remove Project from OU names in CSV file
[io.file]::readalltext("$temppath\projectfolder.csv").replace("project-","") | Out-File $temppath\projectfolders.csv -Encoding ascii –Force

#Set Location to $HomePath
Set-Location $HomePath 

#Import folder list to $folders variable
$Folders = Import-Csv $temppath\projectfolders.csv

#Create folders
ForEach ($Folder in $Folders) { 
New-Item $Folder.Name -type directory 


#Set Access Permissions
ForEach ($Folder in $Folders) {
 $i=$Folder.Name 
 $GroupName = "$groupprefix$i"

$ACL = Get-Acl "$HomePath\$i"
$ACL.SetAccessRuleProtection($true, $false)
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("$NTDomain\Domain Admins","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$NTDOMAIN\$GroupName","Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl "$HomePath\$i" $ACL
}
Set-Location $temppath 

#delete temp files
remove-item -path $temppath\projectfolder.csv
remove-item -path $temppath\projectfolders.csv 

#Clear variables
$ACL =""
$folders =""
$folder =""
$GroupName =""
$i =""
$rule =""
$NTDomain = ""
$oupath = ""
$project = ""
$HomePath = ""
$temppath = ""
$groupprefix = ""

No comments:

Post a Comment