fixed Install-MicrosoftOffice365.ps1

added Repair-OneDriveKnownFolderPaths.ps1
This commit is contained in:
2026-10-22 00:16:40 -04:00
parent aea80c7be4
commit 031cfe40a1
8 changed files with 1041 additions and 22 deletions
+27 -12
View File
@@ -53,7 +53,9 @@ function Get-OfficeDeploymentDefinitions {
MinimumServerRevision = 2402
Windows11Build = 22000
TeamsUnsupportedWindows10Editions = @('EnterpriseS', 'EnterpriseSN', 'IoTEnterpriseS')
RunningAppNames = @('lync', 'winword', 'excel', 'msaccess', 'mstore', 'infopath', 'setlang', 'msouc', 'ois', 'onenote', 'outlook', 'powerpnt', 'mspub', 'groove', 'visio', 'winproj', 'graph', 'teams', 'ms-teams', 'OneDrive', 'olk')
# Teams.exe is classic, msteams.exe is the older personal/Windows Chat client,
# and ms-teams.exe is the current client. Check all three before removal.
RunningAppNames = @('lync', 'winword', 'excel', 'msaccess', 'mstore', 'infopath', 'setlang', 'msouc', 'ois', 'onenote', 'outlook', 'powerpnt', 'mspub', 'groove', 'visio', 'winproj', 'graph', 'teams', 'msteams', 'ms-teams', 'OneDrive', 'olk')
AppxRemovalNames = @('Microsoft.Office.Desktop', 'Microsoft.MicrosoftOfficeHub', 'Microsoft.Office.OneNote', 'Microsoft.OutlookForWindows', 'MSTeams', 'MicrosoftTeams')
TeamsMsiNames = @('Teams Machine-Wide Installer', 'Microsoft Teams Meeting Add-in for Microsoft Office')
OfficeIdentityVersions = @('15.0', '16.0')
@@ -623,6 +625,7 @@ function Install-OfficeCompanionApps {
$packages = @(Wait-OfficeResult { Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -eq $app.Package -and $_.PackageName -like ('*' + $definitions.AppxPublisherSuffix) } } "$($app.Name) provisioning")
if (!$packages.Count) { throw "$($app.Name) setup returned success but the app was not provisioned for all users." }
$versions[$app.Name] = ($packages.Version | Sort-Object -Unique) -join ', '
$null = Write-Output "Verified $($app.Name) provisioned package: $($packages.PackageName -join ', ')."
} else {
$oneDrive = Wait-OfficeResult { Get-OfficeMachineOneDrive } 'per-machine OneDrive registration'
if (!$oneDrive) { throw 'OneDrive setup returned success but a per-machine installation was not detected.' }
@@ -885,15 +888,24 @@ function Clear-OfficeProfileIdentity {
function Start-OfficeUserCleanup {
param([object[]]$Profiles, $Media, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
$deploymentId = Split-Path -Leaf $Workspace; $tasks = @()
$deploymentId = Split-Path -Leaf $Workspace; $tasks = @(); $registrationFailures = @()
foreach ($profile in $Profiles) {
$name = "Emberkom-OfficeCleanup-$deploymentId-$($profile.SID)"
$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$($Media.Helper)`" -DeploymentId $deploymentId"
$principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew
$null = Write-Output "Registering user cleanup task: $name"
$null = Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Force -ErrorAction Stop
try {
$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$($Media.Helper)`" -DeploymentId $deploymentId" -ErrorAction Stop
$principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited -ErrorAction Stop
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID -ErrorAction Stop
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew -ErrorAction Stop
$null = Write-Output "Registering user cleanup task: $name"
$null = Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Force -ErrorAction Stop
} catch {
# A profile can outlive its account, or account lookup can be unavailable.
# Do not leave Office uninstalled because this user's task cannot be created.
# Keep it separate from pending tasks: signing in cannot retry a missing task.
$registrationFailures += [pscustomobject]@{ SID=$profile.SID; ProfilePath=$profile.LocalPath; Error=$_.Exception.Message }
Write-Error "User cleanup task registration failed for $($profile.SID) ($($profile.LocalPath)): $($_.Exception.Message). Continuing Office installation and cleanup scheduling for other users; this user's task needs review." -ErrorAction Continue
continue
}
$tasks += [pscustomobject]@{ Name = $name; SID = $profile.SID; WasLoaded = $profile.Loaded }
if ($profile.Loaded) {
try { Start-ScheduledTask -TaskName $name -ErrorAction Stop }
@@ -915,7 +927,7 @@ function Start-OfficeUserCleanup {
}
else { $pending += $task.SID; $null = Write-Output "Cleanup pending for $($task.SID); task $($task.Name) runs at their next sign-in." }
}
return ,$pending
[pscustomobject]@{ PendingUserSids=$pending; RegistrationFailures=$registrationFailures }
}
function Install-OfficeMedia {
@@ -994,12 +1006,14 @@ function Invoke-OfficeDeployment {
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$userWorkspace = $workspace
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
$pending = Start-OfficeUserCleanup $profiles $media $userWorkspace
$userCleanup = Start-OfficeUserCleanup $profiles $media $userWorkspace
$pending = @($userCleanup.PendingUserSids)
$registrationFailures = @($userCleanup.RegistrationFailures)
Set-OfficeReinstallPhase $userWorkspace
$code = Install-OfficeMedia $Options $media $workspace
$companions = Install-OfficeCompanionApps $media.Companions $workspace -InstallTeams $Options.InstallTeams
if ($reboot -or $removalCode -eq 3010 -or $companions.ExitCode -eq 3010) { $code = 3010 }
$status = if ($pending.Count) { 'InstalledWithUserCleanupPending' } else { 'Installed' }
$status = if ($registrationFailures.Count) { 'InstalledWithUserCleanupIncomplete' } elseif ($pending.Count) { 'InstalledWithUserCleanupPending' } else { 'Installed' }
$null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). No automatic reboot was requested."
$provisionedApps = if ($Options.InstallTeams) { 'Teams and new Outlook are' } else { 'New Outlook is' }
$null = Write-Output "$provisionedApps provisioned for all users; OneDrive is installed per-machine. Users may need to sign out and back in to register the apps."
@@ -1010,7 +1024,7 @@ function Invoke-OfficeDeployment {
}
catch { $cleanupWarnings = @($_.Exception.Message); Write-Error "Office deployment file cleanup was incomplete: $($cleanupWarnings[0])" -ErrorAction Continue }
if ($cleanupWarnings.Count) { $null = Write-Output 'Installation succeeded, but some deployment files remain; see the diagnostic log.' }
[pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; CachedMediaReused=[bool]$media.CachedMediaReused; ArtifactCleanupPending=($cleanupWarnings.Count -gt 0) }
[pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if (($pending.Count -or $registrationFailures.Count) -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; UserCleanupRegistrationFailures = $registrationFailures; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; CachedMediaReused=[bool]$media.CachedMediaReused; ArtifactCleanupPending=($cleanupWarnings.Count -gt 0) }
} finally {
if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose()
@@ -1077,6 +1091,7 @@ function Invoke-OfficeDeploymentEntry {
$null = Write-Output $receipt
Microsoft.PowerShell.Utility\Write-Output $receipt
if ($deployment[0].OfficeDeploymentStatus -like 'Installed*') {
if ($deployment[0].UserCleanupRegistrationFailures.Count) { Microsoft.PowerShell.Utility\Write-Output 'WARNING: Installation succeeded, but some user cleanup tasks could not be registered. Review UserCleanupRegistrationFailures; signing in alone cannot retry a task that was not created.' }
if ($deployment[0].ArtifactCleanupPending) { Microsoft.PowerShell.Utility\Write-Output 'WARNING: Installation succeeded, but some deployment files could not be cleaned up. See the diagnostic log; no background cleanup is scheduled.' }
if ($deployment[0].ExitCode -eq 3010) { Microsoft.PowerShell.Utility\Write-Output 'A restart is required to finish deployment; no automatic reboot was requested.' }
Microsoft.PowerShell.Utility\Write-Output 'Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.'
+4
View File
@@ -24,6 +24,10 @@ For download failures, use the standalone [Test-FileDownload.ps1](Test-FileDownl
See [Office365-Deployment.md](docs/Office365-Deployment.md) for the Syncro dropdowns and clean deployment workflow. Upload the shim in `rmm/Install-MicrosoftOffice365.ps1`; publish the core installer and `resources/office/Office-UserCleanup.ps1` together first. The shim uses the existing `Tools.ps1` unchanged; deployment, host relaunch, and result handling live in the main repository script. `ValidateBeforeChanges` defaults to `true` (checks and stages media only); explicitly select `false` to enable deployment. The workload runs in Windows PowerShell 5.1, requires an explicit subscription selection, removes Office and its companion apps, preserves Windows work-account sign-in, and installs the matching suite silently using Microsoft's current ODT. It then installs new Outlook and per-machine OneDrive using Microsoft's signed installers, plus current Teams only when the selected subscription includes Teams. Pending per-user cleanup is reported separately and protects the reinstalled apps. Action/error diagnostics use the existing Tools log; the result is printed to Syncro.
## OneDrive folder preparation
Use [Repair-OneDriveKnownFolderPaths.ps1](Repair-OneDriveKnownFolderPaths.ps1) to preview and optionally shorten overlong filenames in a user's Documents, Pictures, and Desktop before OneDrive folder backup. It accounts for the projected OneDrive path, preserves extensions, avoids collisions, and saves a CSV plan and rename journal. Preview is the default; paths that require folder restructuring are reported. See [the configuration and RMM guide](docs/OneDrive-PathPreparation.md) and [RMM caller](rmm/Repair-OneDriveKnownFolderPaths.ps1).
## Converting RMM boolean variables
After dot-sourcing `Tools.ps1`, use `ConvertTo-RmmBoolean` with any RMM variable:
+436
View File
@@ -0,0 +1,436 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Previews or shortens filenames in Documents, Pictures, and Desktop for OneDrive.
.DESCRIPTION
Preview is the default. The RMM supplies individual variables inherited by the
core script. Standalone -Options and legacy OneDrivePrepOptions are also supported.
See docs/OneDrive-PathPreparation.md for variable names and defaults.
Only filenames are renamed, in place; extensions and file contents are preserved.
Folders that need restructuring are reported. Does not enable OneDrive backup.
.EXAMPLE
.\Repair-OneDriveKnownFolderPaths.ps1 -Options @{ OneDriveRoot='C:\Users\Jane\OneDrive - Contoso' }
.EXAMPLE
.\Repair-OneDriveKnownFolderPaths.ps1 -Options @{ UserProfilePath='C:\Users\Jane'; OneDriveRoot='C:\Users\Jane\OneDrive - Contoso'; Apply=$true }
#>
[CmdletBinding(SupportsShouldProcess=$true, PositionalBinding=$false)]
param(
# Some Tools.ps1 versions pass an empty positional string to live scripts.
[Parameter(Position=0, DontShow=$true)]
[AllowEmptyString()][ValidatePattern('^\s*$')][string]$RmmArgument,
[hashtable]$Options
)
# Keep implementation variables/preferences local when Run-Script dot-sources us.
& {
param($Configuration, $Caller)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
if ($null -eq $Configuration) {
# Like the Office installer, capture the RMM's injected strings without
# assigning to those variables or requiring a caller-built hashtable.
$rmmInputs = @{}
foreach ($inputName in @('UserProfilePath','OneDriveRoot','Apply','MaxPathLength','MaxNameLength','ReportDirectory','DocumentsPath','PicturesPath','DesktopPath')) {
$inputVariable = Get-Variable -Name $inputName -ErrorAction SilentlyContinue
if ($null -ne $inputVariable) { $rmmInputs[$inputName] = ([string]$inputVariable.Value).Trim() }
}
if ($rmmInputs.Count) {
$Configuration = @{}
foreach ($inputName in @('UserProfilePath','OneDriveRoot','Apply','MaxPathLength','MaxNameLength','ReportDirectory')) {
if ($rmmInputs[$inputName]) { $Configuration[$inputName] = $rmmInputs[$inputName] }
}
$explicitFolders = @{}
foreach ($folderName in @('Documents','Pictures','Desktop')) {
$folderValue = $rmmInputs[$folderName + 'Path']
if ($folderValue -and $folderValue -ine 'Auto') { $explicitFolders[$folderName] = $folderValue }
}
if ($explicitFolders.Count -gt 0 -and $explicitFolders.Count -ne 3) {
throw 'Supply DocumentsPath, PicturesPath, and DesktopPath together, or leave all three Auto/blank for registry discovery.'
}
if ($explicitFolders.Count -eq 3) { $Configuration.KnownFolderPaths = $explicitFolders }
} else {
$shared = Get-Variable -Name OneDrivePrepOptions -ErrorAction SilentlyContinue
$Configuration = if ($shared) { $shared.Value } else { @{} }
}
}
if ($Configuration -isnot [hashtable]) { throw 'Options / OneDrivePrepOptions must be a hashtable.' }
$settings = @{
UserProfilePath=''; OneDriveRoot=''; KnownFolderPaths=$null; Apply=$false
MaxPathLength=240; MaxNameLength=255; ReportDirectory=''
}
foreach ($key in $Configuration.Keys) {
if (-not $settings.ContainsKey($key)) { throw "Unknown option: $key" }
$settings[$key] = $Configuration[$key]
}
# RMM dropdown strings must never be converted using [bool]'false'.
switch -Regex (([string]$settings.Apply).Trim()) {
'^(?i:true|\$true|yes|y|1)$' { $apply = $true; break }
'^(?i:false|\$false|no|n|0)?$' { $apply = $false; break }
default { throw 'Apply must be true/false, yes/no, 1/0, or blank.' }
}
$maxPath = [int]$settings.MaxPathLength
$maxName = [int]$settings.MaxNameLength
if ($maxPath -lt 40 -or $maxPath -gt 520) { throw 'MaxPathLength must be between 40 and 520.' }
if ($maxName -lt 16 -or $maxName -gt 255) { throw 'MaxNameLength must be between 16 and 255.' }
if ($env:OS -ne 'Windows_NT') { throw 'This script requires Windows.' }
function ConvertTo-PrepPath([string]$Path) {
# Absolute drive paths only. UNC roots cannot be used for OneDrive backup.
if ($Path -notmatch '^[A-Za-z]:[\\/]' -or $Path -match '[*?"<>|]' -or $Path.Substring(2).Contains(':')) {
throw "Use an absolute local drive path: $Path"
}
$pathText = [IO.Path]::GetFullPath($Path.Replace('/', '\')).TrimEnd('\')
if ($pathText.Length -le 2) { throw 'A drive root is not a user folder.' }
return $pathText
}
function Test-PrepWithin([string]$Path, [string]$Root) {
return $Path.Equals($Root, [StringComparison]::OrdinalIgnoreCase) -or
$Path.StartsWith($Root + '\', [StringComparison]::OrdinalIgnoreCase)
}
# Use Win32 Unicode APIs with extended paths: PowerShell 5.1's provider can
# fail while enumerating the very paths this script is intended to repair.
if (-not ('Emberkom.OneDrivePathNativeV1' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Emberkom {
public static class OneDrivePathNativeV1 {
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct Entry {
public uint Attributes;
public System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Write;
public uint SizeHigh, SizeLow, Tag, Reserved;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)] public string Name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)] public string AlternateName;
public bool Directory { get { return (Attributes & 16) != 0; } }
public bool UnsupportedReparse { get {
return (Attributes & 1024) != 0 && (Tag & 0xFFFF0FFFu) != 0x9000001Au;
} }
}
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
static extern IntPtr FindFirstFileW(string path, out Entry data);
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
static extern bool FindNextFileW(IntPtr handle, out Entry data);
[DllImport("kernel32.dll", SetLastError=true)] static extern bool FindClose(IntPtr handle);
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
static extern bool MoveFileW(string source, string destination);
static string Extended(string path) { return @"\\?\" + path; }
public static Entry Inspect(string path) {
Entry data;
IntPtr h = FindFirstFileW(Extended(path), out data);
if (h == new IntPtr(-1)) {
int error = Marshal.GetLastWin32Error();
throw new Win32Exception(error, new Win32Exception(error).Message + ": " + path);
}
try { return data; } finally { FindClose(h); }
}
public static Entry[] List(string directory) {
Entry data;
IntPtr h = FindFirstFileW(Extended(directory) + @"\*", out data);
if (h == new IntPtr(-1)) {
int error = Marshal.GetLastWin32Error();
if (error == 2) return new Entry[0]; // Empty directory.
throw new Win32Exception(error, new Win32Exception(error).Message + ": " + directory);
}
var entries = new List<Entry>();
try {
do { if (data.Name != "." && data.Name != "..") entries.Add(data); }
while (FindNextFileW(h, out data));
int error = Marshal.GetLastWin32Error();
if (error != 18) throw new Win32Exception(error, new Win32Exception(error).Message + ": " + directory);
} finally { FindClose(h); }
return entries.ToArray();
}
public static void Rename(string source, string destination) {
// MoveFileW refuses an existing destination; never replace a file.
if (!MoveFileW(Extended(source), Extended(destination))) {
int error = Marshal.GetLastWin32Error();
throw new Win32Exception(error, new Win32Exception(error).Message + ": " + source);
}
}
}
}
'@
}
function Assert-PrepAncestors([string]$Path) {
$parts = $Path.Split('\')
$prefix = $parts[0]
for ($i = 1; $i -lt $parts.Length; $i++) {
$prefix += '\' + $parts[$i]
$entry = [Emberkom.OneDrivePathNativeV1]::Inspect($prefix)
if ($entry.UnsupportedReparse) { throw "Unsupported reparse point (including junction/symlink): $prefix" }
if (-not $entry.Directory) { throw "Not a directory: $prefix" }
}
}
# Resolve the selected user's settings, never SYSTEM's Documents or OneDrive.
$folderPaths = $settings.KnownFolderPaths
$oneDrive = [string]$settings.OneDriveRoot
$profile = [string]$settings.UserProfilePath
if ($null -eq $folderPaths -or [string]::IsNullOrWhiteSpace($oneDrive)) {
$currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
if ([string]::IsNullOrWhiteSpace($profile)) {
if ($currentSid -in @('S-1-5-18','S-1-5-19','S-1-5-20')) {
throw 'When running as SYSTEM/service account, specify UserProfilePath (or all KnownFolderPaths and OneDriveRoot).'
}
$profile = $env:USERPROFILE
}
$profile = ConvertTo-PrepPath $profile
$profiles = @(Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' |
Where-Object {
$p = Get-ItemProperty -LiteralPath $_.PSPath
$p.PSObject.Properties['ProfileImagePath'] -and
[Environment]::ExpandEnvironmentVariables([string]$p.ProfileImagePath).TrimEnd('\') -ieq $profile
})
if ($profiles.Count -ne 1) { throw "Cannot uniquely resolve the user profile: $profile" }
$userKey = [Microsoft.Win32.Registry]::Users.OpenSubKey($profiles[0].PSChildName)
if ($null -eq $userKey) {
throw 'The selected user registry hive is not loaded. Sign the user in, or supply all KnownFolderPaths and OneDriveRoot explicitly.'
}
try {
if ([string]::IsNullOrWhiteSpace($oneDrive)) {
$accountsKey = $userKey.OpenSubKey('Software\Microsoft\OneDrive\Accounts')
$roots = @()
if ($accountsKey) {
try {
foreach ($account in $accountsKey.GetSubKeyNames()) {
$accountKey = $accountsKey.OpenSubKey($account)
try {
$value = [string]$accountKey.GetValue('UserFolder')
if ($value) { $roots += $value }
} finally { $accountKey.Dispose() }
}
} finally { $accountsKey.Dispose() }
}
$roots = @($roots | Sort-Object -Unique)
if ($roots.Count -ne 1) { throw 'No unique OneDrive account found. Specify the intended OneDriveRoot.' }
$oneDrive = $roots[0]
}
if ($null -eq $folderPaths) {
$shellKey = $userKey.OpenSubKey('Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders')
if (-not $shellKey) { throw 'User Shell Folders registry key is missing; supply KnownFolderPaths.' }
$folderPaths = @{}
try {
$userVariables = @{}
foreach ($environmentKeyName in @('Environment','Volatile Environment')) {
$environmentKey = $userKey.OpenSubKey($environmentKeyName)
if ($environmentKey) {
try {
foreach ($variableName in $environmentKey.GetValueNames()) {
$userVariables[$variableName] = [string]$environmentKey.GetValue($variableName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
}
} finally { $environmentKey.Dispose() }
}
}
$userVariables.USERPROFILE = $profile
$userVariables.HOMEDRIVE = $profile.Substring(0,2)
$userVariables.HOMEPATH = $profile.Substring(2)
foreach ($pair in @(@('Documents','Personal'), @('Pictures','My Pictures'), @('Desktop','Desktop'))) {
$value = [string]$shellKey.GetValue($pair[1], '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
# Use the selected user's actual environment. The intended
# destination could be a DIFFERENT OneDrive account.
for ($pass = 0; $pass -lt 10 -and $value -match '%[^%]+%'; $pass++) {
$value = [regex]::Replace($value, '%([^%]+)%', [Text.RegularExpressions.MatchEvaluator]{
param($match)
if ($userVariables.ContainsKey($match.Groups[1].Value)) { return $userVariables[$match.Groups[1].Value] }
return $match.Value
})
}
if (-not $value -or $value -match '%[^%]+%') { throw "Cannot resolve $($pair[0]); supply KnownFolderPaths explicitly." }
$folderPaths[$pair[0]] = $value
}
} finally { $shellKey.Dispose() }
}
} finally { $userKey.Dispose() }
}
$oneDrive = ConvertTo-PrepPath $oneDrive
if ($oneDrive.Length -gt 120) { throw 'OneDriveRoot exceeds the documented 120-character sync-root allowance.' }
if ($folderPaths -isnot [hashtable] -or $folderPaths.Count -ne 3) {
throw 'KnownFolderPaths must map all three keys: Documents, Pictures, Desktop.'
}
$mappings = @()
foreach ($name in @('Documents','Pictures','Desktop')) {
if (-not $folderPaths.ContainsKey($name)) { throw "KnownFolderPaths is missing $name." }
$source = ConvertTo-PrepPath $folderPaths[$name]
if (Test-PrepWithin $oneDrive $source) { throw "OneDriveRoot cannot be inside a source folder: $source" }
foreach ($other in $mappings) {
if ((Test-PrepWithin $source $other.Source) -or (Test-PrepWithin $other.Source $source)) {
throw 'Known folder source paths must not overlap.'
}
}
$destination = if (Test-PrepWithin $source $oneDrive) { $source } else { $oneDrive + '\' + $name }
$mappings += [pscustomobject]@{ Name=$name; Source=$source; Destination=$destination }
}
$reportParent = [string]$settings.ReportDirectory
if (-not $reportParent) { $reportParent = Join-Path ([IO.Path]::GetTempPath()) 'OneDrivePathPreparation' }
$reportParent = ConvertTo-PrepPath $reportParent
foreach ($mapping in $mappings) {
if (Test-PrepWithin $reportParent $mapping.Source) { throw 'ReportDirectory must be outside the folders being scanned.' }
}
if (Test-PrepWithin $reportParent $oneDrive) { throw 'ReportDirectory must be outside OneDriveRoot.' }
$runDirectory = Join-Path $reportParent ((Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0,8))
# Reports are intentionally written even in preview / WhatIf mode.
$null = [IO.Directory]::CreateDirectory($runDirectory)
$planPath = Join-Path $runDirectory 'plan.csv'
$resultPath = Join-Path $runDirectory 'results.csv'
$journalPath = Join-Path $runDirectory 'journal.csv'
$rows = [Collections.Generic.List[object]]::new()
$filesScanned = 0
$foldersScanned = 0
function New-PrepRow($Mapping, [string]$Path, [string]$Projected, [string]$Kind, [string]$Status, [string]$Reason) {
$relative = if ($Projected) { $Projected.Substring($oneDrive.Length + 1) } else { '' }
return [pscustomobject][ordered]@{
Folder=$Mapping.Name; Kind=$Kind; Status=$Status; Reason=$Reason
OriginalPath=$Path; NewPath=''; ProjectedPath=$Projected; NewProjectedPath=''
OriginalPathLength=$Path.Length; ProjectedPathLength=$Projected.Length
CloudRelativePathLength=$relative.Length; NewProjectedPathLength=0
}
}
function Test-PrepInvalidName([string]$Name) {
return $Name -match '["*:<>?/\\|\x00-\x1F]' -or $Name -match '^ |[ .]$' -or
$Name -match '^(?i:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\.|$)' -or
$Name -match '(?i)_vti_' -or $Name -match '^(?i:\.lock|desktop\.ini)$' -or $Name.StartsWith('~$')
}
function Get-PrepShortName([string]$Name, [string]$Identity, [int]$Budget, $Used) {
$extension = [IO.Path]::GetExtension($Name)
$stem = $Name.Substring(0, $Name.Length - $extension.Length)
$sha = [Security.Cryptography.SHA256]::Create()
try { $hash = [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Identity))).Replace('-','').Substring(0,8).ToLowerInvariant() }
finally { $sha.Dispose() }
for ($attempt = 0; $attempt -lt 10000; $attempt++) {
$suffix = '~' + $hash
if ($attempt) { $suffix += '-' + $attempt }
$keep = [Math]::Min($stem.Length, $Budget - $extension.Length - $suffix.Length)
if ($keep -lt 1) { return $null }
if ([char]::IsHighSurrogate($stem[$keep - 1])) { $keep-- }
if ($keep -lt 1) { return $null }
$candidate = $stem.Substring(0, $keep).TrimEnd(' ','.') + $suffix + $extension
if (-not (Test-PrepInvalidName $candidate) -and $Used.Add($candidate)) { return $candidate }
}
return $null
}
foreach ($mapping in $mappings) {
Write-Host "Scanning $($mapping.Name): $($mapping.Source) -> $($mapping.Destination)"
try { Assert-PrepAncestors $mapping.Source }
catch {
$rows.Add((New-PrepRow $mapping $mapping.Source $mapping.Destination 'Folder' 'ScanError' $_.Exception.Message))
continue
}
$queue = [Collections.Generic.Queue[string]]::new()
$queue.Enqueue($mapping.Source)
while ($queue.Count) {
$directory = $queue.Dequeue()
$projectedDirectory = $mapping.Destination + $directory.Substring($mapping.Source.Length)
$cloudDirectory = $projectedDirectory.Substring($oneDrive.Length + 1)
$foldersScanned++
if ($directory.Length -gt $maxPath -or $projectedDirectory.Length -gt $maxPath -or $cloudDirectory.Length -gt 400) {
$rows.Add((New-PrepRow $mapping $directory $projectedDirectory 'Folder' 'NeedsFolderCleanup' 'Folder path exceeds the length budget; shorten ancestor folders or reduce nesting.'))
}
try { $entries = @([Emberkom.OneDrivePathNativeV1]::List($directory) | Sort-Object Name) }
catch {
$rows.Add((New-PrepRow $mapping $directory $projectedDirectory 'Folder' 'ScanError' $_.Exception.Message))
continue
}
$used = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($entry in $entries) { $null = $used.Add($entry.Name) }
foreach ($entry in $entries) {
$path = $directory + '\' + $entry.Name
$projected = $projectedDirectory + '\' + $entry.Name
$kind = if ($entry.Directory) { 'Folder' } else { 'File' }
if ($entry.UnsupportedReparse) {
$rows.Add((New-PrepRow $mapping $path $projected $kind 'SkippedReparsePoint' 'Junction, symlink, or unsupported reparse point; subtree not scanned.'))
continue
}
if (Test-PrepInvalidName $entry.Name) {
$rows.Add((New-PrepRow $mapping $path $projected $kind 'InvalidName' 'Non-length OneDrive name restriction; review manually (desktop.ini and Office lock files normally do not sync).'))
}
if ($entry.Directory) {
if ($entry.Name.Length -gt $maxName) {
$rows.Add((New-PrepRow $mapping $path $projected $kind 'NeedsFolderCleanup' 'Folder name exceeds MaxNameLength; review manually.'))
}
$queue.Enqueue($path)
continue
}
$filesScanned++
$budget = [Math]::Min($maxName, [Math]::Min($maxPath - $directory.Length - 1,
[Math]::Min($maxPath - $projectedDirectory.Length - 1, 400 - $cloudDirectory.Length - 1)))
if ($entry.Name.Length -le $budget -or (Test-PrepInvalidName $entry.Name)) { continue }
$row = New-PrepRow $mapping $path $projected 'File' 'Planned' 'Filename exceeds the current/projected path or filename length budget.'
$newName = Get-PrepShortName $entry.Name $path $budget $used
if (-not $newName) {
$row.Status = 'NeedsFolderCleanup'
$row.Reason = 'Not enough room for a stem, collision suffix, and unchanged extension. Shorten ancestor folders or reduce nesting.'
} else {
$row.NewPath = $directory + '\' + $newName
$row.NewProjectedPath = $projectedDirectory + '\' + $newName
$row.NewProjectedPathLength = $row.NewProjectedPath.Length
}
$rows.Add($row)
}
}
}
# Always keep a plan on disk before the first file is renamed.
function Export-PrepRows([string]$Path) {
if ($rows.Count) { $rows | Export-Csv -LiteralPath $Path -NoTypeInformation -Encoding UTF8 -WhatIf:$false }
else {
$header = (New-PrepRow $mappings[0] '' '' '' '' '' | ConvertTo-Csv -NoTypeInformation)[0]
[IO.File]::WriteAllText($Path, $header + [Environment]::NewLine, [Text.UTF8Encoding]::new($true))
}
}
Export-PrepRows $planPath
$scanErrors = @($rows | Where-Object Status -eq 'ScanError').Count
$journal = $null
try {
if ($apply -and $scanErrors -eq 0) {
$stream = [IO.FileStream]::new($journalPath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
$journal = [IO.StreamWriter]::new($stream, [Text.UTF8Encoding]::new($true))
$journal.WriteLine('"UtcTime","Status","OriginalPath","NewPath","Message"')
$journal.Flush(); $stream.Flush($true)
}
function Write-PrepJournal($Row, [string]$Status, [string]$Message) {
$record = [pscustomobject][ordered]@{ UtcTime=[DateTime]::UtcNow.ToString('o'); Status=$Status; OriginalPath=$Row.OriginalPath; NewPath=$Row.NewPath; Message=$Message }
$journal.WriteLine(($record | ConvertTo-Csv -NoTypeInformation)[1])
$journal.Flush(); $stream.Flush($true)
}
foreach ($row in $rows) {
if ($row.Status -ne 'Planned') { continue }
if (-not $apply) { $row.Status = 'Preview'; continue }
if ($scanErrors) { $row.Status = 'NotApplied'; $row.Reason = 'Scan errors prevent all renames in this run.'; continue }
if (-not $Caller.ShouldProcess($row.OriginalPath, "Rename to $($row.NewPath)")) { $row.Status = 'NotApplied'; continue }
# Write intent durably BEFORE mutating. A journal failure stops the run.
Write-PrepJournal $row 'Pending' ''
try {
$parent = $row.OriginalPath.Substring(0, $row.OriginalPath.LastIndexOf('\'))
Assert-PrepAncestors $parent
$current = [Emberkom.OneDrivePathNativeV1]::Inspect($row.OriginalPath)
if ($current.Directory -or $current.UnsupportedReparse) { throw 'Source became a directory or unsupported reparse point after planning.' }
[Emberkom.OneDrivePathNativeV1]::Rename($row.OriginalPath, $row.NewPath)
$row.Status = 'Renamed'
} catch {
$row.Status = 'RenameFailed'; $row.Reason = $_.Exception.Message
}
Write-PrepJournal $row $row.Status $row.Reason
}
} finally {
if ($journal) { $journal.Dispose() }
Export-PrepRows $resultPath
}
$renamed = @($rows | Where-Object Status -eq 'Renamed').Count
$previewed = @($rows | Where-Object Status -eq 'Preview').Count
$unresolved = @($rows | Where-Object { $_.Status -notin @('Renamed','Preview') }).Count
Write-Host "Scanned $filesScanned files / $foldersScanned folders. Preview: $previewed. Renamed: $renamed. Review needed: $unresolved."
Write-Host "Results: $resultPath"
if ($scanErrors) { Write-Warning 'Scan incomplete. No files were renamed. Resolve ScanError rows and rerun.' }
if ($unresolved) { Write-Warning 'Review unresolved/skipped rows; this run does not establish OneDrive backup readiness.' }
[pscustomobject]@{
Mode=$(if ($apply) { 'Apply' } else { 'Preview' }); FilesScanned=$filesScanned; FoldersScanned=$foldersScanned
Previewed=$previewed; Renamed=$renamed; ReviewNeeded=$unresolved; ScanErrors=$scanErrors
ReportDirectory=$runDirectory; PlanPath=$planPath; ResultPath=$resultPath
JournalPath=$(if ($journal) { $journalPath } else { $null })
}
} $Options $PSCmdlet
+12 -3
View File
@@ -83,6 +83,12 @@ These follow Microsoft's deployment guidance for [Teams](https://learn.microsoft
New Outlook, and Teams when selected, are provisioned for current and future users; users may need to sign out and back in for registration. OneDrive installs per-machine and handles migration of existing user accounts. App account setup and any tenant policy prompts are separate from the silent installation. The script does not switch the default mail application, force migration from classic Outlook, or configure OneDrive folder backup.
Teams now uses a [unified app for work, school, and personal accounts](https://techcommunity.microsoft.com/blog/microsoftteamsblog/unified-teams-app-for-work-personal-and-education-accounts-is-now-available-on-a/4217988). `teamsbootstrapper.exe -p` is Microsoft's business deployment method; verification requires the Microsoft-published `MSTeams` package and logs its package identity. The old personal-only `MicrosoftTeams` package does not satisfy that check. Users should add/select their licensed work or school account; a personal account can show the Teams Free experience in the same unified app. The script does not choose a Teams account or change sign-in policy.
A window that offers **Get Microsoft Teams (work or school)** does not by itself identify the installed package. Check the running executable path: `WindowsApps\MSTeams_<version>\ms-teams.exe` identifies the current client; do not attribute that window to an older personal-client process. Microsoft [documents support for personal and work/school accounts in the downloaded app](https://support.microsoft.com/en-us/teams/platform/how-do-i-get-microsoft-teams). Test **Create or use another account** with the licensed work account and record any actual sign-in error before changing deployment or sign-in policy. Machine provisioning alone does not prove a user's work-account sign-in succeeds.
Shutdown detection includes `Teams.exe`, `msteams.exe` (older personal/Windows Chat), and `ms-teams.exe`: `Abort` reports these running apps, while an actual deployment with `Force` closes them before removal. Earlier script versions omitted `msteams.exe`; this omission can leave that older process running, but does not explain a window confirmed to be running from `MSTeams\ms-teams.exe`. A sign-out/sign-in or restart can finish session/app registration changes; it is not a guaranteed fix for an unexplained sign-in screen.
Removal starts with the separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. ODT then runs `setup.exe /configure remove.xml` with `<Remove All="TRUE" />` and `<Display Level="None" AcceptEULA="TRUE" />` to remove Click-to-Run Office, Visio, and Project without installation UI. The XML honors `OfficeAppShutdown`; `Abort` does not silently become `Force`. The script waits for setup to exit and verifies that non-MSI Office registrations disappear, allowing up to five minutes for registration changes. It skips this separate pass when only MSI Office, or no Office, is detected. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options).
Legacy MSI Office is handled by `<RemoveMSI />` in `install.xml`: ODT removes those products before installing the replacement suite in the same operation. Microsoft's [RemoveMSI guidance](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/upgrade-from-msi-version) covers Office, Visio, and Project 2007/2010/2013/2016. The script does not assume that a standalone `RemoveMSI` configuration without an installation is supported. Consequently, MSI Office can still be present during our identity/user-cleanup phase. After ODT finishes installation, the script verifies that detected MSI Office registrations are gone and the requested new product/version is installed. A completed MSI migration reports `3010` because a restart is required to finish removal, even if ODT returns zero.
@@ -98,6 +104,7 @@ Transient failures get bounded recovery before deployment stops:
- After successful operations, machine removal and installation verification allow up to five minutes of polling for registry/package state to settle. The standalone user's Teams add-in verification retains its 60-second allowance. Reads that fail still raise an error; inaccessible state is not treated as proof that an app is gone.
- Appx removal checks whether the exact package disappeared even when the removal command reports an error. If it remains, removal retries up to three times, each followed by the verification wait. Installed and provisioned packages must both be absent before continuing.
- A process that exits just before forced shutdown is tolerated. Failure to unregister an already-completed cleanup task is logged and does not stop installation; its completion marker makes subsequent task runs a no-op.
- Failure to create/register a user's cleanup task is logged with its SID, profile path, and error, then scheduling continues for the remaining profiles and Office installation proceeds. This handles stale profiles whose accounts no longer resolve, without assuming that every unresolved account has been deleted. Registration failures remain visible in the receipt and are not described as tasks waiting for sign-in. Active cleanup and its transition lock must still finish before installation to prevent concurrent uninstall/install operations.
Retries and waits are recorded in the diagnostic log. Persistent failures still stop the run with an error; these recovery paths do not turn incomplete deployment into success. Retry counts and delays are grouped in `Get-OfficeDeploymentDefinitions`; the standalone user helper has its MSI retry settings in `Get-OfficeUserCleanupDefinitions`.
@@ -115,6 +122,8 @@ Windows work/school registration, WAM/AAD BrokerPlugin, generic Windows credenti
A deployment is reported as **InstalledWithUserCleanupPending** if any user task has not completed. Failed tasks also remain pending and retry on later sign-ins. The helper writes `Status=Complete` under `HKCU\Software\Emberkom\OfficeDeployment\<deployment-id>` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later retain their previous behavior: they remain registered but do no further work after success. An administrator can confirm completion and remove those exact tasks and their helper afterward. There is no daily housekeeping task.
If any cleanup task could not be registered, successful installation instead returns **InstalledWithUserCleanupIncomplete** with `UserCleanupRegistrationFailures` entries containing `SID`, `ProfilePath`, and `Error`. `PendingUserSids` still lists only registered tasks awaiting completion. Signing in alone cannot retry a missing task: review whether the profile belongs to a deleted account or whether account lookup/task registration needs repair. The script does not delete profiles or grant a different account access to their credentials. The machine-side Office identity/cache cleanup still runs before task registration.
The helper, lock, and reinstall marker for these previously agreed logon tasks live separately in `%ProgramData%\EmberkomOfficeDeployment\<deployment-id>`, so routine temp cleanup cannot break deferred user cleanup. The receipt identifies this folder as `UserCleanupWorkspace`. If no user tasks remain at the end of a successful deployment, the script removes this helper folder too. It is the only deployment code intentionally retained for pending users; the main installer does not persist on the endpoint.
## Temporary media and cleanup during deployment
@@ -134,10 +143,10 @@ Earlier ProgramData caches are not searched for reuse in the new temp location.
| --- | --- |
| `0` | `ValidationPassed`: validation only, no deployment performed. `Installed`: Office and companion installations verified; user cleanup completed for the enumerated profiles. |
| `1` | Failure; inspect the error and logs. In deployment mode, removal may already have happened. |
| `2` | Office and companion apps installed, but user cleanup is pending. Sign in as the listed users and inspect task results; do not repeatedly reinstall merely to check status. |
| `3010` | A restart is required. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; `Installed` or `InstalledWithUserCleanupPending` means Office and companions completed with a restart deferred until afterward. `RestartRequired=true` and `DeferReboot` are included; a stop before installation also identifies `RestartStage`. Pending user SIDs can also be present. |
| `2` | Office and companion apps installed, but user cleanup is pending or incomplete. `InstalledWithUserCleanupPending`: sign in as the listed `PendingUserSids` and inspect task results. `InstalledWithUserCleanupIncomplete`: also review `UserCleanupRegistrationFailures`; those users do not have a registered cleanup task. Do not repeatedly reinstall merely to check status. |
| `3010` | A restart is required. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; any `Installed*` status means Office and companions completed with a restart deferred until afterward. `RestartRequired=true` and `DeferReboot` are included; a stop before installation also identifies `RestartStage`. Pending user SIDs and task registration failures can also be present. |
Syncro may flag nonzero results as errors; read the printed status and pending SIDs. Schedule any required restart separately. The script also returns `3010` after verified legacy MSI Office removal, following Microsoft's restart requirement.
Syncro may flag nonzero results as errors; read the printed status, pending SIDs, and task registration failures. Schedule any required restart separately. The script also returns `3010` after verified legacy MSI Office removal, following Microsoft's restart requirement.
If machine companion removal still fails verification, the error identifies the remaining component, version, and registry location, along with the uninstall log folder. The main log also records which add-in registrations were left to user cleanup. An uninstall exit code of `1605` alone does not establish that all users' installations are gone; Windows Installer context determines which stage handles the add-in. This failure occurs before Office removal, identity reset, and reinstallation, but companion apps may already have been removed.
+193
View File
@@ -0,0 +1,193 @@
# Prepare known-folder paths for OneDrive
`Repair-OneDriveKnownFolderPaths.ps1` scans Documents, Pictures, and Desktop and
proposes shorter filenames where their names or full paths exceed a length
budget. Preview is the default. Apply mode renames files **in place**; it does not
move files, rename folders, configure OneDrive, or enable folder backup.
## Preview, review, apply
Run in Windows PowerShell 5.1 or PowerShell 7 on Windows. For another user, run
with access to that user's files and registry hive. Close applications using the
affected files and pause OneDrive sync while applying renames. Renaming can break
shortcuts, application references, and links that depend on the original name.
```powershell
$options = @{
UserProfilePath = 'C:\Users\Jane'
OneDriveRoot = 'C:\Users\Jane\OneDrive - Contoso'
Apply = $false
ReportDirectory = 'C:\ProgramData\Emberkom\Output\OneDrivePathPreparation'
}
$preview = .\Repair-OneDriveKnownFolderPaths.ps1 -Options $options
Import-Csv -LiteralPath $preview.ResultPath |
Format-Table Status, OriginalPath, NewPath -Wrap
# After reviewing the proposed filenames and unresolved rows:
$options.Apply = $true
$result = .\Repair-OneDriveKnownFolderPaths.ps1 -Options $options
```
`-WhatIf` also suppresses renames when `Apply` is true; diagnostic reports are
still written. Each invocation rescans and creates a new plan, so an apply run
can differ from an earlier preview if the files have changed.
When running as the affected user, `UserProfilePath` can be omitted. When only
one OneDrive account is configured, `OneDriveRoot` can also be omitted. An
ambiguous or missing account requires an explicit destination. SYSTEM and
service accounts must identify a target profile; the script never guesses the
logged-on user or scans every profile.
The target profile's loaded `User Shell Folders` registry key resolves redirected
folders. Its own environment values resolve variables such as `%USERPROFILE%`
and `%OneDriveCommercial%`. If its hive is not loaded, sign the user in or supply
all source paths explicitly (no registry hive is loaded by this script):
```powershell
$options.KnownFolderPaths = @{
Documents = 'D:\UserData\Jane\Documents'
Pictures = 'D:\UserData\Jane\Pictures'
Desktop = 'D:\UserData\Jane\Desktop'
}
# OneDriveRoot must also be explicit to bypass registry discovery completely.
```
Use actual known folder locations, especially when backup is already partially
enabled. Paths must be absolute local drive paths. Overlapping source roots,
network paths, and reports inside the scanned folders or destination are rejected.
## Length limits and rename behavior
[Microsoft documents](https://support.microsoft.com/en-us/onedrive/what-are-file-path-length-limits)
a 400-character cloud path limit, 255-character individual names, and a
520-character combined sync path with a root allowance of 120 characters.
Windows applications can impose shorter limits.
The script defaults to **240 characters for both the current and projected local
path**, leaving room below common Windows path limits. This is a conservative
operational default, not OneDrive's cloud limit; it can propose renaming files
that OneDrive itself would accept. `MaxPathLength` accepts 40–520, and
`MaxNameLength` accepts 16–255 (default 255). The 400-character path relative to
the OneDrive root is always enforced independently. These checks do not guarantee
compatibility with every application's own limits.
For folders outside the chosen OneDrive root, the projection is
`OneDriveRoot\Documents`, `OneDriveRoot\Pictures`, or `OneDriveRoot\Desktop`, plus
the existing relative path. Folders already beneath that root retain their
existing relative location. Review this assumption against the intended backup
layout before applying changes.
Only over-budget filenames are shortened. The script retains a readable prefix,
adds `~` and eight deterministic hash characters, and preserves the final
extension. For example: `Long proposal title~1a2b3c4d.docx`. Further suffixes resolve
collisions with existing files, directories, or other proposed names. It never
overwrites a destination. A filename must have room for at least one prefix
character, the suffix, and its extension. If it cannot fit, the file is reported
as `NeedsFolderCleanup` without changing it. A leading-dot file whose entire
name is treated as an extension may also require manual cleanup.
Folder names and nesting are never changed automatically. Long folder paths,
including empty folders, are reported. Hidden/system entries are included.
Unicode extended-path Windows APIs allow existing paths longer than 260
characters to be enumerated and renamed without changing Windows policy.
Junctions, symlinks, and unknown reparse points are skipped, including their
subtrees. Modern Cloud Files placeholders are allowed; no file contents are read
by the preparation script. An unavailable cloud provider or a locked file may
still prevent enumeration or renaming and will be reported.
## Reports and failures
Each run writes a unique directory beneath `ReportDirectory` (default:
`%TEMP%\OneDrivePathPreparation` for the executing account):
- `plan.csv`: original paths, proposed paths, projected OneDrive paths, lengths,
and issues; written before any rename.
- `results.csv`: the outcome for each proposed rename or issue. Files already
within budget are omitted, but counted in the summary.
- `journal.csv`: apply runs record `Pending` before each rename and its outcome
afterward; each record is flushed to disk. Keep this with the plan/results.
Statuses include `Preview`, `Renamed`, `NeedsFolderCleanup`, `InvalidName`,
`SkippedReparsePoint`, `ScanError`, `NotApplied`, and `RenameFailed`. Invalid-name
rows flag common non-length restrictions without fixing them. `desktop.ini` and
Office lock files may be expected exclusions; this is not a complete OneDrive
readiness audit.
Any `ScanError` prevents **all** renames in that run. Other unresolved items are
reported while fixable filenames can still be renamed. Individual rename
failures are recorded and the run continues. Report/journal write failures stop
the run. Existing successful renames are not rolled back automatically. After an
interruption, a final `Pending` journal row means the rename outcome is uncertain;
check both paths. Original names in the reports support manual restoration,
provided the old path is unoccupied. Protect reports as they contain user paths.
The returned summary includes `FilesScanned`, `FoldersScanned`, `Previewed`,
`Renamed`, `ReviewNeeded`, `ScanErrors`, and report paths. `ReviewNeeded` counts
issue rows, not unique files. RMM runs print these counts and the results path;
review them even when PowerShell exits normally. After resolving remaining
issues, resume sync, enable/retry OneDrive folder backup, and verify its status.
This script does not certify that cloud backup completed.
## RMM caller
Publish the main script, then upload/paste
[the caller](../rmm/Repair-OneDriveKnownFolderPaths.ps1) into Syncro as a Windows
PowerShell 5.1 script with **Run As: System**. As with the Microsoft 365 installer,
configure individual script variables in the RMM; the caller does not assign or
overwrite their values. Enter variable names without `$`.
| Variable | Value / recommended default |
| --- | --- |
| `UserProfilePath` | Target profile, e.g. `C:\Users\Jane`; required for the normal SYSTEM workflow |
| `OneDriveRoot` | Intended destination, e.g. `C:\Users\Jane\OneDrive - Contoso` |
| `Apply` | Dropdown: `false`, `true`; default **`false`** (preview) |
| `MaxPathLength` | `240`; allowed range 40–520 |
| `MaxNameLength` | `255`; allowed range 16–255 |
| `ReportDirectory` | `C:\ProgramData\Emberkom\Output\OneDrivePathPreparation` |
| `DocumentsPath` | Optional source override; default `Auto` |
| `PicturesPath` | Optional source override; default `Auto` |
| `DesktopPath` | Optional source override; default `Auto` |
All values are strings. Every variable configured in Syncro needs a nonempty
value. The three source overrides can be omitted from the RMM entirely; if added,
use `Auto` for all three to discover the user's folders, or provide all three
absolute paths. Partial overrides fail before scanning. Explicit source paths
plus `OneDriveRoot` permit scanning without a loaded user registry hive.
First run with `Apply=false`, inspect the CSV, then select `true` to apply renames.
The caller only bootstraps Tools and runs:
```powershell
Run-Script -LivePSScript Repair-OneDriveKnownFolderPaths
```
The core reads the individual shared variables without changing them. Missing
or blank values use the core defaults: preview, 240/255 length limits, and reports
under the executing account's temp directory. Missing profile/OneDrive inputs
follow the discovery and SYSTEM restrictions described above. The RMM's suggested
report path above takes effect when supplied as `ReportDirectory`.
Standalone `-Options` still takes precedence. If it is absent and any of these
individual variables exist, they form the complete configuration with defaults;
the legacy `$OneDrivePrepOptions` hashtable is used only when no individual inputs
exist. This prevents a stale legacy `Apply=true` from enabling changes when a new
RMM caller omits `Apply`.
`Tools.ps1` is unchanged. Apply accepts Boolean values or RMM strings
`true`, `$true`, `yes`, `y`, `1`; `false`, `$false`, `no`, `n`, `0`, blank, and null
disable changes. Unknown values fail before scanning. Option-name typos also fail.
## Offline verification
```powershell
powershell.exe -NoProfile -File .\tests\Repair-OneDriveKnownFolderPaths.Tests.ps1
pwsh.exe -NoProfile -File .\tests\Repair-OneDriveKnownFolderPaths.Tests.ps1
```
Tests use synthetic files in a unique scratch directory under the repository,
then remove that directory. They cover preview/apply, real paths longer than 260
characters, collisions, preserved contents/extensions, projected destination
length, Unicode, deep-folder reporting, WhatIf, incomplete scans, repeat runs,
the rename journal, and RMM shared-scope execution (individual string variables,
defaults, precedence, and legacy callers) with downloads replaced by local fixtures.
They do not contact OneDrive or verify cloud synchronization.
+19
View File
@@ -0,0 +1,19 @@
#Requires -Version 5.1
# Upload this shim to Syncro. Windows PowerShell 5.1; Run As: System.
# See docs/OneDrive-PathPreparation.md. Configure these string variables in Syncro:
# [string]$UserProfilePath - Required target profile, e.g. C:\Users\Jane
# [string]$OneDriveRoot - Intended sync root, e.g. C:\Users\Jane\OneDrive - Contoso
# [string]$Apply - Dropdown: false (default: preview), true (rename files)
# [string]$MaxPathLength - 240 (default); allowed range 40-520
# [string]$MaxNameLength - 255 (default); allowed range 16-255
# [string]$ReportDirectory - e.g. C:\ProgramData\Emberkom\Output\OneDrivePathPreparation
# Optional source overrides, each defaulting to Auto; supply all three paths or none:
# [string]$DocumentsPath, [string]$PicturesPath, [string]$DesktopPath
# Every variable configured in Syncro needs a nonempty value. Do not overwrite
# injected values here. The main script reads them directly and converts Apply.
# Use Apply=false first and review the CSV before selecting true.
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
Run-Script -LivePSScript Repair-OneDriveKnownFolderPaths
+64 -7
View File
@@ -118,6 +118,24 @@ try {
}
}
}
& {
# Personal Teams has a different process name from both classic and current Teams.
# Exercise detection and both shutdown choices without touching real processes.
function Get-Process {
param($Name,$ErrorAction)
foreach ($candidate in @('Teams','msteams','ms-teams','unrelated')) {
if ($candidate -in $Name) { [pscustomobject]@{ProcessName=$candidate; Id=123; HasExited=$false} }
}
}
function Stop-Process { param($InputObject,[switch]$Force,$ErrorAction) $script:stoppedTeams += $InputObject.ProcessName }
$script:stoppedTeams=@()
$running = @(Get-OfficeRunningApps)
Assert-OfficeTest ($running.Count -eq 3 -and 'msteams' -in $running.ProcessName -and 'unrelated' -notin $running.ProcessName) 'Running-app detection must include personal Teams without broad process matching.'
Assert-OfficeThrows { Stop-OfficeDeploymentApps ([pscustomobject]@{OfficeAppShutdown='Abort'}) } 'Apps are running:.*msteams'
Assert-OfficeTest ($script:stoppedTeams.Count -eq 0) 'Abort must not close any Teams client.'
Stop-OfficeDeploymentApps ([pscustomobject]@{OfficeAppShutdown='Force'})
Assert-OfficeTest ($script:stoppedTeams.Count -eq 3 -and 'msteams' -in $script:stoppedTeams) 'Force must close the older personal Teams client along with classic/current Teams.'
}
& {
function Get-OfficeRunningApps { [pscustomobject]@{Id=123; HasExited=$script:appHasExited} }
function Stop-Process { throw 'Process is gone or access was denied.' }
@@ -306,7 +324,8 @@ try {
function Get-AppxProvisionedPackage {
param([switch]$Online,$ErrorAction)
if ($script:appMode -eq 'delayed-success') { $script:packageChecks[$script:lastInstalledApp]++; if ($script:packageChecks[$script:lastInstalledApp] -lt 3) { return } }
if ($script:appMode -ne 'missing-Teams') { [pscustomobject]@{DisplayName='MSTeams'; PackageName='MSTeams_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} }
if ($script:appMode -eq 'personal-Teams-only') { [pscustomobject]@{DisplayName='MicrosoftTeams'; PackageName='MicrosoftTeams_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} }
elseif ($script:appMode -ne 'missing-Teams') { [pscustomobject]@{DisplayName='MSTeams'; PackageName='MSTeams_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} }
if ($script:appMode -ne 'missing-NewOutlook') { [pscustomobject]@{DisplayName='Microsoft.OutlookForWindows'; PackageName='Microsoft.OutlookForWindows_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} }
}
function Get-OfficeMachineOneDrive {
@@ -315,7 +334,7 @@ try {
}
function Assert-OfficeMicrosoftSignature { }
$media = @{WebView2='WebView2'; OneDrive='OneDrive'; Teams='Teams'; NewOutlook='NewOutlook'}
foreach ($script:appMode in @('success','delayed-success','reboot','fail-WebView2','fail-OneDrive','fail-Teams','fail-NewOutlook','missing-OneDrive','missing-Teams','missing-NewOutlook')) {
foreach ($script:appMode in @('success','delayed-success','reboot','fail-WebView2','fail-OneDrive','fail-Teams','fail-NewOutlook','missing-OneDrive','missing-Teams','missing-NewOutlook','personal-Teams-only')) {
$script:webViewPresent = $false; $script:appCalls = @(); $failure = $null; $result = $null
$script:webViewChecks=0; $script:oneDriveChecks=0; $script:packageChecks=@{}
try { $result = Install-OfficeCompanionApps $media $testRoot -InstallTeams $true } catch { $failure = $_ }
@@ -326,6 +345,7 @@ try {
Assert-OfficeTest (($script:appCalls -join '|') -eq 'WebView2 /silent /install|OneDrive /allusers /silent|Teams -p|NewOutlook --provision true --quiet --start-') 'Companion installers must run silently and for all users.'
} else {
Assert-OfficeTest ($null -ne $failure) "Companion failure was swallowed: $script:appMode"
if ($script:appMode -eq 'personal-Teams-only') { Assert-OfficeTest ($failure.Exception.Message -match 'Teams setup returned success but the app was not provisioned') 'Legacy personal MicrosoftTeams must not satisfy MSTeams verification.' }
if ($script:appMode -notlike '*NewOutlook') { Assert-OfficeTest (!($script:appCalls -match '^NewOutlook ')) 'Install continued after a companion failure.' }
}
}
@@ -645,12 +665,34 @@ try {
function Get-ItemPropertyValue { param($LiteralPath,$Name,$ErrorAction) if ($LiteralPath -like '*logged-on*') { 'Complete' } }
function Unregister-ScheduledTask { param($TaskName,$Confirm,$ErrorAction) $script:removed += $TaskName }
$profiles = @([pscustomobject]@{SID='logged-on'; Loaded=$true},[pscustomobject]@{SID='logged-off'; Loaded=$false})
$pending = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32))
$cleanup = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32))
Assert-OfficeTest ($script:registered.Count -eq 2 -and $script:started.Count -eq 1 -and $script:removed.Count -eq 1) 'User scheduling or completed task cleanup is incorrect.'
Assert-OfficeTest ($pending.Count -eq 1 -and $pending[0] -eq 'logged-off') 'Logged-off user cleanup was reported complete.'
Assert-OfficeTest ($cleanup.PendingUserSids.Count -eq 1 -and $cleanup.PendingUserSids[0] -eq 'logged-off' -and $cleanup.RegistrationFailures.Count -eq 0) 'Logged-off user cleanup was reported complete.'
function Unregister-ScheduledTask { throw 'Task Scheduler is temporarily unavailable.' }
$pending = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32))
Assert-OfficeTest ($pending.Count -eq 1 -and $pending[0] -eq 'logged-off') 'Completed task housekeeping must not fail deployment or mark completed cleanup pending.'
$cleanup = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32))
Assert-OfficeTest ($cleanup.PendingUserSids.Count -eq 1 -and $cleanup.PendingUserSids[0] -eq 'logged-off') 'Completed task housekeeping must not fail deployment or mark completed cleanup pending.'
function New-ScheduledTaskPrincipal {
param($UserId,$LogonType,$RunLevel,$ErrorAction)
if ($UserId -eq 'unmapped' -and $script:registrationStage -eq 'principal') { throw 'No mapping between account names and security IDs was done.' }
$UserId
}
function Register-ScheduledTask {
param($TaskName,$Action,$Principal,$Trigger,$Settings,[switch]$Force,$ErrorAction)
if ($Principal -eq 'unmapped') { throw 'No mapping between account names and security IDs was done.' }
$script:registered += $TaskName
}
$unmapped = [pscustomobject]@{SID='unmapped'; LocalPath='C:\Users\defaultuser100000'; Loaded=$true}
foreach ($script:registrationStage in @('principal','register')) {
$script:registered=@(); $script:started=@()
$cleanup = @(Start-OfficeUserCleanup (@($unmapped) + $profiles) ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32)) 2>$null)
Assert-OfficeTest ($cleanup.Count -eq 1 -and $cleanup[0].RegistrationFailures.Count -eq 1) 'An unmapped account must return one structured result with a registration failure.'
Assert-OfficeTest ($cleanup[0].RegistrationFailures[0].SID -eq 'unmapped' -and $cleanup[0].RegistrationFailures[0].ProfilePath -eq $unmapped.LocalPath -and $cleanup[0].RegistrationFailures[0].Error -match 'No mapping') 'Registration failures must identify the affected SID, profile, and actual error.'
Assert-OfficeTest ($script:registered.Count -eq 2 -and $script:started.Count -eq 1) 'An unmapped first profile must not prevent scheduling and starting cleanup for later users.'
Assert-OfficeTest ($cleanup[0].PendingUserSids.Count -eq 1 -and $cleanup[0].PendingUserSids[0] -eq 'logged-off') 'A missing task must not be reported as able to retry at sign-in.'
}
$cleanup = Start-OfficeUserCleanup @() ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32))
Assert-OfficeTest ($cleanup.PendingUserSids.Count -eq 0 -and $cleanup.RegistrationFailures.Count -eq 0) 'An empty profile list must return empty cleanup result arrays.'
Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'Error: User cleanup task registration failed for unmapped \(C:\\Users\\defaultuser100000\)') 'Registration failures must reach the Tools diagnostic log.'
}
# Real temporary files for cache reuse/tampering; no installer or network may run.
@@ -777,7 +819,13 @@ try {
function Remove-OfficeCompanionApps { $script:events += 'companions'; if ($script:mode -eq 'companions') { throw 'companion failure' }; return ($script:mode -eq 'reboot') }
function Remove-OfficeSuite { $script:events += 'remove-office'; if ($script:mode -eq 'remove-office') { throw 'Office removal failure' }; if ($script:mode -eq 'office-reboot') { return 3010 }; return 0 }
function Clear-OfficeProfileIdentity { $script:events += 'identity'; if ($script:mode -eq 'identity') { throw 'identity failure' } }
function Start-OfficeUserCleanup { $script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' }; if ($script:mode -eq 'pending') { return ,@('S-1-5-21-test') }; return ,@() }
function Start-OfficeUserCleanup {
$script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' }
$pending = @(); $failures = @()
if ($script:mode -in @('pending','registration-and-pending')) { $pending = @('S-1-5-21-test') }
if ($script:mode -in @('registration','registration-and-pending','registration-reboot')) { $failures = @([pscustomobject]@{SID='unmapped'; ProfilePath='C:\Users\defaultuser100000'; Error='No mapping'}) }
[pscustomobject]@{PendingUserSids=$pending; RegistrationFailures=$failures}
}
function Set-OfficeReinstallPhase { $script:events += 'phase'; if ($script:mode -eq 'phase') { throw 'user still holds cleanup lock' } }
function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'install') { throw 'install failure' }; return 0 }
function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} }
@@ -802,6 +850,15 @@ try {
$script:mode='cleanup-warning'; $script:events=@()
$result = @(Invoke-OfficeDeployment $options)
Assert-OfficeTest ($result.Count -eq 1 -and $result[0].ArtifactCleanupPending -and $result[0].ExitCode -eq 0 -and $result[0].OfficeDeploymentStatus -eq 'Installed') 'Artifact cleanup problems corrupted the receipt or failed a verified installation.'
foreach ($script:mode in @('registration','registration-and-pending','registration-reboot')) {
$script:events=@(); $script:artifactCleanupRuns=0
function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'registration-reboot') { return 3010 }; return 0 }
$result = Invoke-OfficeDeployment $options
Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'InstalledWithUserCleanupIncomplete' -and $result.UserCleanupRegistrationFailures.Count -eq 1 -and $result.UserCleanupRegistrationFailures[0].SID -eq 'unmapped') 'A task registration failure must remain visible after successful installation.'
Assert-OfficeTest ($result.ExitCode -eq $(if ($script:mode -eq 'registration-reboot') {3010} else {2})) 'Registration failures must report partial completion without hiding a required reboot.'
Assert-OfficeTest ($result.PendingUserSids.Count -eq $(if ($script:mode -eq 'registration-and-pending') {1} else {0})) 'Unregistered tasks must remain distinct from deferred logon tasks.'
Assert-OfficeTest ('install' -in $script:events -and 'install-companions' -in $script:events -and $script:artifactCleanupRuns -eq 1) 'Task registration failure must allow verified installation and staging-file cleanup.'
}
foreach ($script:mode in @('reboot','office-reboot')) {
foreach ($script:removalStillRegistered in @($false,$true)) {
$script:events=@()
@@ -0,0 +1,286 @@
#Requires -Version 5.1
# Offline integration tests; only synthetic files under a unique scratch directory.
$ErrorActionPreference = 'Stop'
$scriptPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'Repair-OneDriveKnownFolderPaths.ps1'
$testParent = Split-Path $PSScriptRoot -Parent
$testRoot = Join-Path $testParent ('odt-' + [guid]::NewGuid().ToString('N').Substring(0,8))
$null = [IO.Directory]::CreateDirectory($testRoot)
function Assert($Condition, [string]$Message) { if (-not $Condition) { throw $Message } }
function New-Fixture([string]$Name) {
$root = Join-Path $testRoot $Name
$folders = @{}
foreach ($folder in @('Documents','Pictures','Desktop')) {
$folders[$folder] = Join-Path $root $folder
$null = [IO.Directory]::CreateDirectory($folders[$folder])
}
return @{
KnownFolderPaths=$folders; OneDriveRoot=(Join-Path $root 'OneDrive - Test')
ReportDirectory=(Join-Path $testRoot 'reports'); Apply='false'; MaxNameLength=80
}
}
function Write-FixtureFile([string]$Path, [string]$Content) {
[IO.File]::WriteAllText(('\\?\' + $Path), $Content)
}
try {
$options = New-Fixture 'basic'
$longA = $options.KnownFolderPaths.Documents + '\' + ('a' * 125) + '.pdf'
$longB = $options.KnownFolderPaths.Documents + '\' + ('a' * 124) + 'b.pdf'
$short = $options.KnownFolderPaths.Pictures + '\keep [1].jpg'
Write-FixtureFile $longA 'first PDF contents'
Write-FixtureFile $longB 'second PDF contents'
Write-FixtureFile $short 'image contents'
$preview = & $scriptPath -Options $options
$rows = @(Import-Csv -LiteralPath $preview.ResultPath)
Assert ($preview.Previewed -eq 2 -and $preview.Renamed -eq 0) 'Default/string-false must preview both long names.'
Assert ([IO.File]::Exists($longA) -and [IO.File]::Exists($longB)) 'Preview changed original files.'
Assert (($rows | Select-Object -ExpandProperty NewPath -Unique).Count -eq 2) 'Truncation must avoid collisions.'
foreach ($row in $rows) {
Assert ($row.NewPath.EndsWith('.pdf')) 'Extension changed.'
Assert ([IO.Path]::GetFileName($row.NewPath).Length -le 80) 'Filename exceeds budget.'
Assert ([int]$row.NewProjectedPathLength -le 240) 'Projected path exceeds budget.'
}
# Occupy a proposed name after preview: planning must choose another name.
$occupied = $rows[0].NewPath
Write-FixtureFile $occupied 'existing destination'
$options.Apply = 'true'
$applied = & $scriptPath -Options $options
Assert ($applied.Renamed -eq 2) 'Apply did not rename both files.'
Assert ([IO.File]::ReadAllText($occupied) -eq 'existing destination') 'An existing destination was overwritten.'
$appliedRows = @(Import-Csv -LiteralPath $applied.ResultPath)
foreach ($row in $appliedRows) {
$expected = if ($row.OriginalPath -eq $longA) { 'first PDF contents' } else { 'second PDF contents' }
Assert ([IO.File]::ReadAllText($row.NewPath) -eq $expected) 'File contents changed during rename.'
Assert (-not [IO.File]::Exists($row.OriginalPath)) 'Old name still exists after rename.'
}
Assert ([IO.File]::ReadAllText($short) -eq 'image contents') 'Short file changed.'
$journal = @(Import-Csv -LiteralPath $applied.JournalPath)
Assert ($journal.Count -eq 4 -and $journal[0].Status -eq 'Pending' -and $journal[1].Status -eq 'Renamed') 'Journal must record intent and outcome.'
$again = & $scriptPath -Options $options
Assert ($again.Renamed -eq 0 -and $again.ReviewNeeded -eq 0) 'Rerun must be idempotent.'
Write-Host 'PASS: preview, collision avoidance, extensions, contents, journal, and idempotence.'
$options = New-Fixture 'long'
$options.MaxNameLength = 255
$nested = $options.KnownFolderPaths.Documents + '\' + ('nested' * 12)
$null = [IO.Directory]::CreateDirectory(('\\?\' + $nested))
$longPath = $nested + '\' + ('report' * 29) + '.xlsx'
Write-FixtureFile $longPath 'long path content'
Assert ($longPath.Length -gt 260) 'Fixture must exceed the traditional Windows path limit.'
$options.Apply = $true
$result = & $scriptPath -Options $options
$renamedRow = @(Import-Csv -LiteralPath $result.ResultPath | Where-Object Status -eq 'Renamed')
Assert ($renamedRow.Count -eq 1) 'Could not enumerate/rename an actual >260-character path.'
Assert ($renamedRow[0].NewPath.Length -le 240 -and $renamedRow[0].NewProjectedPath.Length -le 240) 'Current and projected lengths must both fit.'
Assert ([IO.File]::ReadAllText($renamedRow[0].NewPath) -eq 'long path content') 'Long-path file contents changed.'
Write-Host 'PASS: real >260-character path enumeration and rename.'
$options = New-Fixture 'deep'
$deep = $options.KnownFolderPaths.Documents + '\' + ('d' * 100) + '\' + ('e' * 100)
$null = [IO.Directory]::CreateDirectory(('\\?\' + $deep))
Write-FixtureFile ($deep + '\file.txt') 'deep content'
$options.Apply = $true
$result = & $scriptPath -Options $options
$rows = @(Import-Csv -LiteralPath $result.ResultPath)
Assert ($result.Renamed -eq 0 -and @($rows | Where-Object Status -eq 'NeedsFolderCleanup').Count -ge 1) 'Deep paths must be flagged without changing folders.'
Assert ([Emberkom.OneDrivePathNativeV1]::Inspect($deep + '\file.txt').Name -eq 'file.txt') 'Unfixable file must remain unchanged.'
Write-Host 'PASS: unfixable folder depth reported without renaming folders.'
$options = New-Fixture 'whatif'
$original = $options.KnownFolderPaths.Desktop + '\' + ('x' * 100) + '.txt'
Write-FixtureFile $original 'whatif'
$options.Apply = 'yes'
$result = & $scriptPath -Options $options -WhatIf
Assert ($result.Renamed -eq 0 -and [IO.File]::Exists($original)) 'WhatIf must suppress renames even with Apply=true.'
$options.KnownFolderPaths.Pictures += '\missing'
$result = & $scriptPath -Options $options
Assert ($result.ScanErrors -eq 1 -and $result.Renamed -eq 0 -and [IO.File]::Exists($original)) 'Scan errors must block all renames.'
Write-Host 'PASS: WhatIf and incomplete scans block changes.'
$options = New-Fixture 'projected'
$options.MaxNameLength = 255
$options.MaxPathLength = 200
$parent = $options.KnownFolderPaths.Documents
$nameLength = 200 - $parent.Length - 1
$original = $parent + '\' + ('p' * ($nameLength - 4)) + '.txt'
Write-FixtureFile $original 'projected'
$result = & $scriptPath -Options $options
Assert ($original.Length -eq 200 -and $result.Previewed -eq 1) 'Must account for extra OneDrive destination prefix before migration.'
$options.Apply = 'maybe'
$caught = $false
try { & $scriptPath -Options $options } catch { $caught = $_.Exception.Message -like 'Apply must*' }
Assert $caught 'Ambiguous Apply values must fail closed.'
Write-Host 'PASS: projected destination length and RMM Boolean validation.'
# Literal wildcard characters, UTF-16 boundary, extensionless and dot files.
$options = New-Fixture 'unicode'
$options.MaxNameLength = 40
$emoji = [char]::ConvertFromUtf32(0x1F600)
foreach ($name in @((('a' * 26) + $emoji + ('z' * 45) + '.txt'), (('b' * 80) + '[1]'), ('.' + ('c' * 80)))) {
Write-FixtureFile ($options.KnownFolderPaths.Pictures + '\' + $name) 'unicode'
}
$options.Apply = $true
$result = & $scriptPath -Options $options
$rows = @(Import-Csv -LiteralPath $result.ResultPath)
Assert ($result.Renamed -eq 2 -and $result.ReviewNeeded -eq 1) 'A dotfile with an overlong extension must be reported; other files should rename.'
foreach ($row in @($rows | Where-Object Status -eq 'Renamed')) {
$strictUtf8 = [Text.UTF8Encoding]::new($false, $true)
$null = $strictUtf8.GetBytes($row.NewPath)
Assert ([IO.File]::ReadAllText($row.NewPath) -eq 'unicode') 'Unicode/literal file contents changed.'
}
Write-Host 'PASS: Unicode boundary, literal brackets, extensionless file, and long extension.'
$options = New-Fixture 'locked'
$options.Apply = $true
$original = $options.KnownFolderPaths.Documents + '\' + ('l' * 100) + '.txt'
Write-FixtureFile $original 'locked file'
$locked = [IO.File]::Open($original, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
try { $result = & $scriptPath -Options $options }
finally { $locked.Dispose() }
$rows = @(Import-Csv -LiteralPath $result.ResultPath)
Assert ($result.Renamed -eq 0 -and $rows[0].Status -eq 'RenameFailed') 'Locked file failures must be reported.'
Assert ([IO.File]::ReadAllText($original) -eq 'locked file') 'Failed rename changed file contents.'
$journal = @(Import-Csv -LiteralPath $result.JournalPath)
Assert ($journal.Count -eq 2 -and $journal[1].Status -eq 'RenameFailed') 'Journal must include failed outcome.'
Write-Host 'PASS: locked file is retained and failure is journaled.'
$options = New-Fixture 'cloud'
$options.MaxPathLength = 520
$options.MaxNameLength = 255
$relativeDirectory = 'Documents\' + ('a' * 100) + '\' + ('b' * 100)
$directory = $options.KnownFolderPaths.Documents + $relativeDirectory.Substring('Documents'.Length)
$null = [IO.Directory]::CreateDirectory(('\\?\' + $directory))
$name = ('c' * (401 - $relativeDirectory.Length - 1 - 4)) + '.txt'
Write-FixtureFile ($directory + '\' + $name) 'cloud limit'
$result = & $scriptPath -Options $options
$rows = @(Import-Csv -LiteralPath $result.ResultPath)
Assert ($result.Previewed -eq 1 -and [int]$rows[0].CloudRelativePathLength -eq 401) 'Cloud-relative limit must be enforced independently.'
Assert (($rows[0].NewProjectedPath.Length - $options.OneDriveRoot.Length - 1) -le 400) 'Shortened cloud-relative path exceeds 400.'
Write-Host 'PASS: independent 400-character cloud-relative limit.'
$options = New-Fixture 'links'
$outside = Join-Path $testRoot 'link-target'
$null = [IO.Directory]::CreateDirectory($outside)
$outsideFile = $outside + '\' + ('j' * 100) + '.txt'
Write-FixtureFile $outsideFile 'outside the known folders'
$junction = Join-Path $options.KnownFolderPaths.Documents 'junction'
$null = New-Item -Path $junction -ItemType Junction -Target $outside
try {
$options.Apply = $true
$result = & $scriptPath -Options $options
$rows = @(Import-Csv -LiteralPath $result.ResultPath)
Assert ($result.FilesScanned -eq 0 -and $rows[0].Status -eq 'SkippedReparsePoint') 'Junction must not be traversed.'
Assert ([IO.File]::ReadAllText($outsideFile) -eq 'outside the known folders') 'Junction target changed.'
$options.KnownFolderPaths.Documents = $junction
$result = & $scriptPath -Options $options
Assert ($result.ScanErrors -eq 1) 'A junction supplied as a root must fail the scan.'
} finally {
# Delete only the junction entry, never its target or contents.
[IO.Directory]::Delete($junction)
}
Write-Host 'PASS: nested junction and root junction are not followed.'
# No network/bootstrap: exercise the actual Run-Script shared-scope branch.
$toolsPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'Tools.ps1'
$tokens=$null; $parseErrors=$null
$ast = [Management.Automation.Language.Parser]::ParseFile($toolsPath, [ref]$tokens, [ref]$parseErrors)
$definition = $ast.Find({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script' }, $true)
# Stub only the download expression, including the empty-string argument
# branch used by versions whose typed Arguments parameter converts null to ''.
$offlineDefinition = $definition.Extent.Text.Replace('(New-Object Net.WebClient).DownloadString($URL)', '[IO.File]::ReadAllText($downloadedScript)')
. ([scriptblock]::Create($offlineDefinition))
function IsURLValid { return $true }
function Download-File { return $downloadedScript }
function Write-Output { param($Message) } # Simulate Tools' logging wrapper.
$downloadedScript = Join-Path $testRoot 'downloaded.ps1'
Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript
$OneDrivePrepOptions = New-Fixture 'rmm'
Write-FixtureFile ($OneDrivePrepOptions.KnownFolderPaths.Documents + '\' + ('r' * 100) + '.txt') 'RMM'
$OneDrivePrepOptions.Apply = 'false'
$beforePreference = $ErrorActionPreference
$dotSourced = . $scriptPath
Assert ($dotSourced.Previewed -eq 1) 'Dot-sourcing must read caller options.'
$result = Run-Script -LivePSScript Repair-OneDriveKnownFolderPaths
Assert ($result.Previewed -eq 1 -and $result.Renamed -eq 0) 'RMM shared-scope options were lost or string false enabled changes.'
Assert ($ErrorActionPreference -eq $beforePreference -and $OneDrivePrepOptions.Apply -ceq 'false') 'Caller state must be preserved.'
Write-Host 'PASS: actual Run-Script shared scope and caller-state preservation.'
# The uploaded shim must leave the RMM's scalar strings untouched. Exercise
# its actual source, replacing only the Tools bootstrap to keep tests offline.
$shimPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'rmm\Repair-OneDriveKnownFolderPaths.ps1'
$shimAst = [Management.Automation.Language.Parser]::ParseFile($shimPath, [ref]$tokens, [ref]$parseErrors)
$bootstrap = $shimAst.Find({
param($node)
$node -is [Management.Automation.Language.CommandAst] -and $node.InvocationOperator -eq 'Dot'
}, $true)
Assert ($null -ne $bootstrap) 'RMM shim must retain the shared-scope Tools bootstrap.'
$offlineShim = [scriptblock]::Create([IO.File]::ReadAllText($shimPath).Replace($bootstrap.Extent.Text, '# Offline Tools bootstrap'))
& {
$fixture = New-Fixture 'flat'
$UserProfilePath = 'C:\Users\Synthetic-Test-Profile'
$OneDriveRoot = [string]$fixture.OneDriveRoot
$ReportDirectory = [string]$fixture.ReportDirectory
$DocumentsPath = [string]$fixture.KnownFolderPaths.Documents
$PicturesPath = [string]$fixture.KnownFolderPaths.Pictures
$DesktopPath = [string]$fixture.KnownFolderPaths.Desktop
$Apply = ' false '
$MaxPathLength = '240'
$MaxNameLength = '60'
# An inherited legacy apply setting must not override the new inputs.
$OneDrivePrepOptions = @{ Apply=$true; UnknownLegacySetting='ignored' }
$original = $DocumentsPath + '\' + ('f' * 130) + '.txt'
Write-FixtureFile $original 'flat variable fixture'
Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript -Force
$result = & $offlineShim
Assert ($result.Previewed -eq 1 -and $result.Renamed -eq 0) 'Scalar string false must remain a preview through the RMM shim.'
Assert ($Apply -ceq ' false ' -and $MaxNameLength -ceq '60' -and $UserProfilePath -ceq 'C:\Users\Synthetic-Test-Profile') 'Injected variables were overwritten.'
$row = @(Import-Csv -LiteralPath $result.ResultPath)[0]
Assert ([IO.Path]::GetFileName($row.NewPath).Length -le 60) 'Scalar numeric string was not applied.'
$dotResult = . $scriptPath
Assert ($dotResult.Previewed -eq 1) 'Dot-sourcing must also read individual RMM strings.'
# Missing/blank values default safely instead of inheriting legacy Apply.
Remove-Variable -Name Apply
$MaxPathLength = ''; $MaxNameLength = ''
Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript -Force
$result = Run-Script -LivePSScript Repair-OneDriveKnownFolderPaths
Assert ($result.Mode -eq 'Preview' -and $result.Previewed -eq 1) 'Missing Apply and blank length limits must default safely.'
$row = @(Import-Csv -LiteralPath $result.ResultPath)[0]
Assert ([int]$row.NewProjectedPathLength -le 240) 'Blank length input must retain the 240-character default.'
$Apply = 'maybe'
$caught = $false
try { & $scriptPath } catch { $caught = $_.Exception.Message -like 'Apply must*' }
Assert $caught 'Invalid injected Apply must fail before renaming.'
# Standalone explicit options take precedence over unrelated scope inputs.
$result = & $scriptPath -Options $fixture
Assert ($result.Mode -eq 'Preview') 'Explicit -Options must override injected variables.'
$Apply = 'false'
$DesktopPath = 'Auto'
$caught = $false
try { & $scriptPath } catch { $caught = $_.Exception.Message -like 'Supply DocumentsPath*' }
Assert $caught 'Partial source overrides must not silently target different folders.'
$DesktopPath = [string]$fixture.KnownFolderPaths.Desktop
$Apply = 'true'
$MaxNameLength = '60'
Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript -Force
$result = & $offlineShim
Assert ($result.Renamed -eq 1 -and -not [IO.File]::Exists($original)) 'Scalar string true must enable the requested rename.'
$row = @(Import-Csv -LiteralPath $result.ResultPath)[0]
Assert ([IO.File]::ReadAllText($row.NewPath) -eq 'flat variable fixture') 'RMM rename changed file contents.'
}
Write-Host 'PASS: RMM scalar strings, uploaded shim, safe defaults, input precedence, validation, and explicit apply.'
Write-Host "All OneDrive path preparation tests passed on PowerShell $($PSVersionTable.PSVersion)."
} finally {
# Check the exact absolute target before recursive deletion, using one shell.
$resolvedRoot = [IO.Path]::GetFullPath($testRoot)
$scratchParent = [IO.Path]::GetFullPath($testParent).TrimEnd('\')
if ([IO.Path]::GetDirectoryName($resolvedRoot) -eq $scratchParent -and
[IO.Path]::GetFileName($resolvedRoot) -match '^odt-[a-f0-9]{8}$') {
[IO.Directory]::Delete(('\\?\' + $resolvedRoot), $true)
} else { throw "Refusing to clean an unexpected test directory: $resolvedRoot" }
}