Advertisement
Guest User

FixUserShellFolderPermissions.ps1

a guest
Jan 30th, 2025
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.27 KB | None | 0 0
  1. #
  2. # FixUserShellFolderPermissions.ps1 - 230119.3
  3. #
  4. # Microsoft Customer Support and Services Helper Script
  5. # Checks 'User Shell Folders' registry ACLs and fixes it by restoring inheritance, then registers app packages
  6. # Except with -allprofiles, this tool needs to be run from the affected user context thus non-elevated
  7. #
  8. # Usage:
  9. # - Fix (if needed) your current user profile:
  10. # .\FixUserShellFolderPermissions.ps1
  11. # - Force the registration main Shell packages:
  12. # .\FixUserShellFolderPermissions.ps1 -register
  13. # - Force the registration of every packages (might take long time):
  14. # .\FixUserShellFolderPermissions.ps1 -force
  15. # - [Run As Admin] Attempt to recover every profiles, but won't register packages
  16. # .\FixUserShellFolderPermissions.ps1 -allprofiles
  17. # - To accept the EULA and run the tool silently:
  18. # .\FixUserShellFolderPermissions.ps1 -accepteula
  19. #
  20. # This script is provided AS IS, no support nor warranty of any kind is provided for its usage.
  21. #
  22.  
  23. param (
  24. [switch]$register = $false,
  25. [switch]$force = $false,
  26. [switch]$allprofiles = $false,
  27. [switch]$accepteula = $false
  28. )
  29.  
  30. [void][System.Reflection.Assembly]::Load('System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
  31. [void][System.Reflection.Assembly]::Load('System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
  32.  
  33. # Taken from https://www.leeholmes.com/adjusting-token-privileges-in-powershell/ with minor adjusment (use GetCurrentProcess())
  34. $definition = @'
  35. using System;
  36.  
  37. using System.Runtime.InteropServices;
  38. public class AdjPriv
  39. {
  40. [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  41. internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
  42. ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
  43.  
  44. [DllImport("Kernel32.dll")]
  45. public static extern IntPtr GetCurrentProcess();
  46.  
  47. [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  48. internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
  49.  
  50. [DllImport("advapi32.dll", SetLastError = true)]
  51. internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
  52.  
  53. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  54. internal struct TokPriv1Luid
  55. {
  56. public int Count;
  57. public long Luid;
  58. public int Attr;
  59. }
  60.  
  61. internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
  62. internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
  63. internal const int TOKEN_QUERY = 0x00000008;
  64. internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
  65.  
  66. public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
  67. {
  68. bool retVal;
  69. TokPriv1Luid tp;
  70. IntPtr htok = IntPtr.Zero;
  71. IntPtr hproc = GetCurrentProcess();
  72. retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
  73. tp.Count = 1;
  74. tp.Luid = 0;
  75.  
  76. if(disable)
  77. {
  78. tp.Attr = SE_PRIVILEGE_DISABLED;
  79. }
  80. else
  81. {
  82. tp.Attr = SE_PRIVILEGE_ENABLED;
  83. }
  84.  
  85. retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
  86. retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
  87. return retVal;
  88. }
  89. }
  90. '@
  91.  
  92. function ShowEULAPopup($mode)
  93. {
  94. $EULA = New-Object -TypeName System.Windows.Forms.Form
  95. $richTextBox1 = New-Object System.Windows.Forms.RichTextBox
  96. $btnAcknowledge = New-Object System.Windows.Forms.Button
  97. $btnCancel = New-Object System.Windows.Forms.Button
  98.  
  99. $EULA.SuspendLayout()
  100. $EULA.Name = "EULA"
  101. $EULA.Text = "Microsoft Diagnostic Tools End User License Agreement"
  102.  
  103. $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
  104. $richTextBox1.Location = New-Object System.Drawing.Point(12,12)
  105. $richTextBox1.Name = "richTextBox1"
  106. $richTextBox1.ScrollBars = [System.Windows.Forms.RichTextBoxScrollBars]::Vertical
  107. $richTextBox1.Size = New-Object System.Drawing.Size(776, 397)
  108. $richTextBox1.TabIndex = 0
  109. $richTextBox1.ReadOnly=$True
  110. $richTextBox1.Add_LinkClicked({Start-Process -FilePath $_.LinkText})
  111. $richTextBox1.Rtf = @"
  112. {\rtf1\ansi\ansicpg1252\deff0\nouicompat{\fonttbl{\f0\fswiss\fprq2\fcharset0 Segoe UI;}{\f1\fnil\fcharset0 Calibri;}{\f2\fnil\fcharset0 Microsoft Sans Serif;}}
  113. {\colortbl ;\red0\green0\blue255;}
  114. {\*\generator Riched20 10.0.19041}{\*\mmathPr\mdispDef1\mwrapIndent1440 }\viewkind4\uc1
  115. \pard\widctlpar\f0\fs19\lang1033 MICROSOFT SOFTWARE LICENSE TERMS\par
  116. Microsoft Diagnostic Scripts and Utilities\par
  117. \par
  118. {\pict{\*\picprop}\wmetafile8\picw26\pich26\picwgoal32000\pichgoal15
  119. 0100090000035000000000002700000000000400000003010800050000000b0200000000050000
  120. 000c0202000200030000001e000400000007010400040000000701040027000000410b2000cc00
  121. 010001000000000001000100000000002800000001000000010000000100010000000000000000
  122. 000000000000000000000000000000000000000000ffffff00000000ff040000002701ffff0300
  123. 00000000
  124. }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
  125. {\pict{\*\picprop}\wmetafile8\picw26\pich26\picwgoal32000\pichgoal15
  126. 0100090000035000000000002700000000000400000003010800050000000b0200000000050000
  127. 000c0202000200030000001e000400000007010400040000000701040027000000410b2000cc00
  128. 010001000000000001000100000000002800000001000000010000000100010000000000000000
  129. 000000000000000000000000000000000000000000ffffff00000000ff040000002701ffff0300
  130. 00000000
  131. }\par
  132. \pard
  133. {\pntext\f0 1.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pndec{\pntxta.}}
  134. \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
  135. \pard\widctlpar\par
  136. \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
  137. \par
  138. \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
  139. \pard\widctlpar\par
  140. \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
  141. \pard\widctlpar\par
  142. \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
  143. \pard\widctlpar\par
  144. \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
  145. \pard\widctlpar\par
  146. \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
  147. \pard\widctlpar\qj\par
  148. \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
  149. \pard\widctlpar\par
  150. \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
  151. \pard\widctlpar\par
  152. \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
  153. \pard\widctlpar\par
  154. \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
  155. \pard\sa200\sl276\slmult1\f1\fs22\lang9\par
  156. \pard\f2\fs17\lang2057\par
  157. }
  158. "@
  159. $richTextBox1.BackColor = [System.Drawing.Color]::White
  160. $btnAcknowledge.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right
  161. $btnAcknowledge.Location = New-Object System.Drawing.Point(544, 415)
  162. $btnAcknowledge.Name = "btnAcknowledge";
  163. $btnAcknowledge.Size = New-Object System.Drawing.Size(119, 23)
  164. $btnAcknowledge.TabIndex = 1
  165. $btnAcknowledge.Text = "Accept"
  166. $btnAcknowledge.UseVisualStyleBackColor = $True
  167. $btnAcknowledge.Add_Click({$EULA.DialogResult=[System.Windows.Forms.DialogResult]::Yes})
  168.  
  169. $btnCancel.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right
  170. $btnCancel.Location = New-Object System.Drawing.Point(669, 415)
  171. $btnCancel.Name = "btnCancel"
  172. $btnCancel.Size = New-Object System.Drawing.Size(119, 23)
  173. $btnCancel.TabIndex = 2
  174. if($mode -ne 0)
  175. {
  176. $btnCancel.Text = "Close"
  177. }
  178. else
  179. {
  180. $btnCancel.Text = "Decline"
  181. }
  182. $btnCancel.UseVisualStyleBackColor = $True
  183. $btnCancel.Add_Click({$EULA.DialogResult=[System.Windows.Forms.DialogResult]::No})
  184.  
  185. $EULA.AutoScaleDimensions = New-Object System.Drawing.SizeF(6.0, 13.0)
  186. $EULA.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Font
  187. $EULA.ClientSize = New-Object System.Drawing.Size(800, 450)
  188. $EULA.Controls.Add($btnCancel)
  189. $EULA.Controls.Add($richTextBox1)
  190. if($mode -ne 0)
  191. {
  192. $EULA.AcceptButton=$btnCancel
  193. }
  194. else
  195. {
  196. $EULA.Controls.Add($btnAcknowledge)
  197. $EULA.AcceptButton=$btnAcknowledge
  198. $EULA.CancelButton=$btnCancel
  199. }
  200. $EULA.ResumeLayout($false)
  201. $EULA.Size = New-Object System.Drawing.Size(800, 650)
  202.  
  203. Return ($EULA.ShowDialog())
  204. }
  205.  
  206. function ShowEULAIfNeeded($toolName, $mode)
  207. {
  208. $eulaRegPath = "HKCU:Software\Microsoft\CESDiagnosticTools"
  209. $eulaAccepted = "No"
  210. $eulaValue = $toolName + " EULA Accepted"
  211. if(Test-Path $eulaRegPath)
  212. {
  213. $eulaRegKey = Get-Item $eulaRegPath
  214. $eulaAccepted = $eulaRegKey.GetValue($eulaValue, "No")
  215. }
  216. else
  217. {
  218. $eulaRegKey = New-Item $eulaRegPath
  219. }
  220. if($mode -eq 2) # silent accept
  221. {
  222. $eulaAccepted = "Yes"
  223. $ignore = New-ItemProperty -Path $eulaRegPath -Name $eulaValue -Value $eulaAccepted -PropertyType String -Force
  224. }
  225. else
  226. {
  227. if($eulaAccepted -eq "No")
  228. {
  229. $eulaAccepted = ShowEULAPopup($mode)
  230. if($eulaAccepted -eq [System.Windows.Forms.DialogResult]::Yes)
  231. {
  232. $eulaAccepted = "Yes"
  233. $ignore = New-ItemProperty -Path $eulaRegPath -Name $eulaValue -Value $eulaAccepted -PropertyType String -Force
  234. }
  235. }
  236. }
  237. return $eulaAccepted
  238. }
  239.  
  240. if ($accepteula) {
  241. $eulaAccepted = ShowEULAIfNeeded "FixUserShellFolderPermissions" 2
  242. } else {
  243. $eulaAccepted = ShowEULAIfNeeded "FixUserShellFolderPermissions" 0
  244. }
  245.  
  246. Write-Host ""
  247. if($eulaAccepted -ne "Yes")
  248. {
  249. Write-Host "You must accept the End-User License Agreement (EULA) to run this Microsoft Diagnostic Tool!"
  250. exit
  251. }
  252. Write-Host "Thanks for accepting the End-User License Agreement (EULA) of this Microsoft Diagnostic Tool!"
  253. Write-Host ""
  254.  
  255. $AAP_SID = 'S-1-15-2-1'
  256. $ADMINS_SID = 'S-1-5-32-544'
  257. $SYSTEM_SID = 'S-1-5-18'
  258. $USERS_SHELL_FOLDERS = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
  259. $PROFILE_LIST = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
  260. $EXCLUDED_PROFILES = "*S-1-5-18*","*S-1-5-19*","*S-1-5-20*"
  261.  
  262. Write-Host "Usage:"
  263. Write-Host "------"
  264. Write-Host " - Fix (if needed) your current user profile:"
  265. Write-Host " .\FixUserShellFolderPermissions.ps1"
  266. Write-Host " - Force the registration main Shell packages:"
  267. Write-Host " .\FixUserShellFolderPermissions.ps1 -register"
  268. Write-Host " - Force the registration of every packages (might take long time):"
  269. Write-Host " .\FixUserShellFolderPermissions.ps1 -force"
  270. Write-Host " - [Run As Admin] Attempt to recover every profiles, but won't register packages"
  271. Write-Host " .\FixUserShellFolderPermissions.ps1 -allprofiles"
  272. Write-Host " - To accept the EULA and run the tool silently."
  273. Write-Host " .\FixUserShellFolderPermissions.ps1 -accepteula"
  274. Write-Host ""
  275. Write-Host " ----------------"
  276. Write-Host ""
  277. Write-Host (get-date).ToString() - $MyInvocation.MyCommand.Name started on $env:ComputerName for user $env:UserName
  278. Write-Host "Command line used: " $MyInvocation.Line
  279. Write-Host ""
  280.  
  281. if ($allprofiles) {
  282. # The -allprofiles switch needs to run under Admin or LocalSystem and will iterate on every profile to fix the permissions"
  283. # 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"
  284. $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
  285. $isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
  286. $isSystem = ($currentPrincipal.Identities.User.Value) -eq $SYSTEM_SID
  287.  
  288. if ($isAdmin -or $isSystem) {
  289.  
  290. # Enabled privilege
  291. $processHandle = [System.Diagnostics.Process]::GetCurrentProcess().Handle
  292. $type = Add-Type $definition -PassThru
  293. if ($type -is [Array]) {
  294. $type[0]::EnablePrivilege($processHandle, "SeTakeOwnershipPrivilege", $false) | Out-Null
  295. }
  296.  
  297. $profiles = (Get-ChildItem $PROFILE_LIST -Exclude $EXCLUDED_PROFILES | select -ExpandProperty Name)
  298. New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS | Out-Null
  299.  
  300. Write-Host("Reviewing the registry permissions of $($profiles.Count) profiles:")
  301. Write-Host("")
  302.  
  303. Foreach ($profile in $profiles) {
  304. $profile_sid = Split-Path -path $profile -Leaf
  305. $profile_usf = "HKU:\$profile_sid\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
  306. if (Test-Path($profile_usf))
  307. {
  308. $profile_name = Get-ItemPropertyValue -Path "HKU:\$profile_sid\Volatile Environment" -Name "USERNAME"
  309. Write-Host(" - HKU:\$profile_sid (name '$profile_name')")
  310.  
  311. $acl_fixed = $false
  312. $dacl = $null
  313. $acl = (Get-Acl $profile_usf)
  314. if ($acl) {
  315. $dacl = $acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
  316. }
  317. # If we can't read even the ACL then we need to get the key ownership, then try again
  318. if (-not $dacl) {
  319. $key = [Microsoft.Win32.Registry]::Users.OpenSubKey($profile_usf.Replace("HKU:\", ""),[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::TakeOwnership)
  320. $acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
  321. $acl.SetOwner((New-Object System.Security.Principal.SecurityIdentifier($ADMINS_SID)))
  322. $key.SetAccessControl($acl)
  323. $acl_fixed = $true
  324. Write-Host(" - Fixed broken 'User Shell Folders' registry permissions")
  325.  
  326. $acl = (Get-Acl $profile_usf)
  327. if ($acl) {
  328. $dacl = $acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
  329. }
  330. }
  331. # If we can't find any ACE for All Application Packages, then restore the ACL from parent
  332. if (-not ($dacl | where IdentityReference -eq $AAP_SID)) {
  333. # Restores ACL inheritance from parent
  334. $key = [Microsoft.Win32.Registry]::Users.OpenSubKey($profile_usf.Replace("HKU:\", ""),[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
  335. $acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::Access)
  336. $acl.SetAccessRuleProtection($false, $false)
  337. $key.SetAccessControl($acl)
  338.  
  339. # Now clean up possible rules to only keep inherited ones and restore the owner to System
  340. $dacl = $acl.GetAccessRules($true,$false,[System.Security.Principal.SecurityIdentifier])
  341. $dacl | %{ $acl.RemoveAccessRule($_) } | Out-Null # Clearing the ACL to avoid duplicated ACEs
  342. $acl.SetOwner((New-Object System.Security.Principal.SecurityIdentifier($SYSTEM_SID)))
  343. $key.SetAccessControl($acl)
  344. $acl_fixed = $true
  345. Write-Host(" - Added missing 'All Application Packages' from 'User Shell Folders' registry permissions")
  346. Write-Host(" -> Note you may still need to run from this user session .\FixUserShellFolderPermissions.ps1 -register")
  347. }
  348. if (-not $acl_fixed) {
  349. Write-Host(" -> No changed was made, profil permissions are correct.")
  350. }
  351. } else {
  352. Write-Host(" - The profile hive for $profile_sid is not loaded in the registry.")
  353. Write-Host(" -> If it is an affected user, ask him to login or load manually its registry hive and re-run the script.")
  354. }
  355. Write-Host("")
  356. }
  357. } else {
  358. Write-Host("ERROR: You need to run from an elevated prompt as an Admin or LocalSystem to use the -allprofiles switch.")
  359. Write-Host("")
  360. }
  361. } else {
  362. if (Test-path $USERS_SHELL_FOLDERS)
  363. {
  364. $acl = (Get-Acl $USERS_SHELL_FOLDERS)
  365. if ($acl) {
  366. $dacl = $acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])
  367. }
  368. }
  369.  
  370. if (!$dacl) {
  371. Write-Host "ERROR: Failed to get the access rules from User Shell Folders key."
  372. Write-Host "Please rerun the script as admin from an elevated prompt, and use the special switch -allprofiles"
  373. } elseif ($dacl | where IdentityReference -eq $AAP_SID) {
  374. Write-Host "-> No need to fix User Shell Folders registry permission for the current user, they are correct."
  375. Write-Host ""
  376. } else
  377. {
  378. Write-Host "User Shell Folders registry permission are incorrect..."
  379.  
  380. # Restores ACL inheritance from parent
  381. $dacl | %{ $acl.RemoveAccessRule($_) } | Out-Null # Clearing the ACL to avoid duplicated ACEs
  382. $acl.SetAccessRuleProtection($false, $false) # Enabling inheritance
  383. $acl | Set-Acl -Path $USERS_SHELL_FOLDERS # Now sets the repaired ACL
  384. Write-Host "==> Registry permission were fixed!"
  385. Write-Host ""
  386. $acl_fixed = $true
  387. }
  388.  
  389. # The most critical shell SystemApps list contains important Shell packages which will always try to be re-registered
  390. $MOST_CRITICAL_SHELL_SYSTEMAPPS = @("ShellExperienceHost", "StartMenuExperienceHost", "AAD.BrokerPlugin", "Windows.Search", "Cortana", "Client.CBS")
  391. $APPX_ALL_USER_STORE = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore'
  392.  
  393. if ($acl_fixed -or $register -or $force) {
  394. if ($force) {
  395. Write-Host "Note registering every package may take quite a long time!"
  396. Write-Host "Consider using -register only if a force registration of every package is not require"
  397. Write-Host ""
  398. Write-Host "Force registering EVERY app packages for the user..."
  399. } else {
  400. Write-Host "Re-registering required app packages for the user..."
  401. }
  402.  
  403. # Getting a first list of registered frameworks for the user
  404. $packages = Get-AppxPackage -PackageType:Framework
  405. # Register frameworks (dependencies) if they are not registered, or if -force switch is used
  406. $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}} )
  407. ForEach($dep in $deps) {
  408. if ($force -or (!($packages | where {$_.PackageFullName -eq $dep.PackageFullName}))) {
  409. if(Test-Path $dep.InstallLocation) {
  410. Write-Host "Registering Dependency: " $dep.PackageFullName
  411. Add-AppxPackage -DisableDevelopmentMode -ForceApplicationShutdown -Register -Path ($dep.InstallLocation) -ErrorAction SilentlyContinue
  412. }
  413. }
  414. }
  415. # Getting an updated list of packages, including bundle & every package type, now dependencies are registered
  416. $packages = Get-AppxPackage -PackageType:all
  417.  
  418. # Always force re-registering most important SystemApps, or every SystemApp with -force switch
  419. $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}} )
  420. ForEach($app in $apps) {
  421. if ($force -or ($MOST_CRITICAL_SHELL_SYSTEMAPPS | % { if ($app.PackageFullName -match $_ ) { $True } })) {
  422. if(Test-Path $app.InstallLocation) {
  423. Write-Host "Registering SystemApps: " $app.PackageFullName
  424. Add-AppxPackage -DisableDevelopmentMode -ForceApplicationShutdown -Register -Path ($app.InstallLocation) -ErrorAction SilentlyContinue
  425. }
  426. }
  427. }
  428.  
  429. # Registering WindowsApps if they are not registered for the user, or with -force switch
  430. $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}} )
  431. ForEach($app in $apps) {
  432. if ($force -or (!($packages | where {$_.PackageFullName -eq $app.PackageFullName}))) {
  433. if(Test-Path $app.InstallLocation) {
  434. Write-Host "Registering WindowsApps: " $app.PackageFullName
  435. Add-AppxPackage -DisableDevelopmentMode -ForceApplicationShutdown -Register -Path ($app.InstallLocation) -ErrorAction SilentlyContinue
  436. }
  437. }
  438. }
  439. Write-Host ""
  440. Write-Host "-> Your profile should be fixed."
  441. } else {
  442. Write-Host "-> No packages will be registered as we haven't changed permissions, and -register or -force were not used"
  443. }
  444. }
  445.  
  446. Write-Host ""
  447. Write-Host (get-date).ToString() - User Shell Folders script completed
  448. Write-Host ""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement