Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # FixUserShellFolderPermissions.ps1 - 230119.3
- #
- # Microsoft Customer Support and Services Helper Script
- # Checks 'User Shell Folders' registry ACLs and fixes it by restoring inheritance, then registers app packages
- # Except with -allprofiles, this tool needs to be run from the affected user context thus non-elevated
- #
- # Usage:
- # - Fix (if needed) your current user profile:
- # .\FixUserShellFolderPermissions.ps1
- # - Force the registration main Shell packages:
- # .\FixUserShellFolderPermissions.ps1 -register
- # - Force the registration of every packages (might take long time):
- # .\FixUserShellFolderPermissions.ps1 -force
- # - [Run As Admin] Attempt to recover every profiles, but won't register packages
- # .\FixUserShellFolderPermissions.ps1 -allprofiles
- # - To accept the EULA and run the tool silently:
- # .\FixUserShellFolderPermissions.ps1 -accepteula
- #
- # This script is provided AS IS, no support nor warranty of any kind is provided for its usage.
- #
- param (
- [switch]$register = $false,
- [switch]$force = $false,
- [switch]$allprofiles = $false,
- [switch]$accepteula = $false
- )
- [void][System.Reflection.Assembly]::Load('System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
- [void][System.Reflection.Assembly]::Load('System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
- # Taken from https://www.leeholmes.com/adjusting-token-privileges-in-powershell/ with minor adjusment (use GetCurrentProcess())
- $definition = @'
- using System;
- using System.Runtime.InteropServices;
- public class AdjPriv
- {
- [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")]
- public 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_ENABLED = 0x00000002;
- internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
- internal const int TOKEN_QUERY = 0x00000008;
- internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
- public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
- {
- bool retVal;
- TokPriv1Luid tp;
- IntPtr htok = IntPtr.Zero;
- IntPtr hproc = GetCurrentProcess();
- retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
- tp.Count = 1;
- tp.Luid = 0;
- if(disable)
- {
- tp.Attr = SE_PRIVILEGE_DISABLED;
- }
- else
- {
- 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;
- }
- }
- '@
- function ShowEULAPopup($mode)
- {
- $EULA = New-Object -TypeName System.Windows.Forms.Form
- $richTextBox1 = New-Object System.Windows.Forms.RichTextBox
- $btnAcknowledge = New-Object System.Windows.Forms.Button
- $btnCancel = New-Object System.Windows.Forms.Button
- $EULA.SuspendLayout()
- $EULA.Name = "EULA"
- $EULA.Text = "Microsoft Diagnostic Tools End User License Agreement"
- $richTextBox1.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
- $richTextBox1.Location = New-Object System.Drawing.Point(12,12)
- $richTextBox1.Name = "richTextBox1"
- $richTextBox1.ScrollBars = [System.Windows.Forms.RichTextBoxScrollBars]::Vertical
- $richTextBox1.Size = New-Object System.Drawing.Size(776, 397)
- $richTextBox1.TabIndex = 0
- $richTextBox1.ReadOnly=$True
- $richTextBox1.Add_LinkClicked({Start-Process -FilePath $_.LinkText})
- $richTextBox1.Rtf = @"
- {\rtf1\ansi\ansicpg1252\deff0\nouicompat{\fonttbl{\f0\fswiss\fprq2\fcharset0 Segoe UI;}{\f1\fnil\fcharset0 Calibri;}{\f2\fnil\fcharset0 Microsoft Sans Serif;}}
- {\colortbl ;\red0\green0\blue255;}
- {\*\generator Riched20 10.0.19041}{\*\mmathPr\mdispDef1\mwrapIndent1440 }\viewkind4\uc1
- \pard\widctlpar\f0\fs19\lang1033 MICROSOFT SOFTWARE LICENSE TERMS\par
- Microsoft Diagnostic Scripts and Utilities\par
- \par
- {\pict{\*\picprop}\wmetafile8\picw26\pich26\picwgoal32000\pichgoal15
- 0100090000035000000000002700000000000400000003010800050000000b0200000000050000
- 000c0202000200030000001e000400000007010400040000000701040027000000410b2000cc00
- 010001000000000001000100000000002800000001000000010000000100010000000000000000
- 000000000000000000000000000000000000000000ffffff00000000ff040000002701ffff0300
- 00000000
- }These license terms are an agreement between you and Microsoft Corporation (or one of its affiliates). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS.\par
- {\pict{\*\picprop}\wmetafile8\picw26\pich26\picwgoal32000\pichgoal15
- 0100090000035000000000002700000000000400000003010800050000000b0200000000050000
- 000c0202000200030000001e000400000007010400040000000701040027000000410b2000cc00
- 010001000000000001000100000000002800000001000000010000000100010000000000000000
- 000000000000000000000000000000000000000000ffffff00000000ff040000002701ffff0300
- 00000000
- }\par
- \pard
- {\pntext\f0 1.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pndec{\pntxta.}}
- \fi-360\li360 INSTALLATION AND USE RIGHTS. Subject to the terms and restrictions set forth in this license, Microsoft Corporation (\ldblquote Microsoft\rdblquote ) grants you (\ldblquote Customer\rdblquote or \ldblquote you\rdblquote ) a non-exclusive, non-assignable, fully paid-up license to use and reproduce the script or utility provided under this license (the "Software"), solely for Customer\rquote s internal business purposes, to help Microsoft troubleshoot issues with one or more Microsoft products, provided that such license to the Software does not include any rights to other Microsoft technologies (such as products or services). \ldblquote Use\rdblquote means to copy, install, execute, access, display, run or otherwise interact with the Software. \par
- \pard\widctlpar\par
- \pard\widctlpar\li360 You may not sublicense the Software or any use of it through distribution, network access, or otherwise. Microsoft reserves all other rights not expressly granted herein, whether by implication, estoppel or otherwise. You may not reverse engineer, decompile or disassemble the Software, or otherwise attempt to derive the source code for the Software, except and to the extent required by third party licensing terms governing use of certain open source components that may be included in the Software, or remove, minimize, block, or modify any notices of Microsoft or its suppliers in the Software. Neither you nor your representatives may use the Software provided hereunder: (i) in a way prohibited by law, regulation, governmental order or decree; (ii) to violate the rights of others; (iii) to try to gain unauthorized access to or disrupt any service, device, data, account or network; (iv) to distribute spam or malware; (v) in a way that could harm Microsoft\rquote s IT systems or impair anyone else\rquote s use of them; (vi) in any application or situation where use of the Software could lead to the death or serious bodily injury of any person, or to physical or environmental damage; or (vii) to assist, encourage or enable anyone to do any of the above.\par
- \par
- \pard\widctlpar\fi-360\li360 2.\tab DATA. Customer owns all rights to data that it may elect to share with Microsoft through using the Software. You can learn more about data collection and use in the help documentation and the privacy statement at {{\field{\*\fldinst{HYPERLINK https://aka.ms/privacy }}{\fldrslt{https://aka.ms/privacy\ul0\cf0}}}}\f0\fs19 . Your use of the Software operates as your consent to these practices.\par
- \pard\widctlpar\par
- \pard\widctlpar\fi-360\li360 3.\tab FEEDBACK. If you give feedback about the Software to Microsoft, you grant to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose.\~ You will not provide any feedback that is subject to a license that would require Microsoft to license its software or documentation to third parties due to Microsoft including your feedback in such software or documentation. \par
- \pard\widctlpar\par
- \pard\widctlpar\fi-360\li360 4.\tab EXPORT RESTRICTIONS. Customer must comply with all domestic and international export laws and regulations that apply to the Software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit {{\field{\*\fldinst{HYPERLINK https://aka.ms/exporting }}{\fldrslt{https://aka.ms/exporting\ul0\cf0}}}}\f0\fs19 .\par
- \pard\widctlpar\par
- \pard\widctlpar\fi-360\li360\qj 5.\tab REPRESENTATIONS AND WARRANTIES. Customer will comply with all applicable laws under this agreement, including in the delivery and use of all data. Customer or a designee agreeing to these terms on behalf of an entity represents and warrants that it (i) has the full power and authority to enter into and perform its obligations under this agreement, (ii) has full power and authority to bind its affiliates or organization to the terms of this agreement, and (iii) will secure the permission of the other party prior to providing any source code in a manner that would subject the other party\rquote s intellectual property to any other license terms or require the other party to distribute source code to any of its technologies.\par
- \pard\widctlpar\par
- \pard\widctlpar\fi-360\li360\qj 6.\tab DISCLAIMER OF WARRANTY. THE SOFTWARE IS PROVIDED \ldblquote AS IS,\rdblquote WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL MICROSOFT OR ITS LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par
- \pard\widctlpar\qj\par
- \pard\widctlpar\fi-360\li360\qj 7.\tab LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT, OR INCIDENTAL DAMAGES. This limitation applies to (i) anything related to the Software, services, content (including code) on third party Internet sites, or third party applications; and (ii) claims for breach of contract, warranty, guarantee, or condition; strict liability, negligence, or other tort; or any other claim; in each case to the extent permitted by applicable law. It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your state, province, or country may not allow the exclusion or limitation of incidental, consequential, or other damages.\par
- \pard\widctlpar\par
- \pard\widctlpar\fi-360\li360 8.\tab BINDING ARBITRATION AND CLASS ACTION WAIVER. This section applies if you live in (or, if a business, your principal place of business is in) the United States. If you and Microsoft have a dispute, you and Microsoft agree to try for 60 days to resolve it informally. If you and Microsoft can\rquote t, you and Microsoft agree to binding individual arbitration before the American Arbitration Association under the Federal Arbitration Act (\ldblquote FAA\rdblquote ), and not to sue in court in front of a judge or jury. Instead, a neutral arbitrator will decide. Class action lawsuits, class-wide arbitrations, private attorney-general actions, and any other proceeding where someone acts in a representative capacity are not allowed; nor is combining individual proceedings without the consent of all parties. The complete Arbitration Agreement contains more terms and is at {{\field{\*\fldinst{HYPERLINK https://aka.ms/arb-agreement-4 }}{\fldrslt{https://aka.ms/arb-agreement-4\ul0\cf0}}}}\f0\fs19 . You and Microsoft agree to these terms. \par
- \pard\widctlpar\par
- \pard\widctlpar\fi-360\li360 9.\tab LAW AND VENUE. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court (excluding arbitration). If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court (excluding arbitration).\par
- \pard\widctlpar\par
- \pard\widctlpar\fi-360\li360 10.\tab ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software.\par
- \pard\sa200\sl276\slmult1\f1\fs22\lang9\par
- \pard\f2\fs17\lang2057\par
- }
- "@
- $richTextBox1.BackColor = [System.Drawing.Color]::White
- $btnAcknowledge.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right
- $btnAcknowledge.Location = New-Object System.Drawing.Point(544, 415)
- $btnAcknowledge.Name = "btnAcknowledge";
- $btnAcknowledge.Size = New-Object System.Drawing.Size(119, 23)
- $btnAcknowledge.TabIndex = 1
- $btnAcknowledge.Text = "Accept"
- $btnAcknowledge.UseVisualStyleBackColor = $True
- $btnAcknowledge.Add_Click({$EULA.DialogResult=[System.Windows.Forms.DialogResult]::Yes})
- $btnCancel.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right
- $btnCancel.Location = New-Object System.Drawing.Point(669, 415)
- $btnCancel.Name = "btnCancel"
- $btnCancel.Size = New-Object System.Drawing.Size(119, 23)
- $btnCancel.TabIndex = 2
- if($mode -ne 0)
- {
- $btnCancel.Text = "Close"
- }
- else
- {
- $btnCancel.Text = "Decline"
- }
- $btnCancel.UseVisualStyleBackColor = $True
- $btnCancel.Add_Click({$EULA.DialogResult=[System.Windows.Forms.DialogResult]::No})
- $EULA.AutoScaleDimensions = New-Object System.Drawing.SizeF(6.0, 13.0)
- $EULA.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Font
- $EULA.ClientSize = New-Object System.Drawing.Size(800, 450)
- $EULA.Controls.Add($btnCancel)
- $EULA.Controls.Add($richTextBox1)
- if($mode -ne 0)
- {
- $EULA.AcceptButton=$btnCancel
- }
- else
- {
- $EULA.Controls.Add($btnAcknowledge)
- $EULA.AcceptButton=$btnAcknowledge
- $EULA.CancelButton=$btnCancel
- }
- $EULA.ResumeLayout($false)
- $EULA.Size = New-Object System.Drawing.Size(800, 650)
- Return ($EULA.ShowDialog())
- }
- function ShowEULAIfNeeded($toolName, $mode)
- {
- $eulaRegPath = "HKCU:Software\Microsoft\CESDiagnosticTools"
- $eulaAccepted = "No"
- $eulaValue = $toolName + " EULA Accepted"
- if(Test-Path $eulaRegPath)
- {
- $eulaRegKey = Get-Item $eulaRegPath
- $eulaAccepted = $eulaRegKey.GetValue($eulaValue, "No")
- }
- else
- {
- $eulaRegKey = New-Item $eulaRegPath
- }
- if($mode -eq 2) # silent accept
- {
- $eulaAccepted = "Yes"
- $ignore = New-ItemProperty -Path $eulaRegPath -Name $eulaValue -Value $eulaAccepted -PropertyType String -Force
- }
- else
- {
- if($eulaAccepted -eq "No")
- {
- $eulaAccepted = ShowEULAPopup($mode)
- if($eulaAccepted -eq [System.Windows.Forms.DialogResult]::Yes)
- {
- $eulaAccepted = "Yes"
- $ignore = New-ItemProperty -Path $eulaRegPath -Name $eulaValue -Value $eulaAccepted -PropertyType String -Force
- }
- }
- }
- return $eulaAccepted
- }
- if ($accepteula) {
- $eulaAccepted = ShowEULAIfNeeded "FixUserShellFolderPermissions" 2
- } else {
- $eulaAccepted = ShowEULAIfNeeded "FixUserShellFolderPermissions" 0
- }
- Write-Host ""
- if($eulaAccepted -ne "Yes")
- {
- Write-Host "You must accept the End-User License Agreement (EULA) to run this Microsoft Diagnostic Tool!"
- exit
- }
- Write-Host "Thanks for accepting the End-User License Agreement (EULA) of this Microsoft Diagnostic Tool!"
- Write-Host ""
- $AAP_SID = 'S-1-15-2-1'
- $ADMINS_SID = 'S-1-5-32-544'
- $SYSTEM_SID = 'S-1-5-18'
- $USERS_SHELL_FOLDERS = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
- $PROFILE_LIST = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
- $EXCLUDED_PROFILES = "*S-1-5-18*","*S-1-5-19*","*S-1-5-20*"
- Write-Host "Usage:"
- Write-Host "------"
- Write-Host " - Fix (if needed) your current user profile:"
- Write-Host " .\FixUserShellFolderPermissions.ps1"
- Write-Host " - Force the registration main Shell packages:"
- Write-Host " .\FixUserShellFolderPermissions.ps1 -register"
- Write-Host " - Force the registration of every packages (might take long time):"
- Write-Host " .\FixUserShellFolderPermissions.ps1 -force"
- Write-Host " - [Run As Admin] Attempt to recover every profiles, but won't register packages"
- Write-Host " .\FixUserShellFolderPermissions.ps1 -allprofiles"
- Write-Host " - To accept the EULA and run the tool silently."
- Write-Host " .\FixUserShellFolderPermissions.ps1 -accepteula"
- Write-Host ""
- Write-Host " ----------------"
- Write-Host ""
- Write-Host (get-date).ToString() - $MyInvocation.MyCommand.Name started on $env:ComputerName for user $env:UserName
- Write-Host "Command line used: " $MyInvocation.Line
- Write-Host ""
- if ($allprofiles) {
- # The -allprofiles switch needs to run under Admin or LocalSystem and will iterate on every profile to fix the permissions"
- # But this option can't register packages as it must done in the user context, so after a -register might be needed from non-elevated context"
- $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
- $isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
- $isSystem = ($currentPrincipal.Identities.User.Value) -eq $SYSTEM_SID
- if ($isAdmin -or $isSystem) {
- # Enabled privilege
- $processHandle = [System.Diagnostics.Process]::GetCurrentProcess().Handle
- $type = Add-Type $definition -PassThru
- if ($type -is [Array]) {
- $type[0]::EnablePrivilege($processHandle, "SeTakeOwnershipPrivilege", $false) | Out-Null
- }
- $profiles = (Get-ChildItem $PROFILE_LIST -Exclude $EXCLUDED_PROFILES | select -ExpandProperty Name)
- New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS | Out-Null
- Write-Host("Reviewing the registry permissions of $($profiles.Count) profiles:")
- Write-Host("")
- Foreach ($profile in $profiles) {
- $profile_sid = Split-Path -path $profile -Leaf
- $profile_usf = "HKU:\$profile_sid\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
- if (Test-Path($profile_usf))
- {
- $profile_name = Get-ItemPropertyValue -Path "HKU:\$profile_sid\Volatile Environment" -Name "USERNAME"
- Write-Host(" - HKU:\$profile_sid (name '$profile_name')")
- $acl_fixed = $false
- $dacl = $null
- $acl = (Get-Acl $profile_usf)
- if ($acl) {
- $dacl = $acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
- }
- # If we can't read even the ACL then we need to get the key ownership, then try again
- if (-not $dacl) {
- $key = [Microsoft.Win32.Registry]::Users.OpenSubKey($profile_usf.Replace("HKU:\", ""),[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::TakeOwnership)
- $acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
- $acl.SetOwner((New-Object System.Security.Principal.SecurityIdentifier($ADMINS_SID)))
- $key.SetAccessControl($acl)
- $acl_fixed = $true
- Write-Host(" - Fixed broken 'User Shell Folders' registry permissions")
- $acl = (Get-Acl $profile_usf)
- if ($acl) {
- $dacl = $acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
- }
- }
- # If we can't find any ACE for All Application Packages, then restore the ACL from parent
- if (-not ($dacl | where IdentityReference -eq $AAP_SID)) {
- # Restores ACL inheritance from parent
- $key = [Microsoft.Win32.Registry]::Users.OpenSubKey($profile_usf.Replace("HKU:\", ""),[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
- $acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::Access)
- $acl.SetAccessRuleProtection($false, $false)
- $key.SetAccessControl($acl)
- # Now clean up possible rules to only keep inherited ones and restore the owner to System
- $dacl = $acl.GetAccessRules($true,$false,[System.Security.Principal.SecurityIdentifier])
- $dacl | %{ $acl.RemoveAccessRule($_) } | Out-Null # Clearing the ACL to avoid duplicated ACEs
- $acl.SetOwner((New-Object System.Security.Principal.SecurityIdentifier($SYSTEM_SID)))
- $key.SetAccessControl($acl)
- $acl_fixed = $true
- Write-Host(" - Added missing 'All Application Packages' from 'User Shell Folders' registry permissions")
- Write-Host(" -> Note you may still need to run from this user session .\FixUserShellFolderPermissions.ps1 -register")
- }
- if (-not $acl_fixed) {
- Write-Host(" -> No changed was made, profil permissions are correct.")
- }
- } else {
- Write-Host(" - The profile hive for $profile_sid is not loaded in the registry.")
- Write-Host(" -> If it is an affected user, ask him to login or load manually its registry hive and re-run the script.")
- }
- Write-Host("")
- }
- } else {
- Write-Host("ERROR: You need to run from an elevated prompt as an Admin or LocalSystem to use the -allprofiles switch.")
- Write-Host("")
- }
- } else {
- if (Test-path $USERS_SHELL_FOLDERS)
- {
- $acl = (Get-Acl $USERS_SHELL_FOLDERS)
- if ($acl) {
- $dacl = $acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
- }
- }
- if (!$dacl) {
- Write-Host "ERROR: Failed to get the access rules from User Shell Folders key."
- Write-Host "Please rerun the script as admin from an elevated prompt, and use the special switch -allprofiles"
- } elseif ($dacl | where IdentityReference -eq $AAP_SID) {
- Write-Host "-> No need to fix User Shell Folders registry permission for the current user, they are correct."
- Write-Host ""
- } else
- {
- Write-Host "User Shell Folders registry permission are incorrect..."
- # Restores ACL inheritance from parent
- $dacl | %{ $acl.RemoveAccessRule($_) } | Out-Null # Clearing the ACL to avoid duplicated ACEs
- $acl.SetAccessRuleProtection($false, $false) # Enabling inheritance
- $acl | Set-Acl -Path $USERS_SHELL_FOLDERS # Now sets the repaired ACL
- Write-Host "==> Registry permission were fixed!"
- Write-Host ""
- $acl_fixed = $true
- }
- # The most critical shell SystemApps list contains important Shell packages which will always try to be re-registered
- $MOST_CRITICAL_SHELL_SYSTEMAPPS = @("ShellExperienceHost", "StartMenuExperienceHost", "AAD.BrokerPlugin", "Windows.Search", "Cortana", "Client.CBS")
- $APPX_ALL_USER_STORE = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore'
- if ($acl_fixed -or $register -or $force) {
- if ($force) {
- Write-Host "Note registering every package may take quite a long time!"
- Write-Host "Consider using -register only if a force registration of every package is not require"
- Write-Host ""
- Write-Host "Force registering EVERY app packages for the user..."
- } else {
- Write-Host "Re-registering required app packages for the user..."
- }
- # Getting a first list of registered frameworks for the user
- $packages = Get-AppxPackage -PackageType:Framework
- # Register frameworks (dependencies) if they are not registered, or if -force switch is used
- $deps = (Get-ChildItem "$APPX_ALL_USER_STORE\Applications\*\*", "$APPX_ALL_USER_STORE\InboxApplications\*\*" | Select-Object -Unique @{N='PackageFullName';E={$_.PSChildName}}, @{N='InstallLocation';E={($_ |Get-ItemProperty).Path -replace '%SYSTEMDRIVE%', $Env:SystemDrive}} )
- ForEach($dep in $deps) {
- if ($force -or (!($packages | where {$_.PackageFullName -eq $dep.PackageFullName}))) {
- if(Test-Path $dep.InstallLocation) {
- Write-Host "Registering Dependency: " $dep.PackageFullName
- Add-AppxPackage -DisableDevelopmentMode -ForceApplicationShutdown -Register -Path ($dep.InstallLocation) -ErrorAction SilentlyContinue
- }
- }
- }
- # Getting an updated list of packages, including bundle & every package type, now dependencies are registered
- $packages = Get-AppxPackage -PackageType:all
- # Always force re-registering most important SystemApps, or every SystemApp with -force switch
- $apps = (Get-ChildItem $($APPX_ALL_USER_STORE + "\InboxApplications") | Select-Object -Unique @{N='PackageFullName';E={$_.PSChildName}}, @{N='InstallLocation';E={($_ |Get-ItemProperty).Path -replace '%SYSTEMDRIVE%', $Env:SystemDrive}} )
- ForEach($app in $apps) {
- if ($force -or ($MOST_CRITICAL_SHELL_SYSTEMAPPS | % { if ($app.PackageFullName -match $_ ) { $True } })) {
- if(Test-Path $app.InstallLocation) {
- Write-Host "Registering SystemApps: " $app.PackageFullName
- Add-AppxPackage -DisableDevelopmentMode -ForceApplicationShutdown -Register -Path ($app.InstallLocation) -ErrorAction SilentlyContinue
- }
- }
- }
- # Registering WindowsApps if they are not registered for the user, or with -force switch
- $apps = (Get-ChildItem $($APPX_ALL_USER_STORE + "\Applications") | Select-Object -Unique @{N='PackageFullName';E={$_.PSChildName}}, @{N='InstallLocation';E={($_ |Get-ItemProperty).Path -replace '%SYSTEMDRIVE%', $Env:SystemDrive}} )
- ForEach($app in $apps) {
- if ($force -or (!($packages | where {$_.PackageFullName -eq $app.PackageFullName}))) {
- if(Test-Path $app.InstallLocation) {
- Write-Host "Registering WindowsApps: " $app.PackageFullName
- Add-AppxPackage -DisableDevelopmentMode -ForceApplicationShutdown -Register -Path ($app.InstallLocation) -ErrorAction SilentlyContinue
- }
- }
- }
- Write-Host ""
- Write-Host "-> Your profile should be fixed."
- } else {
- Write-Host "-> No packages will be registered as we haven't changed permissions, and -register or -force were not used"
- }
- }
- Write-Host ""
- Write-Host (get-date).ToString() - User Shell Folders script completed
- Write-Host ""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement