win: improve OneDrive data deletion safety

This commit improves the safety mechanisms in the script for deleting
OneDrive user data on Windows.

Key changes:

- System Integrity Protection: The script now checks if user shell
  folders point to the OneDrive directory. If they do, it halts the
  deletion and provides guidance to the user. This ensures system
  stability is not compromised.
- Data Loss Prevention: The script will no longer delete files or
  non-empty folders. This precaution helps to avoid unintended data
  loss.

Other supporting changes:

- This script now covers OneDrive folders for multi-account users.
- Separation of concerns: The 'Remove OneDrive residual files' script is
  is divided into two distinct scripts for better maintainability and
  documentation clarity:
  1. 'Remove OneDrive user data and synced folders'
  2. 'Remove OneDrive installation files and cache'
- Fix an issue with the Windows 11 check in the 'Disable automatic
  OneDrive installation' revert script.
- Update related documentation with archived URLs for reliability.
- Fix indentation of OneDrive removal scripts.
This commit is contained in:
undergroundwires
2024-03-17 21:40:23 +01:00
parent 5abf8ff216
commit 5eff3a0488

View File

@@ -14295,36 +14295,154 @@ actions:
)
)
-
name: Remove OneDrive residual files
name: Remove OneDrive user data and synced folders
recommend: strict
docs: |-
This script cleans OneDrive files such as installation directories, application data,
and temporary files and cache.
This script deletes the OneDrive directory and all stored data from your profile.
- `C:\OneDriveCache`: Temporary cache location [1].
- `C:\ProgramData\Microsoft OneDrive`: Program data, used during setup [2] [3].
- `C:\Users\<username>\OneDrive`: OneDrive root directory [4].
- `C:\Users\<username>\AppData\Local\Microsoft\OneDrive`: OneDrive installation directory [5].
OneDrive usually saves your data in the `%USERPROFILE%\OneDrive` directory [1] [2], also known as the *OneDrive folder*
or *OneDrive root directory* [2].
By default, OneDrive stores user data in folder called *OneDrive* [1].
For multiple accounts, files may be in *OneDrive - Personal* or *OneDrive - CompanyName* folders [1] [3].
The folders are reported by the community [1]. According to the tests:
OneDrive can synchronize default Windows folders like *Documents*, *Pictures*, *Music*, and *Desktop* [4] [5] [6] [7].
These folders are known as *user shell folders* [6] or *Windows system folders* [7].
Upon synchronization, these folders are moved within the OneDrive user data directory [5] [8].
Users may enable this synchronization unknowingly during Windows setup by choosing *Save files to OneDrive* option [9] [10].
Alternatively, synchronization can be enabled later through OneDrive settings [4]. OneDrive
may also prompt users to *set up protection of important folders* [11], a feature also referred to as *protect your folders* or *Known
Folder Move (KFM)* [11]. Additionally, an organization may move files of their managed computers to OneDrive using methods such as the
*Windows Folder Redirection Group Policy* [8].
This script contains safeguards to protect against unintended consequences:
1. **System Integrity Protection**:
The script verifies if any user shell folders are linked to the OneDrive directory.
This is crucial as redirecting these folders to OneDrive can cause system integrity issues.
For instance, if the *Desktop* folder is redirected to OneDrive, deleting the OneDrive folder could make the *Desktop* inaccessible.
The script stops and warns if any user shell folders are found within OneDrive.
> 💡 Move these folders back to their original locations using the
> `HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders` registry key [6] before proceeding.
2. **Data Loss Prevention**:
The script avoids deleting files or non-empty directories to prevent accidental data loss.
> 💡 Manually empty these directories before running the script or opt to delete them afterward if needed.
The OneDrive folder has been confirmed to exist in modern versions of Windows, tested since Windows 11 (since 22H2)
and Windows 10 (since 22H2).
[1]: https://web.archive.org/web/20231025220524/https://support.microsoft.com/en-us/office/sync-onedrive-files-and-folders-3b8246e0-cc3c-4ae7-b4e1-4b4b37d27f68 "Sync OneDrive files and folders - Microsoft Support | support.microsoft.com"
[2]: https://web.archive.org/web/20220812205500/https://admx.help/?Category=OneDrive&Policy=Microsoft.Policies.OneDriveNGSC::DefaultRootDir "Set the default location for the OneDrive folder | admx.help"
[3]: https://web.archive.org/web/20231025220530/https://support.microsoft.com/en-us/office/sync-files-with-onedrive-in-windows-615391c4-2bd3-4aae-a42a-858262e42a49 "Sync files with OneDrive in Windows | support.microsoft.com"
[4]: https://web.archive.org/web/20231025220541/https://support.microsoft.com/en-us/office/choose-which-onedrive-folders-to-sync-to-your-computer-98b8b011-8b94-419b-aa95-a14ff2415e85 "Choose which OneDrive folders to sync to your computer - Microsoft Support | support.microsoft.com"
[5]: https://web.archive.org/web/20240317200014/https://support.microsoft.com/en-us/office/back-up-your-folders-with-onedrive-d61a7930-a6fb-4b95-b28a-6552e77c3057 "Back up your folders with OneDrive - Microsoft Support | support.microsoft.com"
[6]: https://web.archive.org/web/20231025220843/https://support.microsoft.com/en-us/topic/how-to-redirect-user-shell-folders-to-a-specified-path-by-using-profile-maker-ed6289ae-1f9c-b874-4e8c-20d23ea65b2e "How to redirect user shell folders to a specified path by using Profile Maker - Microsoft Support | support.microsoft.com"
[7]: https://web.archive.org/web/20231025220733/https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/controlled-folders?view=o365-worldwide#windows-system-folders-are-protected-by-default "Protect important folders from ransomware from encrypting your files with controlled folder access | Microsoft Learn | learn.microsoft.com"
[8]: https://web.archive.org/web/20231025220852/https://learn.microsoft.com/en-us/sharepoint/redirect-known-folders "Redirect and move Windows known folders to OneDrive - SharePoint in Microsoft 365 | Microsoft Learn | learn.microsoft.com"
[9]: https://web.archive.org/web/20231025220728/https://learn.microsoft.com/en-us/windows-hardware/customize/desktop/customize-oobe-in-windows-11 "Customize the Out of Box experience (OOBE) | Microsoft Learn | learn.microsoft.com"
[10]: https://web.archive.org/web/20231025220741/https://learn.microsoft.com/en-us/windows-hardware/customize/desktop/customize-oobe "Customize OOBE | Microsoft Learn | learn.microsoft.com"
[11]: https://web.archive.org/web/20231025220711/https://techcommunity.microsoft.com/t5/microsoft-onedrive-blog/migrate-your-files-to-onedrive-easily-with-known-folder-move/ba-p/207076 "Migrate Your Files to OneDrive Easily with Known Folder Move - Microsoft Community Hub | techcommunity.microsoft.com"
call:
function: DeleteDirectory
parameters:
directoryGlob: '%USERPROFILE%\OneDrive*'
# System Integrity Guard: Verifying user shell folders
# This section checks if any user shell folders are set to the OneDrive directory.
# It ensures the system's integrity by verifying the registry path and entries for user shell folders.
# If any user shell folder is found in OneDrive, a warning is issued, and the script stops to avoid system disruptions.
beforeIteration: |-
$oneDriveUserFolderPattern = [System.Environment]::ExpandEnvironmentVariables('%USERPROFILE%\OneDrive') + '*'
while ($true) { # Loop to control the execution of the subsequent code
try {
$userShellFoldersRegistryPath = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
if (-not (Test-Path $userShellFoldersRegistryPath)) {
Write-Output "Skipping verification: The registry path for user shell folders is missing: `"$userShellFoldersRegistryPath`""
break;
}
$userShellFoldersRegistryKeys = Get-ItemProperty -Path $userShellFoldersRegistryPath
$userShellFoldersEntries = @($userShellFoldersRegistryKeys.PSObject.Properties)
if ($userShellFoldersEntries.Count -eq 0) {
Write-Warning "Skipping verification: No entries found for user shell folders in the registry: `"$userShellFoldersRegistryPath`""
break;
}
Write-Output "Initiating verification: Checking if any of the ${userShellFoldersEntries.Count} user shell folders point to the OneDrive user folder pattern ($oneDriveUserFolderPattern)."
$userShellFoldersInOneDrive = @()
foreach ($registryEntry in $userShellFoldersEntries) {
$userShellFolderName = $registryEntry.Name
$userShellFolderPath = $registryEntry.Value
if (!$userShellFolderPath) {
Write-Output "Skipping: The user shell folder `"$userShellFolderName`" does not have a defined path."
continue
}
$expandedUserShellFolderPath = [System.Environment]::ExpandEnvironmentVariables($userShellFolderPath)
if(-not ($expandedUserShellFolderPath -like $oneDriveUserFolderPattern)) {
continue
}
$userShellFoldersInOneDrive += [PSCustomObject]@{ Name = $userShellFolderName; Path = $expandedUserShellFolderPath }
}
if ($userShellFoldersInOneDrive.Count -gt 0) {
$warningMessage = 'To keep your computer running smoothly, OneDrive user folder will not be deleted.'
$warningMessage += "`nIt's being used by the OS as a user shell directory for the following folders:"
$userShellFoldersInOneDrive.ForEach({
$warningMessage += "`n- $($_.Name): $($_.Path)"
})
Write-Warning $warningMessage
exit 0
}
Write-Output "Successfully verified that none of the $($userShellFoldersEntries.Count) user shell folders point to the OneDrive user folder pattern."
break;
} catch {
Write-Warning "An error occurred during verification of user shell folders. Skipping prevent potential issues. Error: $($_.Exception.Message)"
exit 0
}
}
# Data Loss Prevention Guard: Checking directory contents
# This guard ensures that no file or non-empty directory is accidentally deleted.
# It checks each path; if it's a file or a non-empty directory, the script skips deletion for that path.
# This step is designed to prevent unintended data loss during script execution.
duringIteration: |-
try {
if (Test-Path -Path $path -PathType Leaf) {
Write-Warning "Retaining file `"$path`" to safeguard your data."
continue;
} elseif (Test-Path -Path $path -PathType Container) {
if ((Get-ChildItem "$path" -Recurse | Measure-Object).Count -gt 0) {
Write-Warning "Preserving non-empty folder `"$path`" to protect your files."
continue;
}
}
} catch {
Write-Warning "An error occurred while processing `"$path`". Skipping to protect your data. Error: $($_.Exception.Message)"
continue;
}
-
name: Remove OneDrive installation files and cache
recommend: strict
docs: |-
This script removes OneDrive installation directories, application data, temporary files, and cache.
- `C:\OneDriveCache`: A location for temporary cache files [1].
- `C:\ProgramData\Microsoft OneDrive`: Stores data used in setting up OneDrive [2] [3].
- `C:\Users\<username>\AppData\Local\Microsoft\OneDrive`: OneDrive installation directory [4].
Identified by the community [1] and confirmed through testing, these folders include:
| Directory | Windows 11 (since 22H2) | Windows 10 (since 22H2) |
| --------- |:-----------------------:|:-----------------------:|
| `%SYSTEMDRIVE%C:\OneDriveCache` | ❌ Missing | ❌ Missing |
| `%SYSTEMDRIVE%\OneDriveCache` | ❌ Missing | ❌ Missing |
| `%PROGRAMDATA%\Microsoft OneDrive` | ✅ Exists | ✅ Exists |
| `%LOCALAPPDATA%\Microsoft\OneDrive` | ✅ Exists | ✅ Exists |
| `%USERPROFILE%\OneDrive` | ✅ Exists | ✅ Exists |
[1]: https://social.microsoft.com/Forums/en-US/53263a51-856f-4e64-bc0e-a689d4cc5a8b/release-notes-for-1907-build-29711727413?forum=FSLogix "Release Notes for 1907 - build 2.9.7117.27413 | social.microsoft.com"
[2]: https://techcommunity.microsoft.com/t5/sharepoint/onedrive-setup-fails-to-complete/m-p/2072446 "OneDrive setup fails to complete - Microsoft Tech Community"
[3]: https://answers.microsoft.com/en-us/msoffice/forum/all/why-does-onedrive-act-as-ransomware/288e5940-b92b-493c-91ff-dafd26279bee "Why does OneDrive act as Ransomware? - Microsoft Community"
[4]: https://techcommunity.microsoft.com/t5/onedrive-for-business/change-onedrive-installation-location/m-p/225064 "Change OneDrive installation location - Microsoft Tech Community | techcommunity.microsoft.com"
[5]: https://learn.microsoft.com/en-us/sharepoint/install/configure-syncing-with-the-onedrive-sync-app "Configure syncing with the new OneDrive sync app - SharePoint Server | Microsoft Learn | learn.microsoft.com"
[1]: https://web.archive.org/web/20231206213533/https://social.microsoft.com/Forums/en-US/53263a51-856f-4e64-bc0e-a689d4cc5a8b/release-notes-for-1907-build-29711727413?forum=FSLogix "Release Notes for 1907 - build 2.9.7117.27413 | social.microsoft.com"
[2]: https://web.archive.org/web/20231231134443/https://techcommunity.microsoft.com/t5/sharepoint/onedrive-setup-fails-to-complete/m-p/2072446 "OneDrive setup fails to complete - Microsoft Tech Community"
[3]: https://web.archive.org/web/20231231134548/https://answers.microsoft.com/en-us/msoffice/forum/all/why-does-onedrive-act-as-ransomware/288e5940-b92b-493c-91ff-dafd26279bee "Why does OneDrive act as Ransomware? - Microsoft Community"
[4]: https://web.archive.org/web/20231231134612/https://learn.microsoft.com/en-us/sharepoint/install/configure-syncing-with-the-onedrive-sync-app "Configure syncing with the new OneDrive sync app - SharePoint Server | Microsoft Learn | learn.microsoft.com"
call:
-
function: DeleteDirectory
parameters:
directoryGlob: '%USERPROFILE%\OneDrive'
-
function: DeleteDirectory
parameters:
@@ -14435,6 +14553,7 @@ actions:
parameters:
code: reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "OneDriveSetup" /f 2>$null
revertCode: |-
$osVersion = [System.Environment]::OSVersion.Version
function Test-IsWindows11 { ($osVersion.Major -gt 10) -or (($osVersion.Major -eq 10) -and ($osVersion.Build -ge 22000)) }
if (Test-IsWindows11) {
Write-Host 'Skipping, no action needed on Windows 11.'
@@ -14456,7 +14575,7 @@ actions:
This CLSID includes `System.IsPinnedToNameSpaceTree` as value as `1` after clean installation in both Windows 10 and Windows 11.
[1]: https://support.microsoft.com/en-us/office/sync-files-with-onedrive-in-windows-615391c4-2bd3-4aae-a42a-858262e42a49 "Sync files with OneDrive in Windows | support.microsoft.com"
[1]: https://web.archive.org/web/20231025220530/https://support.microsoft.com/en-us/office/sync-files-with-onedrive-in-windows-615391c4-2bd3-4aae-a42a-858262e42a49 "Sync files with OneDrive in Windows | support.microsoft.com"
[2]: https://answers.microsoft.com/en-us/windows/forum/all/remove-onedrive-from-file-explorer-navigation-pane/38ac7524-2b35-4ffc-baab-40ad61dc5d79 "Remove OneDrive from File Explorer navigation pane - Microsoft Community | answers.microsoft.com"
code: |-
reg add "HKCR\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" /v "System.IsPinnedToNameSpaceTree" /d "0" /t REG_DWORD /f
@@ -17785,6 +17904,10 @@ functions:
- name: directoryGlob # The directory to delete along with its files and subdirectories
- name: grantPermissions # Grants permission on the parent directory and its sub-items recursively (including all files and directories) to be able to delete them.
optional: true
- name: beforeIteration # (Iteration callback) Code to run before iteration.
optional: true
- name: duringIteration # (Iteration callback) Code to run for each found item.
optional: true
call:
-
function: Comment
@@ -17803,6 +17926,8 @@ functions:
$($directoryGlob = '{{ $directoryGlob }}'; if (-Not $directoryGlob.EndsWith('\')) { $directoryGlob += '\' }; $directoryGlob )
grantPermissions: '{{ with $grantPermissions }}true{{ end }}'
recurse: 'true' # Logs every deleted file name
beforeIteration: '{{ with $beforeIteration }}{{ . }}{{ end }}'
duringIteration: '{{ with $duringIteration }}{{ . }}{{ end }}'
-
name: DeleteFiles
# 💡 Purpose: