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
+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" }
}