Permissions

When you work with files or folders you need to be able to grant or deny persons to read or edit the files or folders.
When you make e.g. a homefolder you want administrators and the user to be able to modify their content and administrators to be able to troubleshoot.
You can set permissions by the GUI but it is more prone to errors. When you use a script it will always make the user and e.g homedrive with the same layout and concistency.
I searched the Internet and found some usefull pieces to make a user and to create it's homedrive and profile. I adjusted the script to suit my needs.
Feel free to use it and adjust it but I need to say many thanks to the original maker of this script.

##################################################################################
#
#
#  Script name: SetHomeFolder.ps1
#  Author:      Aaron and John and modified by HS (c) 2010
#
#
##################################################################################

param ([string]$User, [switch]$help)

function GetHelp()
{
$HelpText = @"

DESCRIPTION:
NAME: SetHomeFolder.ps1
Creates folder and sets permissions for the specified user.
Creates folder if it does not exist. Removes "Administrators" default permission.

PARAMETERS:
-User            User to create folder for and who should have access (Required)
-help            Prints the HelpFile (Optional)

SYNTAX:
./SetHomeFolder.ps1 -User Domain\UserName

Creates \\[server]\Users\[UserName] and sets new permissions for that folder.

"@
$HelpText

[system.enum]::getnames([System.Security.AccessControl.FileSystemRights])
}

function CreateFolder ([string]$Path)
{
#check if the folder Exists
Write-Host "$Path..." -Foregroundcolor Green

if (Test-Path $Path) {
Write-Host "...Already Exists" -ForeGroundColor Yellow
} else {
Write-Host "...Created"
New-Item -Path $Path -type directory | Out-Null
}
}
function SetAcl ([string]$Path, [string]$User, [string]$Permission)
{
#this trap prevents ugly errors on the screen when attempting to update the ACL for the user.
trap [Exception]
{
write-host "  ERROR: $($_.Exception.Message)" -ForeGroundColor Magenta
continue
}

Write-Host "Setting Permissions..." -ForeGroundColor Green

#get ACL on folder and assign as object
$GetACL = Get-Acl $Path
$isProtected = $true
$preserveInheritance = $true
$GetAcl.SetAccessRuleProtection($isProtected, $preserveInheritance)
# Apply the inheritance change
Set-ACL $path $GetAcl
# Get the updated ACL
$GetAcl = Get-ACL $Path

$GetAcl.Access | ?{ $_.IdentityReference -Like "DOMAIN\*" } |%{
  $GetAcl.RemoveAccessRuleSpecific($_)
}

Set-ACL $Path $GetAcl

#set up the access rules
$Allinherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$Allpropagation = [system.security.accesscontrol.PropagationFlags]"None"
$AccessRule = New-Object system.security.AccessControl.FileSystemAccessRule($User, $Permission, $AllInherit, $Allpropagation, "Allow")
$SystemAccessRule = New-Object system.security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl", $AllInherit, $Allpropagation, "Allow")
$AdminAccessRule = New-Object system.security.AccessControl.FileSystemAccessRule("Domain Users", "ReadAndExecute", $AllInherit, $Allpropagation, "Allow")

#check if Access for Domain Users already exists - and REMOVE
Write-Host "...Removing Permission For: Domain Users" -ForeGroundColor DarkGray
$GetACL.RemoveAccessRuleAll($AdminAccessRule) | Out-Null
#end of Domain Users permissions

#check if Access for User Already Exists - and ADD
if ($GetACL.Access | Where { $_.IdentityReference -eq $User}) {
Write-Host "...Modifying Permissions For: $User" -ForeGroundColor Yellow

$AccessModification = New-Object system.security.AccessControl.AccessControlModification
$AccessModification.value__ = 2
$Modification = $False
#modify the ACL rule
$GetACL.ModifyAccessRule($AccessModification, $AccessRule, [ref]$Modification) | Out-Null
} else {
Write-Host "...Adding Permission: $Permission For: $User"
# add the ACL rule
$GetACL.AddAccessRule($AccessRule)
}
#end of User permissions

#check if Access for SYSTEM already exists - and ADD
if ($GetACL.Access | Where { $_.IdentityReference -eq "SYSTEM"}) {
Write-Host "...Modifying Permissions For: SYSTEM" -ForeGroundColor Yellow

$SystemAccessModification = New-Object system.security.AccessControl.AccessControlModification
$SystemAccessModification.value__ = 2
$SystemModification = $False
# modify the ACL rule
$GetACL.ModifyAccessRule($SystemAccessModification, $SystemAccessRule, [ref]$SystemModification) | Out-Null
} else {
Write-Host "...Adding Permission: FullControl For: SYSTEM"
#add the ACL rule
$GetACL.AddAccessRule($SystemAccessRule)
}
#end of SYSTEM permissions

#set the owner of the folder to the specified user
$GetACL.SetOwner((new-object System.Security.Principal.NTAccount("$User")))

#this command performs the actual update using the objects as defined above
Set-Acl -aclobject $GetACL -Path $Path
}

function Get-ADUser( [string]$samid=$env:username)
{
#find the user object in active directory and returns the user object to the calling line
$searcher=New-Object DirectoryServices.DirectorySearcher
$searcher.Filter="(&(objectcategory=person)(objectclass=user)(sAMAccountname=$samid))"
$aduser=$searcher.FindOne()

if ($aduser -ne $null )
{
$aduser.getdirectoryentry()
}
}

if ($help)
{
#the user requested help, so let us display that help.
GetHelp
}

#set some global variables per our environment.
$Permission = "Modify"
$username = $User.substring($User.indexof("\") + 1)
$Path = "\\servername\Homedrives\$username"

#LET'S BEGIN (sub Main()) - Process folder creation and security changes
if ($Path -AND $User -AND $Permission)
{
#1. create the folder
CreateFolder $Path

#2. set the ACL permissions and ownership for that folder
SetAcl $Path $User $Permission

#3. update active directory with the new path location
Write-Host "Updating Active Directory Home Folder..."
$aduser = Get-ADUser $username
$aduser.homeDirectory = "$Path"
$aduser.homeDrive = "P:"
$aduser.SetInfo()
Write-Host "...$username Updated with: $Path" -ForeGroundColor Green
}

I also found this tip to find the NTFS permissions for a folder:
Get-Acl -Path $env:windir | Select-Object -ExpandProperty Access

I made a little script that was of use when some child folders had inherited the group domain\domain users with read rights and the parent folder did not have these setting anymore. So there was done inheritance half of the folders and half not. This script will remove inheritance and then remove that group and set some other rights.

$rootfolder = Get-ChildItem -Path \\fileserver1\pst$
foreach ($userfolder in $rootfolder) {
        $userfolder.FullName
        If (get-qaduser "Domain\$userfolder") {
            Disable-Inheritance -path $userfolder.FullName 
        Get-ace -path $userfolder.FullName | remove-ace -path $userfolder.Fullname -account 'Domain\domain users' -AccessRights ReadAndExecute, Synchronize
        Get-Acl $userfolder.FullName | Format-List
            $acl = Get-Acl $userfolder.FullName
            $IsProtected = $false
        $PreserveInheritance = $false # this means that inheritance will be passed on to folders
            $ACL.SetAccessRuleProtection($IsProtected,$PreserveInheritance)
           $colRights = [System.Security.AccessControl.FileSystemRights]"Read, Write" 

        $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None 
        $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None 

        $objType =[System.Security.AccessControl.AccessControlType]::Allow 

        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
            $acl.AddAccessRule($rule)
            $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userfolder.Name,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
            $acl.AddAccessRule($rule)
            $acct=New-Object System.Security.Principal.NTAccount("Administrators")
            $acl.SetOwner($acct)
            Set-Acl $userfolder.FullName $acl
            Get-Acl $userfolder.FullName  | Format-List
        Enable-Inheritance -path $userfolder.FullName

        }
    elseif (get-qaduser "OtherDomain\$userfolder" -service OtherDomain) {
        Disable-Inheritance -path $userfolder.FullName 
        Get-ace -path $userfolder.FullName | remove-ace -path $userfolder.Fullname -account 'OtherDomain\domain users' -AccessRights ReadAndExecute, Synchronize
        Enable-Inheritance -path $userfolder.FullName
        Get-Acl $userfolder.FullName | Format-List
            $acl = Get-Acl $userfolder.FullName
            $IsProtected = $false
        $PreserveInheritance = $false  # this means that inheritance will be passed on to folders
            $colRights = [System.Security.AccessControl.FileSystemRights]"Read, Write" 

        $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None 
        $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None 

        $objType =[System.Security.AccessControl.AccessControlType]::Allow 

        $objUser = New-Object System.Security.Principal.NTAccount("OtherDomain\Domain Users") 

        $objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
            ($objUser, $colRights, $InheritanceFlag, $PropagationFlag, $objType) 

        $ACL.RemoveAccessRule($objACE) 

        #$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
            #$acl.AddAccessRule($rule)
            $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userfolder.Name,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
            $acl.AddAccessRule($rule)
            $acct=New-Object System.Security.Principal.NTAccount("Administrators")
            $acl.SetOwner($acct)
            Set-Acl $userfolder.FullName $acl
            Get-Acl $userfolder.FullName  | Format-List
    }
    else {$userfolder.fullname | out-file \\servername1\username$\downloads\scripts\Unresolvingnames.txt -append}

}

Another nice script which I found on StackOverflow at the link HERE
#Set variables
$path =  $args[0]
$filename = $args[1]
$date = Get-Date

#Place Headers on out-put file
$list = "Permissions for directories in: $Path"
$list | format-table | Out-File "C:\Powershell\Results\$filename"
$datelist = "Report Run Time: $date"
$datelist | format-table | Out-File -append "C:\Powershell\Results\$filename"
$spacelist = " "
$spacelist | format-table | Out-File -append "C:\Powershell\Results\$filename"

#Populate Folders Array
[Array] $folders = Get-ChildItem -path $path -force -recurse 

#Process data in array
ForEach ($folder in [Array] $folders)
{
#Convert Powershell Provider Folder Path to standard folder path
$PSPath = (Convert-Path $folder.pspath)
$list = ("Path: $PSPath")
$list | format-table | Out-File -append "C:\Powershell\Results\$filename"

Get-Acl -path $PSPath | Format-List -property AccessToString | Out-File -append "C:\Powershell\Results\$filename"

"-----------------------" | Out-File -FilePath "C:\Powershell\Results\$filename" -Append

} #end ForEach

On Me
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License