src/Public/Repair-ProfileFolderPermissions.ps1
|
<#
.SYNOPSIS Repairs permissions for a user's profile folder. .DESCRIPTION The Repair-ProfileFolderPermissions function is designed to set appropriate permissions for a specified user's profile folder. It ensures that the specified user has the necessary permissions to access and modify their profile folder. The function takes ownership of the folder and modifies its ACL (Access Control List) to grant the required permissions. .PARAMETER ProfilePath [Mandatory] The full path to the user's profile folder that needs permission repair. It can be a UNC path or local path. .PARAMETER Username [Mandatory] The username of the account for which the profile folder permissions are being repaired. .EXAMPLE Repair-ProfileFolderPermissions -ProfilePath "C:\Users\JohnDoe\Profile" -Username "JohnDoe" This example repairs the permissions for the profile folder of the user "JohnDoe" located at "C:\Profile$\JohnDoe". .NOTES It's recommended to run this function with administrative privileges to ensure it can successfully take ownership and modify permissions of the profile folder. #> Function Repair-ProfileFolderPermissions { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [String] $Username ) Begin { Write-Verbose "Setting permissions for $ProfilePath for $Username" -ForegroundColor DarkYellow } Process { try { if (Test-Path $ProfilePath) { #Take Ownership of the folder $ACL = Get-Acl -Path $ProfilePath $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $NewOwner = New-Object System.Security.Principal.NTAccount($currentUser) $ACL.SetOwner($NewOwner) $ACL.SetAccessRuleProtection($false, $false) Try { Write-Verbose "Setting owner of $ProfilePath to $NewOwner" Set-ACL -Path $ProfilePath -AclObject $ACL -ErrorAction Stop } catch { Write-Error "Owner not set" Write-Error "$_" } $ACL = Get-Acl -Path $ProfilePath #Refetch ACLs after setting owner $accessRules = @( @{Identity = $Username; Permission = "FullControl" }, @{Identity = "SYSTEM"; Permission = "FullControl" }, @{Identity = "Administrators"; Permission = "FullControl" }, @{Identity = "Administrator"; Permission = "FullControl" } ) foreach ($rule in $accessRules) { Write-Verbose " Adding profile access rule - $($rule.Identity) - $($rule.Permission)" -ForegroundColor Yellow $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $rule.Identity, $rule.Permission, "ContainerInherit,ObjectInherit", "None", "Allow" ) $ACL.AddAccessRule($accessRule) } try { Write-Verbose "Applying ACL to $ProfilePath" Set-Acl -Path $ProfilePath -AclObject $ACL } catch { Write-Error "Failed to set ACL on ${ProfilePath}" Write-Error "$_" } } else { Write-Error "Profile path $ProfilePath does not exist" } } catch { Write-Error "An error occurred: $_" } } End { } } |