Update-HTPersonalShares.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function Update-HTPersonalShares {
    [CmdletBinding()]
    param (
        # Base Share Path Default is 'I:\Personal'
        [Parameter(Position=1)]
        [string]
        $PersonalPath =  'I:\Personal'
    )
    
    process {
        $UsersFull = Get-ADUser -Filter {Enabled -eq $true} | Where-Object {$_.DistinguishedName -notlike '*service*'}  | Select-Object samAccountName

        foreach ($u in $UsersFull)
        {

            $userDir = Join-Path $PersonalPath $u.samAccountName

            if(Test-Path $userDir)
            {
                continue
            }
            Write-Verbose "$userDir no found creating new directory.."
            $UserDirectory = New-Item $userDir -ItemType Directory        
            $acl = Get-Acl $UserDirectory
            $admingroup = New-Object System.Security.Principal.NTAccount("MCT", "FileServerAdmins")
            $userIdentity = New-Object System.Security.Principal.NTAccount("MCT", $u.samAccountName)

            $acl.SetOwner($admingroup)
            $acl.SetAccessRuleProtection($true,$true) ##Disable inheritence and keep rules..

            Set-Acl -Path $UserDirectory -AclObject $acl

            $acl = Get-Acl $UserDirectory

            foreach($rule in $acl.Access)
            {
                if($rule.IdentityReference.Value -eq 'MCT\Domain Users')
                {
                    $acl.RemoveAccessRule($rule) | Out-Null
                }
            }

            $r = [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor `
                 [System.Security.AccessControl.FileSystemRights]::Write -bor `
                 [System.Security.AccessControl.FileSystemRights]::ReadAndExecute -bor `
                 [System.Security.AccessControl.FileSystemRights]::Synchronize

            $inhtflag = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor  [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
            $propflag = [System.Security.AccessControl.PropagationFlags]::None
            $acltyp = [System.Security.AccessControl.AccessControlType]::Allow

            $userRule = New-Object  system.security.accesscontrol.filesystemaccessrule($userIdentity,$r,$inhtflag,$propflag,$acltyp)

            $acl.AddAccessRule($userRule)

            Set-Acl -Path $UserDirectory -AclObject $acl

        }
    }
}