Compare commits
22
Commits
a61b3bb6a3
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e766357cc | ||
|
|
2bbb07c05e | ||
|
|
bfdf8f5eae | ||
|
|
467f699103 | ||
|
|
f2830cb10a | ||
|
|
0c614596f8 | ||
|
|
597524fc13 | ||
|
|
a8b8429b58 | ||
|
|
52aa59a70c | ||
|
|
3e24920646 | ||
|
|
e2163a6158 | ||
|
|
f9daec0542 | ||
|
|
08dbb3cdd5 | ||
|
|
c5ef81dfca | ||
|
|
ec9141d062 | ||
|
|
e9fcc2f33b | ||
|
|
c8eec20391 | ||
|
|
0030be0c7b | ||
|
|
031cfe40a1 | ||
|
|
aea80c7be4 | ||
|
|
e6604564a7 | ||
|
|
136c88fedf |
@@ -2,6 +2,17 @@
|
|||||||
|
|
||||||
## RMM script execution model
|
## RMM script execution model
|
||||||
|
|
||||||
|
Target **Windows PowerShell 4.0** by default for new Windows RMM scripts. Put
|
||||||
|
`#Requires -Version 4.0` in both the RMM caller and its downloaded core. Use
|
||||||
|
4.0-compatible syntax, cmdlets and .NET APIs throughout their execution path,
|
||||||
|
including shared helpers. If a workload genuinely needs a newer version,
|
||||||
|
document the dependency alongside its version requirement.
|
||||||
|
|
||||||
|
This is the required convention for new RMM scripts. Read both
|
||||||
|
[`Install-MicrosoftOffice365.ps1`](Install-MicrosoftOffice365.ps1) and its
|
||||||
|
[`rmm/Install-MicrosoftOffice365.ps1`](rmm/Install-MicrosoftOffice365.ps1) caller
|
||||||
|
as the reference implementation before designing script inputs or a loader.
|
||||||
|
|
||||||
Scripts in this repository are generally executed by a small caller script in the RMM. The caller first downloads and dot-sources `Tools.ps1` from the public repository URL:
|
Scripts in this repository are generally executed by a small caller script in the RMM. The caller first downloads and dot-sources `Tools.ps1` from the public repository URL:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
@@ -14,8 +25,74 @@ The caller then invokes `Run-Script`, passing the repository script's filename w
|
|||||||
Run-Script -LivePSScript Create-BatteryReport
|
Run-Script -LivePSScript Create-BatteryReport
|
||||||
```
|
```
|
||||||
|
|
||||||
For a live PowerShell script without `-Arguments`, `Run-Script` downloads the target script and dot-sources it. This keeps the core script logic in version control, and changes pushed to the repository take effect in production without updating each RMM caller.
|
The live-script calling convention preserves the caller's PowerShell context so
|
||||||
|
the downloaded core can read the caller's variables. Dot-sourcing (`. $ScriptFile`
|
||||||
|
or `. $ScriptBlock`) is the standard way to provide this shared scope. Keep the
|
||||||
|
core logic in version control so repository updates take effect without replacing
|
||||||
|
each RMM caller. `Run-Script` has separate execution branches; verify variable
|
||||||
|
visibility against the actual helper when changing a loader.
|
||||||
|
|
||||||
When a repository script needs RMM-provided input, define the variable in the RMM caller before calling `Run-Script`. Because the target is dot-sourced into the caller's scope, it can read that variable directly.
|
When a repository script needs RMM-provided input, define the variable in the RMM caller before calling `Run-Script`. The downloaded core reads that variable directly from the inherited scope.
|
||||||
|
|
||||||
When changing `Run-Script` or scripts invoked through it, preserve this shared-scope behavior unless the change explicitly includes migrating all affected RMM callers.
|
When changing `Run-Script` or scripts invoked through it, preserve this shared-scope behavior unless the change explicitly includes migrating all affected RMM callers.
|
||||||
|
|
||||||
|
## RMM inputs are caller variables containing strings
|
||||||
|
|
||||||
|
- Define/configure operator inputs in the RMM shim, before loading the core. The
|
||||||
|
RMM supplies **strings only**, even for boolean, integer, and list settings.
|
||||||
|
- The core reads inherited variables, as the Office installer does. Do **not**
|
||||||
|
introduce script-level `param(...)` blocks, command-line flags, or a public
|
||||||
|
`-Options` hashtable for RMM settings. Helper functions inside a script may
|
||||||
|
still declare parameters for their internal interfaces.
|
||||||
|
- Do not pass RMM settings through `Run-Script -Arguments`. Use
|
||||||
|
`Run-Script -LivePSScript <filename-without-extension>` with caller variables
|
||||||
|
already defined. Do not add a new PowerShell process/runspace for convenience:
|
||||||
|
it does not inherit those variables. If a new process is required, explicitly
|
||||||
|
transfer the inputs, as the Office installer does for its native-host relaunch.
|
||||||
|
- Never overwrite values injected by the RMM. When defaults are appropriate,
|
||||||
|
distinguish a missing variable from a supplied blank/false value. A core can
|
||||||
|
use `Get-Variable -Name ... -ErrorAction SilentlyContinue` to collect optional
|
||||||
|
inputs without redefining them or relying on a script parameter block.
|
||||||
|
- Convert boolean strings with **`ConvertTo-RmmBoolean` from `Tools.ps1`**.
|
||||||
|
Never use `[bool]$Text`: a nonempty string such as `'false'` casts to true.
|
||||||
|
- Parse semicolon-separated list strings with
|
||||||
|
**`@(ConvertTo-RmmList -Value $Text)` from `Tools.ps1`**. The helper trims items
|
||||||
|
and removes empty entries; `@(...)` ensures an array for zero/one/many items.
|
||||||
|
It does not validate or resolve paths. Validate share names/paths in the core
|
||||||
|
according to the workload. Keep reusable conversion helpers in `Tools.ps1`;
|
||||||
|
do not duplicate their implementation in individual scripts.
|
||||||
|
- Parse integer strings explicitly and validate the allowed range. Keep the
|
||||||
|
original caller values intact and use separate normalized internal values.
|
||||||
|
- For a permanent endpoint shim launched later by a backup agent, persist its
|
||||||
|
configured **string** values in that shim. Variables injected into an earlier
|
||||||
|
RMM process do not survive into the backup agent's new PowerShell process.
|
||||||
|
|
||||||
|
Example values in a caller (the RMM may inject these rather than assigning them
|
||||||
|
in the script):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$QuickBooksShareNames = 'QBData;QBArchive'
|
||||||
|
$QuickBooksForceClose = 'true'
|
||||||
|
$QuickBooksGraceSeconds = '60'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tools loading and verification
|
||||||
|
|
||||||
|
- Download `Tools.ps1` live when needed. **Do not cache `Tools.ps1` or its helper
|
||||||
|
definitions**, or introduce an offline Tools fallback. This is an explicit
|
||||||
|
repository preference; the cloud-backup workflow requires network access.
|
||||||
|
- Set TLS 1.2 before the first HTTPS download on Windows PowerShell 4.0 and 5.x.
|
||||||
|
- Normally dot-source live `Tools.ps1` as shown above, then call `Run-Script`.
|
||||||
|
The QuickBooks permanent backup shim has a documented specialized loader: it
|
||||||
|
downloads Tools live and dot-sources only its two conversion definitions to
|
||||||
|
avoid running unrelated setup/logging during backup. This is not a reason to
|
||||||
|
replace the standard loader in other scripts. Each QuickBooks shim downloads
|
||||||
|
its matching root script (Stop or Start), which downloads the shared routines
|
||||||
|
from `resources/quickbooks/QuickBooksBackup.ps1`. All code is fetched live;
|
||||||
|
only recovery state/logs persist. Start must not call a local Stop shim or use
|
||||||
|
a cached Stop script in a hidden restore mode.
|
||||||
|
- Test shim-to-core input visibility, string conversions, and exit-code
|
||||||
|
propagation when changing these boundaries. Mock downloads and disruptive
|
||||||
|
actions. For the 4.0 baseline, run on Windows PowerShell 4.0 when available.
|
||||||
|
Otherwise check compatibility against the Server 2012 R2 / PowerShell 4.0
|
||||||
|
profile and run the focused tests on Windows PowerShell 5.1.
|
||||||
|
|||||||
+30
-27
@@ -1,30 +1,34 @@
|
|||||||
$DNSHelper = $Global:ToolsDirectory + '\ekdns.exe'
|
$DNSHelper = $Global:ToolsDirectory + '\ekdns.exe'
|
||||||
|
|
||||||
$DNSHelperRequiredVersion = '2.3.0'
|
# SHA-256 of ekdns.exe from each v2.3.0 Windows release archive.
|
||||||
$DownloadRequired = $false
|
If ([Environment]::Is64BitOperatingSystem) {
|
||||||
|
|
||||||
If (Test-Path $DNSHelper) {
|
|
||||||
$versionOutput = (& $DNSHelper 2>&1 | Select-Object -First 1)
|
|
||||||
If ($versionOutput -match 'v(\d+\.\d+\.\d+)') {
|
|
||||||
If ($Matches[1] -ne $DNSHelperRequiredVersion) {
|
|
||||||
$DownloadRequired = $true
|
|
||||||
}
|
|
||||||
} Else {
|
|
||||||
$DownloadRequired = $true
|
|
||||||
}
|
|
||||||
} Else {
|
|
||||||
$DownloadRequired = $true
|
|
||||||
}
|
|
||||||
|
|
||||||
# Download the latest version of ekDNSHelper
|
|
||||||
If ($DownloadRequired) {
|
|
||||||
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe'
|
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe'
|
||||||
If (!(Test-Path ${Env:ProgramFiles(x86)})) {
|
$DNSHelperHash = '308E36680C0E4AD7CE802F4B1D8C38E89B0D8E24BBCE4F33550721C78BA2224C'
|
||||||
|
} Else {
|
||||||
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x86-exe/download/ekdns-x86.exe'
|
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x86-exe/download/ekdns-x86.exe'
|
||||||
|
$DNSHelperHash = 'F987E75D8FFB87B587B57D2394131B072957C0E3EB6B73B4FB784E9B0D65277B'
|
||||||
}
|
}
|
||||||
If (Test-Path $DNSHelper) { Remove-Item -Path $DNSHelper -Force -ErrorAction SilentlyContinue }
|
|
||||||
|
$InstalledHash = (Get-FileHash -LiteralPath $DNSHelper -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash
|
||||||
|
If ($InstalledHash -ne $DNSHelperHash) {
|
||||||
|
$StagedHelper = $DNSHelper + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
|
||||||
|
Try {
|
||||||
Write-Output "Downloading latest version of ekDNSHelper"
|
Write-Output "Downloading latest version of ekDNSHelper"
|
||||||
Download-File -URL $DNSHelperURL -File $DNSHelper
|
$null = Download-File -URL $DNSHelperURL -File $StagedHelper
|
||||||
|
If ((Get-FileHash -LiteralPath $StagedHelper -Algorithm SHA256 -ErrorAction Stop).Hash -ne $DNSHelperHash) {
|
||||||
|
Throw 'Downloaded ekdns.exe failed SHA-256 verification.'
|
||||||
|
}
|
||||||
|
If ([IO.File]::Exists($DNSHelper)) {
|
||||||
|
[IO.File]::Replace($StagedHelper, $DNSHelper, [NullString]::Value)
|
||||||
|
} Else {
|
||||||
|
[IO.File]::Move($StagedHelper, $DNSHelper)
|
||||||
|
}
|
||||||
|
} Catch {
|
||||||
|
Write-Error $_.Exception.Message
|
||||||
|
Exit 1
|
||||||
|
} Finally {
|
||||||
|
Remove-Item -LiteralPath $StagedHelper -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Delete the old version of ekDNSHelper if it exists
|
# Delete the old version of ekDNSHelper if it exists
|
||||||
@@ -62,15 +66,14 @@ If ( Test-Path $DNSHelper ) {
|
|||||||
$commandString = """${DNSHelper}"" add -host ${HostString}"
|
$commandString = """${DNSHelper}"" add -host ${HostString}"
|
||||||
$content = $RefreshScriptHeader + $commandString
|
$content = $RefreshScriptHeader + $commandString
|
||||||
Write-Output "Creating latest refresh script"
|
Write-Output "Creating latest refresh script"
|
||||||
If ( Test-Path $RefreshScript ) { Remove-Item -Path $RefreshScript -Force }
|
|
||||||
Try {
|
Try {
|
||||||
New-Item -Path $RefreshScript -ItemType File -Force | Out-Null
|
Set-Content -LiteralPath $RefreshScript -Value $content -Force -ErrorAction Stop
|
||||||
Set-Content -Path $RefreshScript -Value $content
|
|
||||||
}
|
|
||||||
Catch { Write-Error $_.Exception.Message }
|
|
||||||
|
|
||||||
Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}"
|
Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}"
|
||||||
& "${RefreshScript}"
|
& "${RefreshScript}"
|
||||||
|
If ($LASTEXITCODE -ne 0) { Exit $LASTEXITCODE }
|
||||||
|
}
|
||||||
|
Catch { Write-Error $_.Exception.Message ; Exit 1 }
|
||||||
} Else {
|
} Else {
|
||||||
Write-Error "Cannot find the DNS Helper executable: ""${DNSHelper}"""
|
Write-Error "Cannot find the DNS Helper executable: ""${DNSHelper}"""
|
||||||
|
Exit 1
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
#Requires -RunAsAdministrator
|
||||||
|
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Lists saved network drive mappings for every local user profile.
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Run in an elevated PowerShell window on the computer being inventoried.
|
||||||
|
Reads the Network key in each non-system user's registry hive. For unloaded
|
||||||
|
profiles, temporarily loads NTUSER.DAT (or NTUSER.MAN) under a unique HKU key
|
||||||
|
and unloads it in a finally block. Does not edit drive mappings or credentials.
|
||||||
|
|
||||||
|
Also enumerates mappings visible to this PowerShell logon session, unless
|
||||||
|
-SavedOnly is specified. These are NOT all other users' live mappings.
|
||||||
|
Saved mappings may be disconnected or obsolete. No shares are probed.
|
||||||
|
Temporary mappings in other sessions and unavailable profile containers
|
||||||
|
cannot be inventoried by this script. Accounts without local profiles are
|
||||||
|
not included. Warnings identify profiles that could not be fully scanned.
|
||||||
|
|
||||||
|
The script returns objects; use Format-Table for display or Export-Csv to save.
|
||||||
|
Use -Verbose to see the scan result for each profile, including empty profiles.
|
||||||
|
|
||||||
|
.EXAMPLE
|
||||||
|
$drives = .\Get-AllNetworkDrives.ps1 -Verbose
|
||||||
|
$drives | Format-Table User, Drive, RemotePath, Source -AutoSize -Wrap
|
||||||
|
|
||||||
|
.EXAMPLE
|
||||||
|
.\Get-AllNetworkDrives.ps1 | Export-Csv .\NetworkDrives.csv -NoTypeInformation -Encoding UTF8
|
||||||
|
#>
|
||||||
|
|
||||||
|
[CmdletBinding(PositionalBinding=$false)]
|
||||||
|
param(
|
||||||
|
# Run-Script passes an empty positional argument even when none was supplied.
|
||||||
|
# Absorb only blank input here so it cannot bind to the SavedOnly switch.
|
||||||
|
[Parameter(Position=0,DontShow=$true)]
|
||||||
|
[AllowEmptyString()]
|
||||||
|
[ValidatePattern('^\s*$')]
|
||||||
|
[string]$RmmArgument,
|
||||||
|
|
||||||
|
[switch]$SavedOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version 2.0
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
# Capture reg.exe failures without parsing localized success/error messages.
|
||||||
|
function Invoke-HiveCommand {
|
||||||
|
param(
|
||||||
|
[ValidateSet('load', 'unload')][string]$Action,
|
||||||
|
[string]$MountName,
|
||||||
|
[string]$HiveFile
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
$PSNativeCommandUseErrorActionPreference = $false
|
||||||
|
$regExe = Join-Path $env:SystemRoot 'System32\reg.exe'
|
||||||
|
$messages = if ($Action -eq 'load') {
|
||||||
|
& $regExe load "HKU\$MountName" $HiveFile 2>&1
|
||||||
|
} else {
|
||||||
|
& $regExe unload "HKU\$MountName" 2>&1
|
||||||
|
}
|
||||||
|
$exitCode = $LASTEXITCODE
|
||||||
|
[pscustomobject]@{
|
||||||
|
ExitCode = $exitCode
|
||||||
|
Message = ($messages | Out-String).Trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$results = [System.Collections.Generic.List[object]]::new()
|
||||||
|
$profiles = @(Get-CimInstance -ClassName Win32_UserProfile -ErrorAction Stop |
|
||||||
|
Where-Object { -not $_.Special -and $_.SID } |
|
||||||
|
Sort-Object LocalPath)
|
||||||
|
|
||||||
|
if ($profiles.Count -eq 0) {
|
||||||
|
Write-Warning 'Windows reported no non-system user profiles.'
|
||||||
|
}
|
||||||
|
|
||||||
|
$usersKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey(
|
||||||
|
[Microsoft.Win32.RegistryHive]::Users,
|
||||||
|
[Microsoft.Win32.RegistryView]::Default
|
||||||
|
)
|
||||||
|
|
||||||
|
try {
|
||||||
|
foreach ($profile in $profiles) {
|
||||||
|
$sid = [string]$profile.SID
|
||||||
|
$userName = $sid
|
||||||
|
try {
|
||||||
|
$userName = ([System.Security.Principal.SecurityIdentifier]::new($sid)).Translate(
|
||||||
|
[System.Security.Principal.NTAccount]
|
||||||
|
).Value
|
||||||
|
} catch {
|
||||||
|
# Keep the SID when a deleted account or offline domain cannot resolve.
|
||||||
|
Write-Verbose "Account name unavailable for $sid; retaining its SID."
|
||||||
|
}
|
||||||
|
|
||||||
|
$profileKey = $null
|
||||||
|
$networkKey = $null
|
||||||
|
$mountedByScript = $false
|
||||||
|
$mountName = 'DriveInventory_' + [guid]::NewGuid().ToString('N')
|
||||||
|
$countBefore = $results.Count
|
||||||
|
|
||||||
|
try {
|
||||||
|
# Check the registry itself: the profile's Loaded flag can be stale.
|
||||||
|
$profileKey = $usersKey.OpenSubKey($sid, $false)
|
||||||
|
if ($null -eq $profileKey) {
|
||||||
|
if ([string]::IsNullOrWhiteSpace($profile.LocalPath)) {
|
||||||
|
throw 'The profile has no local path and its hive is not loaded.'
|
||||||
|
}
|
||||||
|
|
||||||
|
$hiveFile = Join-Path $profile.LocalPath 'NTUSER.DAT'
|
||||||
|
if (-not (Test-Path -LiteralPath $hiveFile -PathType Leaf)) {
|
||||||
|
$hiveFile = Join-Path $profile.LocalPath 'NTUSER.MAN'
|
||||||
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $hiveFile -PathType Leaf)) {
|
||||||
|
throw "Neither NTUSER.DAT nor NTUSER.MAN is available in $($profile.LocalPath)."
|
||||||
|
}
|
||||||
|
|
||||||
|
$loadResult = Invoke-HiveCommand -Action load -MountName $mountName -HiveFile $hiveFile
|
||||||
|
if ($loadResult.ExitCode -eq 0) {
|
||||||
|
$mountedByScript = $true
|
||||||
|
$profileKey = $usersKey.OpenSubKey($mountName, $false)
|
||||||
|
} else {
|
||||||
|
# The user may have signed in between our check and reg load.
|
||||||
|
$profileKey = $usersKey.OpenSubKey($sid, $false)
|
||||||
|
if ($null -eq $profileKey) {
|
||||||
|
throw "Could not load the profile hive: $($loadResult.Message)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($null -eq $profileKey) {
|
||||||
|
throw 'The profile hive could not be opened after loading.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$networkKey = $profileKey.OpenSubKey('Network', $false)
|
||||||
|
if ($null -ne $networkKey) {
|
||||||
|
foreach ($letter in $networkKey.GetSubKeyNames()) {
|
||||||
|
if ($letter -notmatch '^[A-Za-z]$') { continue }
|
||||||
|
$driveKey = $null
|
||||||
|
try {
|
||||||
|
$driveKey = $networkKey.OpenSubKey($letter, $false)
|
||||||
|
if ($null -eq $driveKey) {
|
||||||
|
throw "Drive key $letter disappeared during the scan."
|
||||||
|
}
|
||||||
|
$remotePath = [string]$driveKey.GetValue('RemotePath', '')
|
||||||
|
if ([string]::IsNullOrWhiteSpace($remotePath)) {
|
||||||
|
Write-Warning "${userName}: saved drive ${letter}: has no RemotePath."
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
$results.Add([pscustomobject][ordered]@{
|
||||||
|
User = $userName
|
||||||
|
Drive = $letter.ToUpperInvariant() + ':'
|
||||||
|
RemotePath = $remotePath
|
||||||
|
Source = 'Saved'
|
||||||
|
ComputerName = $env:COMPUTERNAME
|
||||||
|
SID = $sid
|
||||||
|
ProfilePath = $profile.LocalPath
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
if ($null -ne $driveKey) { $driveKey.Dispose() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-Verbose ("{0}: {1} saved mapping(s) found." -f $userName, ($results.Count - $countBefore))
|
||||||
|
} catch {
|
||||||
|
Write-Warning "Incomplete scan for $userName [$sid], profile '$($profile.LocalPath)': $($_.Exception.Message)"
|
||||||
|
} finally {
|
||||||
|
# Close every child handle BEFORE unloading. Never unload an existing user hive.
|
||||||
|
if ($null -ne $networkKey) { $networkKey.Dispose() }
|
||||||
|
if ($null -ne $profileKey) { $profileKey.Dispose() }
|
||||||
|
if ($mountedByScript) {
|
||||||
|
$unloadResult = Invoke-HiveCommand -Action unload -MountName $mountName
|
||||||
|
if ($unloadResult.ExitCode -ne 0) {
|
||||||
|
Write-Warning "Could not unload HKU\$mountName. $($unloadResult.Message) After closing any handles, run: reg.exe unload HKU\$mountName"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
$usersKey.Dispose()
|
||||||
|
}
|
||||||
|
|
||||||
|
# Supplement saved mappings with those visible to THIS process's logon session.
|
||||||
|
# This can include temporary mappings, but only for the session running the script.
|
||||||
|
if (-not $SavedOnly) {
|
||||||
|
$identity = $null
|
||||||
|
$network = $null
|
||||||
|
$sessionDrives = $null
|
||||||
|
try {
|
||||||
|
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
|
$currentSid = $identity.User.Value
|
||||||
|
$network = New-Object -ComObject WScript.Network
|
||||||
|
$sessionDrives = $network.EnumNetworkDrives()
|
||||||
|
# WshCollection exposes Count as a COM method, not a PowerShell property.
|
||||||
|
for ($i = 0; $i -lt $sessionDrives.Count(); $i += 2) {
|
||||||
|
$drive = [string]$sessionDrives.Item($i)
|
||||||
|
$remotePath = [string]$sessionDrives.Item($i + 1)
|
||||||
|
if ($drive -notmatch '^[A-Za-z]:$') { continue }
|
||||||
|
|
||||||
|
$matchesSaved = @($results | Where-Object {
|
||||||
|
$_.SID -eq $currentSid -and $_.Drive -eq $drive -and $_.RemotePath -eq $remotePath
|
||||||
|
})
|
||||||
|
if ($matchesSaved.Count -gt 0) {
|
||||||
|
foreach ($match in $matchesSaved) { $match.Source = 'Saved + CurrentSession' }
|
||||||
|
} else {
|
||||||
|
$results.Add([pscustomobject][ordered]@{
|
||||||
|
User = $identity.Name
|
||||||
|
Drive = $drive.ToUpperInvariant()
|
||||||
|
RemotePath = $remotePath
|
||||||
|
Source = 'CurrentSession'
|
||||||
|
ComputerName = $env:COMPUTERNAME
|
||||||
|
SID = $currentSid
|
||||||
|
ProfilePath = $env:USERPROFILE
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
Write-Warning "Could not fully enumerate current-session drives: $($_.Exception.Message)"
|
||||||
|
} finally {
|
||||||
|
if ($null -ne $sessionDrives) {
|
||||||
|
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($sessionDrives)
|
||||||
|
}
|
||||||
|
if ($null -ne $network) {
|
||||||
|
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($network)
|
||||||
|
}
|
||||||
|
if ($null -ne $identity) { $identity.Dispose() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($results.Count -eq 0) {
|
||||||
|
Write-Warning 'No mappings were found in the sources successfully scanned. Review any earlier warnings; other sessions may still have temporary mappings.'
|
||||||
|
}
|
||||||
|
|
||||||
|
$results | Sort-Object User, Drive, RemotePath
|
||||||
|
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
# Read-only endpoint investigation. Creates a diagnostic ZIP; never runs Office,
|
||||||
|
# changes its registry, stops workers, or imports the deployment script.
|
||||||
|
# Run elevated, directly or through rmm/Get-OfficeDeploymentDiagnostics.ps1.
|
||||||
|
|
||||||
|
function Get-OfficeDiagnosticFiles {
|
||||||
|
param([string]$Root, [string[]]$Patterns, [datetime]$SinceUtc, [int]$Depth = 0, $Issues)
|
||||||
|
try {
|
||||||
|
if (!(Test-Path -LiteralPath $Root -ErrorAction Stop)) { return }
|
||||||
|
$item = Get-Item -LiteralPath $Root -ErrorAction Stop
|
||||||
|
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { return }
|
||||||
|
foreach ($child in @(Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop)) {
|
||||||
|
if ($child.Attributes -band [IO.FileAttributes]::ReparsePoint) { continue }
|
||||||
|
if ($child.PSIsContainer) {
|
||||||
|
if ($Depth -gt 0) { Get-OfficeDiagnosticFiles $child.FullName $Patterns $SinceUtc ($Depth - 1) $Issues }
|
||||||
|
} elseif ($child.LastWriteTimeUtc -ge $SinceUtc) {
|
||||||
|
foreach ($pattern in $Patterns) { if ($child.Name -like $pattern) { $child; break } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { $Issues.Add("File enumeration: $Root : $($_.Exception.Message)") }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-OfficeDiagnosticRegistry {
|
||||||
|
# Explicit views also work when Syncro runs 32-bit PowerShell. Do not export
|
||||||
|
# licensing/identity stores or use Win32_Product (which can trigger repairs).
|
||||||
|
foreach ($view in @([Microsoft.Win32.RegistryView]::Registry64, [Microsoft.Win32.RegistryView]::Registry32)) {
|
||||||
|
$base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $view)
|
||||||
|
try {
|
||||||
|
$queue = New-Object 'Collections.Generic.Queue[string]'
|
||||||
|
$queue.Enqueue('SOFTWARE\Microsoft\Office\ClickToRun')
|
||||||
|
while ($queue.Count) {
|
||||||
|
$path = $queue.Dequeue(); $key = $base.OpenSubKey($path, $false)
|
||||||
|
if (!$key) { continue }
|
||||||
|
try {
|
||||||
|
foreach ($name in $key.GetValueNames()) {
|
||||||
|
$value = $key.GetValue($name)
|
||||||
|
if ($name -match '^(WorkingConfig(uration)?|SourcePath|InstallationPath|InstallPath|ProductReleaseIds|VersionToReport|ClientVersionToReport|Platform|CDNBaseUrl|UpdateChannel|UpdateUrl|UpdatePath|AudienceId)$' -or
|
||||||
|
($value -is [string] -and $value -match '(?i)EmberkomOfficeDeployment[\\/]')) {
|
||||||
|
[pscustomobject]@{ View=[string]$view; Key=$path; Name=$name; Value=$value }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($child in $key.GetSubKeyNames()) { $queue.Enqueue("$path\$child") }
|
||||||
|
} finally { $key.Dispose() }
|
||||||
|
}
|
||||||
|
$uninstall = $base.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', $false)
|
||||||
|
if ($uninstall) {
|
||||||
|
try {
|
||||||
|
foreach ($name in $uninstall.GetSubKeyNames()) {
|
||||||
|
$key = $uninstall.OpenSubKey($name, $false)
|
||||||
|
if (!$key) { continue }
|
||||||
|
try {
|
||||||
|
$display = $key.GetValue('DisplayName')
|
||||||
|
if ($display -match '(?i)^(Microsoft\s+)?(365|Office|Visio|Project|Access|Word|Excel|Outlook|PowerPoint|OneNote|Publisher|Skype for Business)(\s|$)') {
|
||||||
|
[pscustomobject]@{ View=[string]$view; Key=$key.Name; DisplayName=$display; DisplayVersion=$key.GetValue('DisplayVersion'); Publisher=$key.GetValue('Publisher'); WindowsInstaller=$key.GetValue('WindowsInstaller'); InstallLocation=$key.GetValue('InstallLocation') }
|
||||||
|
}
|
||||||
|
} finally { $key.Dispose() }
|
||||||
|
}
|
||||||
|
} finally { $uninstall.Dispose() }
|
||||||
|
}
|
||||||
|
} finally { $base.Dispose() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Add-OfficeDiagnosticText {
|
||||||
|
param($Archive, [string]$Name, [string]$Text)
|
||||||
|
$stream = $Archive.CreateEntry($Name).Open()
|
||||||
|
$writer = New-Object IO.StreamWriter($stream, (New-Object Text.UTF8Encoding($false)))
|
||||||
|
try { $writer.Write($Text) } finally { $writer.Dispose() }
|
||||||
|
}
|
||||||
|
|
||||||
|
function New-OfficeDiagnosticArchive {
|
||||||
|
param([string]$Path, [object[]]$Files, $Report, $Issues)
|
||||||
|
Add-Type -AssemblyName System.IO.Compression -ErrorAction Stop
|
||||||
|
$output = [IO.File]::Open($Path, [IO.FileMode]::CreateNew, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None)
|
||||||
|
$archive = $null; $total = 0L; $manifest = New-Object 'Collections.Generic.List[object]'
|
||||||
|
try {
|
||||||
|
$archive = New-Object IO.Compression.ZipArchive($output, [IO.Compression.ZipArchiveMode]::Create, $true)
|
||||||
|
foreach ($file in @($Files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending)) {
|
||||||
|
$row = [pscustomobject]@{ Source=$file.FullName; LastWriteTimeUtc=$file.LastWriteTimeUtc; Length=$file.Length; Entry=$null; CapturedBytes=0L; Status='Pending' }
|
||||||
|
$manifest.Add($row)
|
||||||
|
$inputStream = $null; $entryStream = $null
|
||||||
|
try {
|
||||||
|
if ($file.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Reparse points are excluded.' }
|
||||||
|
$inputStream = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, ([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete))
|
||||||
|
$length = $inputStream.Length
|
||||||
|
if ($length -gt 64MB -or ($total + $length) -gt 512MB -or $manifest.Count -gt 2000) { throw 'Collection limit reached (64 MB/file, 512 MB total, 2000 files); source was not changed.' }
|
||||||
|
$row.Entry = 'files/{0:D4}_{1}' -f $manifest.Count, $file.Name
|
||||||
|
$entryStream = $archive.CreateEntry($row.Entry, [IO.Compression.CompressionLevel]::Optimal).Open()
|
||||||
|
$buffer = New-Object byte[] 65536
|
||||||
|
# Bound the copy to its initial length even if a live log grows.
|
||||||
|
while ($row.CapturedBytes -lt $length) {
|
||||||
|
$read = $inputStream.Read($buffer, 0, [int][Math]::Min($buffer.Length, $length - $row.CapturedBytes))
|
||||||
|
if (!$read) { throw 'Source changed/truncated during capture.' }
|
||||||
|
$entryStream.Write($buffer, 0, $read); $row.CapturedBytes += $read; $total += $read
|
||||||
|
}
|
||||||
|
$row.Status = 'Captured (live files are not an atomic snapshot)'
|
||||||
|
} catch { $row.Status = "Incomplete: $($_.Exception.Message)"; $Issues.Add("$($row.Source) : $($row.Status)") }
|
||||||
|
finally { if ($entryStream) { $entryStream.Dispose() }; if ($inputStream) { $inputStream.Dispose() } }
|
||||||
|
}
|
||||||
|
Add-OfficeDiagnosticText $archive 'endpoint.json' ($Report | ConvertTo-Json -Depth 10)
|
||||||
|
Add-OfficeDiagnosticText $archive 'manifest.json' (ConvertTo-Json -InputObject @($manifest.ToArray()) -Depth 5)
|
||||||
|
Add-OfficeDiagnosticText $archive 'collection-issues.json' (ConvertTo-Json -InputObject @($Issues.ToArray()))
|
||||||
|
Add-OfficeDiagnosticText $archive 'README.txt' 'Read-only evidence bundle. endpoint.json is CURRENT state, not the state before the manual install. Use original timestamps inside native logs to compare runs. manifest.json maps archived files to their original paths. Read collection-issues.json for omissions. No Office media is archived or executed. Logs may contain user names and paths.'
|
||||||
|
} finally { if ($archive) { $archive.Dispose() }; $output.Dispose() }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-OfficeDiagnosticCollection {
|
||||||
|
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
|
if (!(New-Object Security.Principal.WindowsPrincipal($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run the diagnostic collector elevated or as SYSTEM.' }
|
||||||
|
$since = [datetime]::UtcNow.AddHours(-72)
|
||||||
|
$issues = New-Object 'Collections.Generic.List[string]'
|
||||||
|
$files = New-Object 'Collections.Generic.List[object]'
|
||||||
|
$report = [ordered]@{ CollectedUtc=[datetime]::UtcNow; SinceUtc=$since; Computer=$env:COMPUTERNAME; Identity=$identity.Name; ProcessId=$PID; Is64BitProcess=[Environment]::Is64BitProcess; PowerShellVersion=[string]$PSVersionTable.PSVersion; TimeZone=[TimeZoneInfo]::Local.Id }
|
||||||
|
try { $report.OS = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop | Select-Object Caption, Version, BuildNumber, LastBootUpTime } catch { $issues.Add("OS: $($_.Exception.Message)") }
|
||||||
|
try { $profiles = @(Get-CimInstance Win32_UserProfile -ErrorAction Stop | Select-Object SID, LocalPath, Loaded, Special); $report.Profiles = $profiles } catch { $profiles=@(); $issues.Add("Profiles: $($_.Exception.Message)") }
|
||||||
|
try { $report.OfficeRegistry = @(Get-OfficeDiagnosticRegistry) } catch { $issues.Add("Registry: $($_.Exception.Message)") }
|
||||||
|
try { $report.ClickToRunService = Get-CimInstance Win32_Service -Filter "Name='ClickToRunSvc'" -ErrorAction Stop | Select-Object Name, State, StartMode, ProcessId, PathName } catch { $issues.Add("Service: $($_.Exception.Message)") }
|
||||||
|
try {
|
||||||
|
$report.Workers = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object {
|
||||||
|
$_.Name -match '^(setup|OfficeClickToRun|OfficeC2RClient|GetHelpCmd|SaRAcmd|msiexec|cscript|wscript)\.exe$' -or $_.CommandLine -match '(?i)OfficeScrub|OffScrub|GetHelpElevated|EmberkomOfficeDeployment'
|
||||||
|
} | ForEach-Object {
|
||||||
|
$worker = $_ | Select-Object Name, ProcessId, ParentProcessId, SessionId, CreationDate, ExecutablePath, CommandLine
|
||||||
|
try { $owner = Invoke-CimMethod -InputObject $_ -MethodName GetOwner -ErrorAction Stop; $worker | Add-Member NoteProperty Owner "$($owner.Domain)\$($owner.User)"; $worker | Add-Member NoteProperty OwnerQueryResult $owner.ReturnValue } catch { $issues.Add("Process owner PID $($worker.ProcessId): $($_.Exception.Message)") }
|
||||||
|
$worker
|
||||||
|
})
|
||||||
|
} catch { $issues.Add("Workers: $($_.Exception.Message)") }
|
||||||
|
try { $report.CleanupTasks = @(Get-ScheduledTask -TaskName 'Emberkom-OfficeCleanup-*' -ErrorAction Stop | Select-Object TaskName, State, Principal, Actions) } catch { $issues.Add("Cleanup tasks (possibly none): $($_.Exception.Message)") }
|
||||||
|
|
||||||
|
$nativeWindows = if ([Environment]::Is64BitOperatingSystem -and ![Environment]::Is64BitProcess) { Join-Path $env:windir 'Sysnative' } else { Join-Path $env:windir 'System32' }
|
||||||
|
$tempRoots = @($env:TEMP, "$env:windir\Temp", "$env:windir\SystemTemp") + @($profiles | ForEach-Object { Join-Path $_.LocalPath 'AppData\Local\Temp' })
|
||||||
|
foreach ($root in @($tempRoots | Select-Object -Unique)) {
|
||||||
|
foreach ($file in @(Get-OfficeDiagnosticFiles $root @("$env:COMPUTERNAME*.log", 'Office*.log', 'Microsoft*Office*.log', 'ClickToRun*.log', 'Setup*.log', 'OffScrub*.log', 'OffScrub*.txt') $since 0 $issues)) { $files.Add($file) }
|
||||||
|
foreach ($file in @(Get-OfficeDiagnosticFiles (Join-Path $root 'EmberkomOfficeDeployment') @('*.log', 'install.xml', 'remove.xml') $since 3 $issues)) { $files.Add($file) }
|
||||||
|
# Worker scripts carry Microsoft's package timestamps, so do not filter them by LastWriteTime.
|
||||||
|
foreach ($file in @(Get-OfficeDiagnosticFiles (Join-Path $root 'GetHelpElevated') @('Run.ps1', 'OfficeUninstall.ps1', 'Logger-FileLogUtils.ps1', 'Utils.ps1', 'Env-Utils.ps1') ([datetime]::MinValue) 1 $issues)) { $files.Add($file) }
|
||||||
|
}
|
||||||
|
$localRoots = @($env:LOCALAPPDATA, "$nativeWindows\config\systemprofile\AppData\Local", "$env:windir\SysWOW64\config\systemprofile\AppData\Local") + @($profiles | ForEach-Object { Join-Path $_.LocalPath 'AppData\Local' })
|
||||||
|
foreach ($root in @($localRoots | Select-Object -Unique)) {
|
||||||
|
foreach ($file in @(Get-OfficeDiagnosticFiles (Join-Path $root 'DAFs') @('*office*uninstall*.log', '*uninstall*office*.log') $since 2 $issues)) { $files.Add($file) }
|
||||||
|
}
|
||||||
|
foreach ($file in @(Get-OfficeDiagnosticFiles "$env:ProgramData\EmberkomOfficeDeployment" @('*.log') $since 3 $issues)) { $files.Add($file) }
|
||||||
|
foreach ($file in @(Get-OfficeDiagnosticFiles "$env:ProgramData\Emberkom\Logs" @('ManagementScript_*.log') $since 0 $issues)) {
|
||||||
|
try {
|
||||||
|
if ($file.Length -gt 64MB) { $issues.Add("Management log exceeds 64 MB filter limit: $($file.FullName)"); continue }
|
||||||
|
if (Select-String -LiteralPath $file.FullName -Pattern 'Install-MicrosoftOffice365', 'EmberkomOfficeDeployment' -SimpleMatch -Quiet -ErrorAction Stop) { $files.Add($file) }
|
||||||
|
}
|
||||||
|
catch { $issues.Add("Management log filter: $($file.FullName) : $($_.Exception.Message)") }
|
||||||
|
}
|
||||||
|
$destination = Join-Path $env:ProgramData 'Emberkom\Logs\OfficeDiagnostics'
|
||||||
|
$null = New-Item -ItemType Directory -Path $destination -Force -ErrorAction Stop
|
||||||
|
$zip = Join-Path $destination ('OfficeDiagnostics-{0}-{1}-{2}.zip' -f $env:COMPUTERNAME, (Get-Date -Format 'yyyyMMdd-HHmmss'), [guid]::NewGuid().ToString('N').Substring(0,8))
|
||||||
|
New-OfficeDiagnosticArchive $zip @($files.ToArray()) $report $issues
|
||||||
|
Write-Output "Office diagnostic ZIP: $zip"
|
||||||
|
Write-Output "Collection issues: $($issues.Count). Review collection-issues.json for missing/unreadable files. Office installation and running processes were not changed."
|
||||||
|
}
|
||||||
|
|
||||||
|
try { Invoke-OfficeDiagnosticCollection }
|
||||||
|
catch { Write-Error "Office diagnostic collection failed: $($_.Exception.Message)" -ErrorAction Continue; exit 1 }
|
||||||
@@ -1,15 +1,8 @@
|
|||||||
# Specify URL to "Backup for Windows" agent installer
|
# Install and update use the same published Emberkom packages.
|
||||||
$ECB_WIN_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VmK3VHNmxBVEZTQkxhMFhNR2ZuZzJCeE80MDJxVkRSWXdNa0dqSHdpbUN1bE01c3BWNFBVUmt2Q1c4endncjVZemFSSjEyYmFNL3hESHR2eWpVYXpBVlV2eU1kZVZFaEpvalk2Rk40Wk96UG9QdUwxYnZrRHREMmhLeTZoMW5Rbz0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4'
|
switch ($Edition) {
|
||||||
|
'server' { $CloudBackupBuild = 'Windows'; $AgentEdition = 'baremetal' }
|
||||||
# Specify URL to "Backup Virtual Machine Edition" agent installer
|
'vm' { $CloudBackupBuild = 'VM'; $AgentEdition = 'vmedition' }
|
||||||
$ECB_VMM_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNwOTFVa3h6WUdoeVVod1JmT2lRQ1FlVTE3Y0pnUncwSEJwS3FFcDBmTWt3cEdnSy9YemRsSTRiQWJHNi96cUtWbzZsc25QVllaR1QyQ21VVS95dFFVTkNndXdPVStGQXBIT0FZb2FIUzFuZy9mMU5qZUd5emhab1hFYjZWODB4ND0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4'
|
default { $CloudBackupBuild = 'Windows'; $AgentEdition = 'desktop' }
|
||||||
|
|
||||||
# Set the correct download URL and agent edition
|
|
||||||
switch ( $Edition.ToLower() ) {
|
|
||||||
'server' { $URL = $ECB_WIN_URL; $AgentEdition = 'baremetal' }
|
|
||||||
'desktop' { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop' }
|
|
||||||
'vm' { $URL = $ECB_VMM_URL; $AgentEdition = 'vmedition' }
|
|
||||||
default { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop' }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Install and import additional Powershell module
|
# Install and import additional Powershell module
|
||||||
@@ -21,30 +14,9 @@ If ( $(Get-MBSAgent -ErrorAction SilentlyContinue) ) {
|
|||||||
Return
|
Return
|
||||||
}
|
}
|
||||||
|
|
||||||
#
|
$CloudBackupRelease = Get-EmberkomCloudBackupRelease -Build $CloudBackupBuild
|
||||||
# The URL is now too long to pass as a variable to other functions and cmdlets, so this is a workaround to download the file
|
$Installer = Join-Path (Get-TempPath) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid())
|
||||||
#
|
Save-EmberkomCloudBackupInstaller -Release $CloudBackupRelease -Path $Installer
|
||||||
|
|
||||||
# Make sure the URL is valid
|
|
||||||
$StatusCode = [System.Net.WebRequest]::Create($URL).GetResponse().StatusCode
|
|
||||||
If ( !(($StatusCode -ge 200) -and ($StatusCode -lt 400)) ) { Write-Output "URL cannot be reached (status code ${StatusCode}): ${URL}" ; Return }
|
|
||||||
|
|
||||||
# Make a local file to download to
|
|
||||||
$Installer = '{0}EmberkomCloudBackup.exe' -f (Get-TempPath)
|
|
||||||
|
|
||||||
# Delete previous local file if it exists
|
|
||||||
If ( Test-Path $Installer ) { Write-Output "Deleting previously downloaded file: ${Installer}" ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue }
|
|
||||||
|
|
||||||
# Download the file
|
|
||||||
Try { (New-Object System.Net.WebClient).DownloadFile($URL,$Installer) }
|
|
||||||
Catch { Write-Error $_.Exception.Message ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue }
|
|
||||||
|
|
||||||
# Make sure the file exists
|
|
||||||
If ( !(Test-Path $Installer) ) { Write-Output "There was a problem downloading the file, this script will not continue" ; Return }
|
|
||||||
|
|
||||||
#
|
|
||||||
# End the workaround
|
|
||||||
#
|
|
||||||
|
|
||||||
# Install the agent
|
# Install the agent
|
||||||
Write-Output "Installing Emberkom Cloud Backup agent"
|
Write-Output "Installing Emberkom Cloud Backup agent"
|
||||||
|
|||||||
+789
-48
File diff suppressed because it is too large
Load Diff
@@ -14,15 +14,40 @@ You can then run any of the scripts using the Run-Script function:
|
|||||||
|
|
||||||
If you're using an RMM tool, the scripts in the /rmm directory are all that's needed to hook the main script in this directory.
|
If you're using an RMM tool, the scripts in the /rmm directory are all that's needed to hook the main script in this directory.
|
||||||
|
|
||||||
|
For QuickBooks image-backup preparation, use [Stop-QuickBooksDesktop.ps1](Stop-QuickBooksDesktop.ps1)
|
||||||
|
and [Start-QuickBooksDesktop.ps1](Start-QuickBooksDesktop.ps1). The permanent
|
||||||
|
[stop shim](rmm/Stop-QuickBooksDesktop.ps1) defines the host's exact company-file
|
||||||
|
share names as a semicolon-separated string and pairs with the
|
||||||
|
[start shim](rmm/Start-QuickBooksDesktop.ps1). See [deployment, exit codes, and
|
||||||
|
recovery](docs/QuickBooks-Backup.md) before scheduling: desktop, database-service,
|
||||||
|
share-isolation, or open-handle failures prevent backup; post restores the
|
||||||
|
recorded services and share access. Each shim downloads its matching repository
|
||||||
|
script, `Tools.ps1`, and the shared QuickBooks routines live on every run. Only
|
||||||
|
the two shims need deployment; recovery state persists locally and no code is cached.
|
||||||
|
|
||||||
For DSA collection, paste [rmm/Get-DSAManifest.ps1](rmm/Get-DSAManifest.ps1) into the RMM caller, preserving its configured platform variables. This caller selects TLS 1.2 before downloading, stops on bootstrap failure, and dot-sources the downloaded tools in the caller's scope. Updating the repository alone will not change an existing RMM caller.
|
For DSA collection, paste [rmm/Get-DSAManifest.ps1](rmm/Get-DSAManifest.ps1) into the RMM caller, preserving its configured platform variables. This caller selects TLS 1.2 before downloading, stops on bootstrap failure, and dot-sources the downloaded tools in the caller's scope. Updating the repository alone will not change an existing RMM caller.
|
||||||
|
|
||||||
For download failures, use the standalone [Test-FileDownload.ps1](Test-FileDownload.ps1) diagnostic. See [the RMM caller, report guide, and shared caller audit](docs/FileDownload-Diagnostics.md). It compares the existing helper, BITS, and direct GET without changing production download behavior or running downloaded files.
|
For download failures, use the standalone [Test-FileDownload.ps1](Test-FileDownload.ps1) diagnostic. See [the RMM caller, report guide, and shared caller audit](docs/FileDownload-Diagnostics.md). It compares the existing helper, BITS, and direct GET without changing production download behavior or running downloaded files.
|
||||||
|
|
||||||
`Get-DSAManifest.ps1` uses `Download-FileDirectly`, which passes the original URL to BITS without preliminary `Get-AbsoluteURI` or `IsURLValid` requests. It accepts the same URL and optional `-File` arguments as `Download-File`, waits for completion, and throws on BITS errors. If `-File` is omitted, its temporary filename comes from the original URL; supply `-File` for extensionless URLs or URLs with query strings. Existing `Download-File` callers retain their previous behavior. Publish `Tools.ps1` together with `Get-DSAManifest.ps1` so the new helper is available.
|
`Get-DSAManifest.ps1` uses `Download-FileDirectly`, which passes the original URL to BITS without preliminary `Get-AbsoluteURI` or `IsURLValid` requests. It accepts the same URL and optional `-File` arguments as `Download-File`, waits for completion, and throws on BITS errors. If `-File` is omitted, its temporary filename comes from the original URL; supply `-File` for extensionless URLs or URLs with query strings. Existing `Download-File` callers retain their previous behavior. Publish `Tools.ps1` together with `Get-DSAManifest.ps1` so the new helper is available.
|
||||||
|
|
||||||
|
## Environment inventory
|
||||||
|
|
||||||
|
Use [Get-EnvironmentInventory.ps1](Get-EnvironmentInventory.ps1) to collect file
|
||||||
|
shares, networks, printer connections, wireless observations, and internet egress
|
||||||
|
into versioned JSON on Windows PowerShell 5.1. Reports describe the environment;
|
||||||
|
endpoint identity is optional and no Hudu credentials or module are required.
|
||||||
|
The [RMM caller](rmm/Get-EnvironmentInventory.ps1) supports optional upload through
|
||||||
|
the existing Filedrop helper. See the [options and data contract](docs/Environment-Inventory.md)
|
||||||
|
and [JSON schema](resources/environment-inventory/schema-v1.json). No importer is included.
|
||||||
|
|
||||||
## Microsoft 365 deployment
|
## Microsoft 365 deployment
|
||||||
|
|
||||||
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.
|
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` (assessment and HTTP HEAD checks without staging or downloads); 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. Confirmed removal corruption or residual state can trigger one Microsoft Get Help scrub before installation; its downloads are fresh and cleaned afterward, and a child window may appear. 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
|
## Converting RMM boolean variables
|
||||||
|
|
||||||
@@ -43,6 +68,22 @@ Each input returns a `System.Boolean`: `true`, `$true`, `yes`, `y`, and `1` beco
|
|||||||
|
|
||||||
`Get-DSAManifest.ps1` uses this helper for its three options. Publish it together with the updated `Tools.ps1` so the helper is available to the RMM caller.
|
`Get-DSAManifest.ps1` uses this helper for its three options. Publish it together with the updated `Tools.ps1` so the helper is available to the RMM caller.
|
||||||
|
|
||||||
|
## Converting RMM lists
|
||||||
|
|
||||||
|
Use `ConvertTo-RmmList` for an RMM string containing semicolon-separated values:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$Paths = @(ConvertTo-RmmList -Value 'C:\QB Data; \\server\Archive;')
|
||||||
|
$Shares = @(ConvertTo-RmmList -Value $QuickBooksShareNames)
|
||||||
|
```
|
||||||
|
|
||||||
|
The helper trims surrounding whitespace and omits empty entries. It preserves
|
||||||
|
item order, duplicates, case, internal spaces, commas, and backslashes. It does
|
||||||
|
not evaluate text, resolve paths, or check whether files/shares exist. Semicolons
|
||||||
|
are always separators; there is no quoting or escaping syntax. Use `@(...)` so
|
||||||
|
zero, one, and multiple items always produce an array. Publish the updated
|
||||||
|
`Tools.ps1` with callers that use this new helper.
|
||||||
|
|
||||||
## Uploading files
|
## Uploading files
|
||||||
|
|
||||||
After dot-sourcing `Tools.ps1`, scripts can upload a completed file to the Emberkom FileDrop:
|
After dot-sourcing `Tools.ps1`, scripts can upload a completed file to the Emberkom FileDrop:
|
||||||
@@ -68,4 +109,6 @@ powershell.exe -NoProfile -File .\tests\Upload-File.Tests.ps1
|
|||||||
powershell.exe -NoProfile -File .\tests\Get-DSAManifest.Tests.ps1
|
powershell.exe -NoProfile -File .\tests\Get-DSAManifest.Tests.ps1
|
||||||
powershell.exe -NoProfile -File .\tests\Download-File.Tests.ps1
|
powershell.exe -NoProfile -File .\tests\Download-File.Tests.ps1
|
||||||
powershell.exe -NoProfile -File .\tests\ConvertTo-RmmBoolean.Tests.ps1
|
powershell.exe -NoProfile -File .\tests\ConvertTo-RmmBoolean.Tests.ps1
|
||||||
|
powershell.exe -NoProfile -File .\tests\ConvertTo-RmmList.Tests.ps1
|
||||||
|
powershell.exe -NoProfile -File .\tests\Get-AllNetworkDrives.Tests.ps1
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,952 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Retention-aware cleanup for Windows workstations and servers.
|
||||||
|
.DESCRIPTION
|
||||||
|
Reads Cleanup* variables from the calling scope (including the RMM Run-Script
|
||||||
|
dot-source scope). Missing variables use Get-SystemCleanupDefaults. No param()
|
||||||
|
block deliberately: RMM variables must not be overwritten by parameter defaults.
|
||||||
|
ReportOnly defaults to true and assesses enabled and disabled categories separately.
|
||||||
|
Category rows include hibernation/VSS usage. Component-store savings are noted without running DISM analysis.
|
||||||
|
Server exclusions still apply. See rmm/Start-SystemCleanup.ps1 and
|
||||||
|
docs/SystemCleanup.md for options, server exclusions, and legacy operation mapping.
|
||||||
|
The core is self-contained; loading Tools.ps1 is the RMM shim's responsibility.
|
||||||
|
#>
|
||||||
|
|
||||||
|
function Get-SystemCleanupDefaults {
|
||||||
|
return [ordered]@{
|
||||||
|
CleanupReportOnly = $true
|
||||||
|
CleanupTempDays = 7
|
||||||
|
CleanupDiagnosticDays = 30
|
||||||
|
CleanupBackupDays = 30
|
||||||
|
CleanupSystemTemp = $true
|
||||||
|
CleanupOfficeStaging = $true
|
||||||
|
CleanupUserTemp = $true
|
||||||
|
CleanupServiceTemp = $true
|
||||||
|
CleanupCBSArchives = $true
|
||||||
|
CleanupActiveCBSLog = $false
|
||||||
|
CleanupCrashDumps = $true
|
||||||
|
CleanupWERArchives = $true
|
||||||
|
CleanupAutodeskInstallers = $false
|
||||||
|
CleanupRecycleBin = $false
|
||||||
|
CleanupDisableHibernation = $false
|
||||||
|
CleanupCompactSearch = $false
|
||||||
|
CleanupShadowCopies = $false
|
||||||
|
CleanupDownloadedExecutables = $false
|
||||||
|
CleanupDuplicateDownloads = $false
|
||||||
|
CleanupOutlookBackups = $false
|
||||||
|
CleanupITunesBackups = $false
|
||||||
|
CleanupAppleDownloads = $false
|
||||||
|
CleanupBrowserCache = $false
|
||||||
|
CleanupRevitJournals = $true
|
||||||
|
CleanupDeliveryOptimization = $false
|
||||||
|
CleanupComponentStore = $false
|
||||||
|
CleanupDiskCleanupItems = 'Standard'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupHandlers {
|
||||||
|
# Every VolumeCaches handler from Start-Cleanup.ps1, including disabled ones.
|
||||||
|
return @(
|
||||||
|
'Downloaded Program Files', 'Internet Cache Files', 'Offline Pages Files',
|
||||||
|
'Recycle Bin', 'Temporary Files', 'Thumbnail Cache', 'User file versions',
|
||||||
|
'Active Setup Temp Folders', 'BranchCache', 'Memory Dump Files',
|
||||||
|
'Old ChkDsk Files', 'RetailDemo Offline Content', 'System error memory dump files',
|
||||||
|
'System error minidump files', 'Temporary Setup Files', 'Windows Defender',
|
||||||
|
'Windows Error Reporting Archive Files', 'Windows Error Reporting Queue Files',
|
||||||
|
'Windows Error Reporting System Archive Files', 'Windows Error Reporting System Queue Files',
|
||||||
|
'Windows Error Reporting Temp Files', 'Service Pack Cleanup', 'Update Cleanup',
|
||||||
|
'Upgrade Discarded Files', 'Windows Upgrade Log Files', 'Previous Installations',
|
||||||
|
'Setup Log Files', 'Windows ESD installation files', 'Content Indexer Cleaner',
|
||||||
|
'Delivery Optimization Files', 'Device Driver Packages', 'GameNewsFiles',
|
||||||
|
'GameStatisticsFiles', 'GameUpdateFiles', 'Temporary Sync Files'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupDiskCleanupPresets {
|
||||||
|
$standard = @(
|
||||||
|
'Downloaded Program Files', 'Internet Cache Files', 'Thumbnail Cache',
|
||||||
|
'Active Setup Temp Folders', 'Temporary Setup Files', 'Windows Defender',
|
||||||
|
'RetailDemo Offline Content'
|
||||||
|
)
|
||||||
|
$updates = @('Service Pack Cleanup', 'Update Cleanup', 'Upgrade Discarded Files', 'Windows Upgrade Log Files')
|
||||||
|
$diagnostics = @(
|
||||||
|
'Memory Dump Files', 'Old ChkDsk Files', 'System error memory dump files',
|
||||||
|
'System error minidump files', 'Setup Log Files',
|
||||||
|
'Windows Error Reporting Archive Files', 'Windows Error Reporting Queue Files',
|
||||||
|
'Windows Error Reporting System Archive Files', 'Windows Error Reporting System Queue Files',
|
||||||
|
'Windows Error Reporting Temp Files'
|
||||||
|
)
|
||||||
|
return [ordered]@{
|
||||||
|
Standard = $standard
|
||||||
|
StandardAndUpdates = @($standard + $updates)
|
||||||
|
StandardUpdatesAndDiagnostics = @($standard + $updates + $diagnostics)
|
||||||
|
All = @(Get-SystemCleanupHandlers)
|
||||||
|
None = @()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Resolve-SystemCleanupDiskCleanupItems {
|
||||||
|
param($Value)
|
||||||
|
$items = @($Value | ForEach-Object { ([string]$_).Split(',') } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||||
|
if (-not $items.Count) { throw 'CleanupDiskCleanupItems cannot be blank. Select None to disable Disk Cleanup.' }
|
||||||
|
$presets = Get-SystemCleanupDiskCleanupPresets
|
||||||
|
if ($items.Count -eq 1) {
|
||||||
|
foreach ($preset in $presets.Keys) {
|
||||||
|
if ($items[0] -ieq $preset) {
|
||||||
|
return [pscustomobject]@{ Preset = $preset; Items = @($presets[$preset]) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Exact lists remain supported for existing/manual callers. Presets cannot be
|
||||||
|
# combined with other presets or handlers; in particular, None must stand alone.
|
||||||
|
$handlers = @(Get-SystemCleanupHandlers)
|
||||||
|
$selected = @()
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$match = @($handlers | Where-Object { $_ -ieq $item })
|
||||||
|
if (-not $match.Count) {
|
||||||
|
throw "Unknown Disk Cleanup preset or item: '$item'. Select one preset ($($presets.Keys -join ', ')) or exact handler names. Do not mix presets with other values."
|
||||||
|
}
|
||||||
|
if ($match[0] -notin $selected) { $selected += $match[0] }
|
||||||
|
}
|
||||||
|
return [pscustomobject]@{ Preset = 'Custom'; Items = @($selected) }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupOptions {
|
||||||
|
# Reject stale callers instead of silently re-enabling cleanup when their
|
||||||
|
# former false flag is ignored and the new Standard default takes effect.
|
||||||
|
if ($null -ne (Get-Variable -Name CleanupDiskCleanup -ErrorAction SilentlyContinue)) {
|
||||||
|
throw 'CleanupDiskCleanup has been removed. Remove it from Syncro/the caller and select CleanupDiskCleanupItems=None to disable Disk Cleanup.'
|
||||||
|
}
|
||||||
|
$options = @{}
|
||||||
|
$defaults = Get-SystemCleanupDefaults
|
||||||
|
foreach ($name in $defaults.Keys) {
|
||||||
|
$variable = Get-Variable -Name $name -ErrorAction SilentlyContinue
|
||||||
|
$value = if ($null -eq $variable) { $defaults[$name] } else { $variable.Value }
|
||||||
|
if ($defaults[$name] -is [bool]) {
|
||||||
|
# Do not cast RMM text to [bool]: [bool]'false' is true.
|
||||||
|
switch -Regex ([string]$value) {
|
||||||
|
'^(?i:\s*(\$?true|yes|1)\s*)$' { $value = $true; break }
|
||||||
|
'^(?i:\s*(\$?false|no|0)\s*)$' { $value = $false; break }
|
||||||
|
default { throw "$name must be true or false (received '$value')." }
|
||||||
|
}
|
||||||
|
} elseif ($defaults[$name] -is [int]) {
|
||||||
|
$number = 0
|
||||||
|
if (-not [int]::TryParse([string]$value, [ref]$number) -or $number -lt 1 -or $number -gt 3650) {
|
||||||
|
throw "$name must be a whole number from 1 to 3650."
|
||||||
|
}
|
||||||
|
$value = $number
|
||||||
|
} else {
|
||||||
|
$selection = Resolve-SystemCleanupDiskCleanupItems $value
|
||||||
|
$options.DiskCleanupPreset = $selection.Preset
|
||||||
|
$value = @($selection.Items)
|
||||||
|
}
|
||||||
|
$options[$name.Substring(7)] = $value
|
||||||
|
}
|
||||||
|
return $options
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupOS {
|
||||||
|
$os = @(Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop)
|
||||||
|
if ($os.Count -ne 1 -or $os[0].ProductType -notin @(1, 2, 3)) {
|
||||||
|
throw 'Cannot identify OS ProductType; no cleanup will run.'
|
||||||
|
}
|
||||||
|
return [pscustomobject]@{ IsServer = ($os[0].ProductType -ne 1); Caption = $os[0].Caption }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-SystemCleanupMessage {
|
||||||
|
param([string]$Message, [switch]$Detail)
|
||||||
|
# Host/information stream keeps logs out of helper return values, even with Tools loaded.
|
||||||
|
if ($Detail) { Write-Verbose "[SystemCleanup] $Message" }
|
||||||
|
else { Write-Host "[SystemCleanup] $Message" }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-SystemCleanupPath {
|
||||||
|
param([string]$Path, [string]$Root)
|
||||||
|
if ($Path -notmatch '^[A-Za-z]:\\' -or $Root -notmatch '^[A-Za-z]:\\') { return $false }
|
||||||
|
$full = [IO.Path]::GetFullPath($Path).TrimEnd('\')
|
||||||
|
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
|
||||||
|
if ($base.Length -le 2 -or ($full -ne $base -and -not $full.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase))) { return $false }
|
||||||
|
# Check every ancestor, not just the leaf. Never follow a junction into another tree.
|
||||||
|
$probe = $full
|
||||||
|
while ($probe.Length -gt 3) {
|
||||||
|
$item = Get-Item -LiteralPath $probe -Force -ErrorAction Stop
|
||||||
|
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { return $false }
|
||||||
|
$probe = Split-Path -Parent $probe
|
||||||
|
}
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupChildren {
|
||||||
|
param([string]$Root)
|
||||||
|
if (-not (Test-Path -LiteralPath $Root)) { return }
|
||||||
|
if (-not (Test-SystemCleanupPath $Root $Root)) {
|
||||||
|
Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
# Office staging has its own mutex/identity/retention rules. Generic temp scans
|
||||||
|
# must not bypass them or remove deferred user-cleanup helpers.
|
||||||
|
Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and $_.Name -ne 'EmberkomOfficeDeployment' }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupFiles {
|
||||||
|
param([string]$Root, [switch]$Recurse)
|
||||||
|
$pending = New-Object 'System.Collections.Generic.Stack[string]'
|
||||||
|
$pending.Push($Root)
|
||||||
|
while ($pending.Count) {
|
||||||
|
$directory = $pending.Pop()
|
||||||
|
foreach ($item in @(Get-SystemCleanupChildren $directory)) {
|
||||||
|
if ($item.PSIsContainer) { if ($Recurse) { $pending.Push($item.FullName) } }
|
||||||
|
else { $item }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Remove-SystemCleanupFile {
|
||||||
|
param($Context, [string]$Category, [string]$Root, [string]$Path, [datetime]$Cutoff)
|
||||||
|
if ($Category -ne 'OfficeStaging' -and $Path -match '(?i)(^|[\\/])EmberkomOfficeDeployment([\\/]|$)') { return }
|
||||||
|
if (-not (Test-SystemCleanupPath $Path $Root)) { return }
|
||||||
|
$file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
|
||||||
|
if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return }
|
||||||
|
if ($Context.Options.ReportOnly) {
|
||||||
|
# Each category is an independent estimate. A disabled category must not
|
||||||
|
# consume a file before an enabled category can assess the same file.
|
||||||
|
$candidates = $Context.Candidates[$Category]
|
||||||
|
if ($candidates.ContainsKey($file.FullName)) { return }
|
||||||
|
$candidates[$file.FullName] = [long]$file.Length
|
||||||
|
} elseif (-not $Context.Seen.Add($file.FullName)) { return }
|
||||||
|
$stat = $Context.Stats[$Category]
|
||||||
|
$stat.CandidateBytes += $file.Length
|
||||||
|
$stat.CandidateFiles++
|
||||||
|
if ($Context.Options.ReportOnly) { return }
|
||||||
|
try {
|
||||||
|
# Literal leaf deletion only. In-use files are skipped, never force-unlocked.
|
||||||
|
Remove-Item -LiteralPath $file.FullName -Force -ErrorAction Stop
|
||||||
|
$stat.RemovedBytes += $file.Length
|
||||||
|
$stat.RemovedFiles++
|
||||||
|
} catch {
|
||||||
|
$stat.FailedFiles++
|
||||||
|
Write-SystemCleanupMessage "Skipped '$Path': $($_.Exception.Message)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Clear-SystemCleanupTree {
|
||||||
|
param($Context, [string]$Category, [string]$Root, [datetime]$Cutoff,
|
||||||
|
[string[]]$Include = @('*'), [string[]]$Exclude = @(), [switch]$Recurse)
|
||||||
|
foreach ($file in @(Get-SystemCleanupFiles $Root -Recurse:$Recurse)) {
|
||||||
|
$match = @($Include | Where-Object { $file.Name -like $_ }).Count -gt 0
|
||||||
|
if ($match -and @($Exclude | Where-Object { $file.Name -like $_ }).Count -eq 0) {
|
||||||
|
Remove-SystemCleanupFile $Context $Category $Root $file.FullName $Cutoff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Ordinary temp/cache directories are retained. No recursive directory deletes.
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-SystemCleanupCategory {
|
||||||
|
param($Context, [string]$Name, [scriptblock]$Action)
|
||||||
|
$enabled = if ($Name -eq 'DiskCleanup') { @($Context.Options.DiskCleanupItems).Count -gt 0 } else { [bool]$Context.Options[$Name] }
|
||||||
|
if (-not $enabled -and -not $Context.Options.ReportOnly) { return }
|
||||||
|
$setting = "Cleanup$Name=$($enabled.ToString().ToLowerInvariant())"
|
||||||
|
$notes = ''
|
||||||
|
if ($Name -eq 'DiskCleanup') {
|
||||||
|
$selection = $Context.Options.DiskCleanupPreset
|
||||||
|
if ($selection -eq 'Custom') { $selection = $Context.Options.DiskCleanupItems -join ', ' }
|
||||||
|
$setting = "CleanupDiskCleanupItems=$selection"
|
||||||
|
$notes = if ($enabled) { "Selected handlers: $($Context.Options.DiskCleanupItems -join ', ')." } else { 'No handlers selected; Disk Cleanup will not run.' }
|
||||||
|
}
|
||||||
|
$blocked = $Context.OS.IsServer -and $Name -in @('ShadowCopies', 'DisableHibernation', 'CompactSearch',
|
||||||
|
'DownloadedExecutables', 'DuplicateDownloads', 'OutlookBackups', 'ITunesBackups', 'DiskCleanup')
|
||||||
|
$native = $Name -in @('DisableHibernation', 'CompactSearch', 'ShadowCopies', 'DeliveryOptimization', 'ComponentStore', 'DiskCleanup')
|
||||||
|
$Context.Stats[$Name] = [pscustomobject]@{
|
||||||
|
Category = $Name; Enabled = $enabled
|
||||||
|
CandidateFiles = $(if ($native -or $blocked) { $null } else { 0 })
|
||||||
|
CandidateBytes = $(if ($native -or $blocked) { $null } else { [long]0 })
|
||||||
|
UsageBytes = $null; UsageNote = ''
|
||||||
|
RemovedFiles = 0; RemovedBytes = [long]0; FailedFiles = 0
|
||||||
|
Status = $(if ($Context.Options.ReportOnly) { 'Preview' } else { 'Completed' })
|
||||||
|
EstimateStatus = $(if ($native) { 'Not estimated' } else { 'Estimated' })
|
||||||
|
Setting = $setting; Notes = $notes
|
||||||
|
}
|
||||||
|
if ($blocked) {
|
||||||
|
$Context.Stats[$Name].Status = 'Blocked on server'
|
||||||
|
$Context.Stats[$Name].EstimateStatus = 'Not assessed'
|
||||||
|
Write-SystemCleanupMessage "BLOCKED on server OS: $Name ($setting)" -Detail:$Context.Options.ReportOnly
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ($Context.Options.ReportOnly) {
|
||||||
|
if (-not $Context.ContainsKey('Candidates')) { $Context.Candidates = @{} }
|
||||||
|
$Context.Candidates[$Name] = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
$selection = if ($enabled) { 'enabled for apply' } else { 'disabled; assessment only' }
|
||||||
|
Write-SystemCleanupMessage "Assessing $Name ($selection)." -Detail
|
||||||
|
}
|
||||||
|
try { & $Action } catch {
|
||||||
|
$Context.Stats[$Name].Status = 'Failed'
|
||||||
|
$Context.Stats[$Name].EstimateStatus = 'Incomplete'
|
||||||
|
$Context.Stats[$Name].Notes = $_.Exception.Message
|
||||||
|
$Context.Errors++
|
||||||
|
Write-SystemCleanupMessage "$Name failed: $($_.Exception.Message)" -Detail:$Context.Options.ReportOnly
|
||||||
|
}
|
||||||
|
if (-not $Context.Options.ReportOnly) {
|
||||||
|
$s = $Context.Stats[$Name]
|
||||||
|
if ($native) { Write-SystemCleanupMessage "$Name : $($s.Status); native savings not measured." }
|
||||||
|
else { Write-SystemCleanupMessage ("{0}: {1} eligible files / {2:N2} MiB; {3} removed / {4:N2} MiB; {5} skipped; {6}" -f $Name, $s.CandidateFiles, ($s.CandidateBytes / 1MB), $s.RemovedFiles, ($s.RemovedBytes / 1MB), $s.FailedFiles, $s.Status) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Set-SystemCleanupSkipped {
|
||||||
|
param($Context, [string]$Category, [string]$Reason, [string]$Status = 'Skipped')
|
||||||
|
$Context.Stats[$Category].Status = $Status
|
||||||
|
$Context.Stats[$Category].EstimateStatus = 'Not assessed'
|
||||||
|
$Context.Stats[$Category].Notes = $Reason
|
||||||
|
Write-SystemCleanupMessage $Reason -Detail:$Context.Options.ReportOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupReportTotals {
|
||||||
|
param($Context)
|
||||||
|
$enabled = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
$disabled = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
foreach ($row in $Context.Stats.Values) {
|
||||||
|
if ($row.Status -eq 'Blocked on server' -or -not $Context.Candidates.ContainsKey($row.Category)) { continue }
|
||||||
|
$target = if ($row.Enabled) { $enabled } else { $disabled }
|
||||||
|
foreach ($entry in $Context.Candidates[$row.Category].GetEnumerator()) { $target[$entry.Key] = $entry.Value }
|
||||||
|
}
|
||||||
|
$enabledBytes = [long]0; $additionalBytes = [long]0; $additionalFiles = 0
|
||||||
|
foreach ($size in $enabled.Values) { $enabledBytes += $size }
|
||||||
|
foreach ($entry in $disabled.GetEnumerator()) {
|
||||||
|
if (-not $enabled.ContainsKey($entry.Key)) { $additionalBytes += $entry.Value; $additionalFiles++ }
|
||||||
|
}
|
||||||
|
return [pscustomobject]@{
|
||||||
|
EnabledFiles = $enabled.Count; EnabledBytes = $enabledBytes
|
||||||
|
AdditionalDisabledFiles = $additionalFiles; AdditionalDisabledBytes = $additionalBytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupVolumeId {
|
||||||
|
param($Reference)
|
||||||
|
# CIM references can be embedded instances or escaped WMI object-path strings.
|
||||||
|
$text = if ($Reference -is [string]) { $Reference } elseif ($Reference.DeviceID) { [string]$Reference.DeviceID } else { [string]$Reference }
|
||||||
|
$match = [regex]::Match($text, '(?i)Volume\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}')
|
||||||
|
if (-not $match.Success) { throw 'Cannot identify the volume in a shadow-storage reference.' }
|
||||||
|
return $match.Value.ToLowerInvariant()
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupShadowStorageDiagnostic {
|
||||||
|
$volumes = @(Get-CimInstance -ClassName Win32_Volume -ErrorAction Stop)
|
||||||
|
$systemVolume = @($volumes | Where-Object { $_.DriveLetter -eq $env:SystemDrive })
|
||||||
|
if ($systemVolume.Count -ne 1) { throw 'Cannot uniquely identify the system volume.' }
|
||||||
|
$systemId = Get-SystemCleanupVolumeId $systemVolume[0]
|
||||||
|
$storage = @(Get-CimInstance -ClassName Win32_ShadowStorage -ErrorAction Stop | Where-Object {
|
||||||
|
(Get-SystemCleanupVolumeId $_.Volume) -eq $systemId
|
||||||
|
})
|
||||||
|
if (-not $storage.Count) { return [pscustomobject]@{UsedBytes=[decimal]0; AllocatedBytes=[decimal]0; StoredOn=''} }
|
||||||
|
$used = [decimal]0; $allocated = [decimal]0; $locations = @()
|
||||||
|
foreach ($item in $storage) {
|
||||||
|
# A missing measurement must not be converted to zero.
|
||||||
|
foreach ($property in @('UsedSpace', 'AllocatedSpace')) {
|
||||||
|
$bytes = [uint64]0
|
||||||
|
if (-not [uint64]::TryParse([string]$item.$property, [ref]$bytes)) { throw "Invalid shadow-storage $property." }
|
||||||
|
if ($property -eq 'UsedSpace') { $used += $bytes } else { $allocated += $bytes }
|
||||||
|
}
|
||||||
|
$targetId = Get-SystemCleanupVolumeId $item.DiffVolume
|
||||||
|
$target = @($volumes | Where-Object { (Get-SystemCleanupVolumeId $_) -eq $targetId })
|
||||||
|
$locations += if ($target.Count -eq 1 -and $target[0].DriveLetter) { $target[0].DriveLetter } else { 'unmounted/unknown volume' }
|
||||||
|
}
|
||||||
|
return [pscustomobject]@{UsedBytes=$used; AllocatedBytes=$allocated; StoredOn=(($locations | Select-Object -Unique) -join ', ')}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupDiagnostics {
|
||||||
|
param($Context)
|
||||||
|
$diagnostics = [ordered]@{}
|
||||||
|
if (-not $Context.Options.ReportOnly) { return $diagnostics }
|
||||||
|
if (-not $Context.OS.IsServer) {
|
||||||
|
# Store usage separately from candidate savings so totals do not overpromise.
|
||||||
|
$hibernation = $Context.Stats['DisableHibernation']
|
||||||
|
$hibernation.UsageBytes = $null
|
||||||
|
$hibernation.UsageNote = 'file size; excluded from totals'
|
||||||
|
try {
|
||||||
|
$path = Join-Path $env:SystemDrive 'hiberfil.sys'
|
||||||
|
$file = Get-Item -LiteralPath $path -Force -ErrorAction Stop
|
||||||
|
if ($file.PSIsContainer -or ($file.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Unexpected hibernation file type.' }
|
||||||
|
$hibernation.UsageBytes = [long]$file.Length
|
||||||
|
} catch [System.Management.Automation.ItemNotFoundException] {
|
||||||
|
$hibernation.UsageBytes = [long]0
|
||||||
|
} catch {
|
||||||
|
Write-SystemCleanupMessage "Hibernation diagnostic: $($_.Exception.Message)" -Detail
|
||||||
|
$hibernation.UsageNote = 'unavailable (file inspection failed; see verbose)'
|
||||||
|
}
|
||||||
|
$shadows = $Context.Stats['ShadowCopies']
|
||||||
|
$shadows.UsageBytes = $null
|
||||||
|
$shadows.UsageNote = 'VSS used; excluded from totals'
|
||||||
|
try {
|
||||||
|
$storage = Get-SystemCleanupShadowStorageDiagnostic
|
||||||
|
$shadows.UsageBytes = $storage.UsedBytes
|
||||||
|
if ($storage.UsedBytes -gt 0) { $shadows.UsageNote += '; newest retained' }
|
||||||
|
if ($storage.StoredOn) { $shadows.UsageNote += '; stored on ' + $storage.StoredOn }
|
||||||
|
Write-SystemCleanupMessage ('Shadow storage for {0}: {1:N2} MiB used / {2:N2} MiB allocated; stored on {3}' -f $env:SystemDrive, ($storage.UsedBytes / 1MB), ($storage.AllocatedBytes / 1MB), $storage.StoredOn) -Detail
|
||||||
|
} catch {
|
||||||
|
Write-SystemCleanupMessage "Shadow-storage diagnostic: $($_.Exception.Message)" -Detail
|
||||||
|
$shadows.UsageNote = 'unavailable (storage inspection failed; see verbose)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Avoid slow DISM analysis during previews; potential savings are not measured.
|
||||||
|
$diagnostics.ComponentStore = 'not analyzed; removing superseded updates may free substantial space, or little/none.'
|
||||||
|
return $diagnostics
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-SystemCleanupReport {
|
||||||
|
param($Context)
|
||||||
|
Write-SystemCleanupMessage 'REPORT ONLY - no cleanup performed.'
|
||||||
|
$totals = Get-SystemCleanupReportTotals $Context
|
||||||
|
Write-SystemCleanupMessage ('Known savings: ENABLED {0:N2} MiB ({1:N0} files); additional DISABLED {2:N2} MiB ({3:N0} files).' -f ($totals.EnabledBytes / 1MB), $totals.EnabledFiles, ($totals.AdditionalDisabledBytes / 1MB), $totals.AdditionalDisabledFiles)
|
||||||
|
if ($Context.ContainsKey('Diagnostics') -and $Context.Diagnostics.Count) {
|
||||||
|
Write-SystemCleanupMessage 'DIAGNOSTICS - potential, excluded from savings totals'
|
||||||
|
foreach ($entry in $Context.Diagnostics.GetEnumerator()) {
|
||||||
|
Write-SystemCleanupMessage (" {0}: {1}" -f $entry.Key, $entry.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-SystemCleanupMessage "Retention: temp $($Context.Options.TempDays)d; diagnostics $($Context.Options.DiagnosticDays)d; backups $($Context.Options.BackupDays)d."
|
||||||
|
Write-SystemCleanupMessage ('{0,-25} {1,8} {2,11} {3}' -f 'Category', 'Files', 'MiB', 'Notes')
|
||||||
|
foreach ($group in @('Enabled', 'Disabled', 'Blocked')) {
|
||||||
|
$rows = @($Context.Stats.Values | Where-Object {
|
||||||
|
if ($group -eq 'Blocked') { $_.Status -eq 'Blocked on server' }
|
||||||
|
else { $_.Status -ne 'Blocked on server' -and $_.Enabled -eq ($group -eq 'Enabled') }
|
||||||
|
} | Sort-Object Category)
|
||||||
|
$heading = switch ($group) {
|
||||||
|
Enabled { 'ENABLED - would run with current settings' }
|
||||||
|
Disabled { 'DISABLED - potential only; will not run' }
|
||||||
|
Blocked { 'BLOCKED ON SERVER - cannot run' }
|
||||||
|
}
|
||||||
|
Write-SystemCleanupMessage $heading
|
||||||
|
if (-not $rows.Count) { Write-SystemCleanupMessage ' None.' }
|
||||||
|
foreach ($row in $rows) {
|
||||||
|
$files = '-'; $size = '-'; $notes = @(); $bytes = $null
|
||||||
|
if ($row.UsageNote) {
|
||||||
|
$bytes = $row.UsageBytes
|
||||||
|
$notes += $row.UsageNote
|
||||||
|
} elseif ($row.EstimateStatus -eq 'Not estimated') { $notes += 'not estimated' }
|
||||||
|
elseif ($row.EstimateStatus -eq 'Not assessed') { $notes += 'not assessed' }
|
||||||
|
elseif ($null -ne $row.CandidateBytes) {
|
||||||
|
$files = '{0:N0}' -f $row.CandidateFiles
|
||||||
|
$bytes = $row.CandidateBytes
|
||||||
|
} else { $notes += 'unavailable' }
|
||||||
|
if ($null -ne $bytes) { $size = if ($bytes -gt 0 -and $bytes -lt (0.01 * 1MB)) { '<0.01' } else { '{0:N2}' -f ($bytes / 1MB) } }
|
||||||
|
if ($row.Status -notin @('Preview', 'Blocked on server')) { $notes += $row.Status }
|
||||||
|
if ($row.EstimateStatus -eq 'Incomplete') { $notes += 'incomplete' }
|
||||||
|
if ($row.FailedFiles) { $notes += "$($row.FailedFiles) files skipped" }
|
||||||
|
if ($row.Category -eq 'DiskCleanup') {
|
||||||
|
$notes += "$($Context.Options.DiskCleanupPreset) ($(@($Context.Options.DiskCleanupItems).Count) handlers)"
|
||||||
|
if (-not $row.Enabled) { $notes += 'will not run' }
|
||||||
|
# The selected handler list is configuration detail, not a warning.
|
||||||
|
if ($row.Status -eq 'Failed') { $notes += $row.Notes }
|
||||||
|
else { Write-SystemCleanupMessage "Disk Cleanup: $($row.Notes)" -Detail }
|
||||||
|
} elseif ($row.Category -eq 'ComponentStore') {
|
||||||
|
$notes += 'background task on apply'
|
||||||
|
if ($row.Notes) { $notes += $row.Notes }
|
||||||
|
} elseif ($row.Notes) { $notes += $row.Notes }
|
||||||
|
# Keep every category on one line, including multiline native errors.
|
||||||
|
$noteText = ($notes -join '; ') -replace '\s+', ' '
|
||||||
|
if ($noteText.Length -gt 180) {
|
||||||
|
Write-SystemCleanupMessage "$($row.Category): $noteText" -Detail
|
||||||
|
$noteText = $noteText.Substring(0, 163) + '... (see verbose)'
|
||||||
|
}
|
||||||
|
Write-SystemCleanupMessage ('{0,-25} {1,8} {2,11} {3}' -f $row.Category, $files, $size, $noteText.Trim())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-SystemCleanupMessage 'Totals count each path once; rows may overlap. Unknown/unassessed savings excluded; disk space freed may differ.'
|
||||||
|
Write-SystemCleanupMessage 'Settings: Cleanup<Category>; DiskCleanup uses CleanupDiskCleanupItems. Full diagnostics: $VerbosePreference="Continue".'
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-SystemCleanupAppRunning {
|
||||||
|
param([string[]]$Names)
|
||||||
|
# Inventory failure aborts the category instead of assuming the app is closed.
|
||||||
|
return @((Get-Process -ErrorAction Stop) | Where-Object { $_.ProcessName -in $Names }).Count -gt 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-SystemCleanupProcess {
|
||||||
|
param($Context, [string]$FileName, [string]$Arguments)
|
||||||
|
$nativeDir = if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { 'Sysnative' } else { 'System32' }
|
||||||
|
$executable = Join-Path $env:SystemRoot "$nativeDir\$FileName"
|
||||||
|
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw "Unavailable: $executable" }
|
||||||
|
Write-SystemCleanupMessage "$FileName $Arguments (native operation; size not estimated)" -Detail:$Context.Options.ReportOnly
|
||||||
|
if ($Context.Options.ReportOnly) { return }
|
||||||
|
$process = Start-Process -FilePath $executable -ArgumentList $Arguments -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
|
||||||
|
if ($process.ExitCode -ne 0) { throw "$FileName returned exit code $($process.ExitCode)." }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Remove-SystemCleanupDuplicates {
|
||||||
|
param($Context, [string]$Root, [datetime]$Cutoff)
|
||||||
|
$files = @(Get-SystemCleanupFiles $Root)
|
||||||
|
foreach ($duplicate in $files) {
|
||||||
|
if ($duplicate.LastWriteTimeUtc -ge $Cutoff -or $duplicate.BaseName -notmatch '^(.*) \([0-9]+\)$') { continue }
|
||||||
|
$originalName = $Matches[1] + $duplicate.Extension
|
||||||
|
$original = @($files | Where-Object { $_.Name -ieq $originalName -and $_.Length -eq $duplicate.Length })
|
||||||
|
if ($original.Count -ne 1) { continue }
|
||||||
|
if (-not (Test-SystemCleanupPath $duplicate.FullName $Root) -or -not (Test-SystemCleanupPath $original[0].FullName $Root)) { continue }
|
||||||
|
$originalStream = $null; $duplicateStream = $null
|
||||||
|
try {
|
||||||
|
# Hold read handles through deletion, refusing concurrent writers while hashing.
|
||||||
|
$sharing = [IO.FileShare]::Read -bor [IO.FileShare]::Delete
|
||||||
|
$originalStream = [IO.File]::Open($original[0].FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, $sharing)
|
||||||
|
$duplicateStream = [IO.File]::Open($duplicate.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, $sharing)
|
||||||
|
$hash = Get-FileHash -InputStream $duplicateStream -Algorithm SHA256 -ErrorAction Stop
|
||||||
|
$other = Get-FileHash -InputStream $originalStream -Algorithm SHA256 -ErrorAction Stop
|
||||||
|
if ($hash.Hash -eq $other.Hash) { Remove-SystemCleanupFile $Context 'DuplicateDownloads' $Root $duplicate.FullName $Cutoff }
|
||||||
|
} catch { Write-SystemCleanupMessage "Skipping changing/in-use duplicate '$($duplicate.FullName)': $($_.Exception.Message)" }
|
||||||
|
finally {
|
||||||
|
if ($duplicateStream) { $duplicateStream.Dispose() }
|
||||||
|
if ($originalStream) { $originalStream.Dispose() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Remove-SystemCleanupBundle {
|
||||||
|
param($Context, [string]$Category, [string]$Root, [datetime]$Cutoff)
|
||||||
|
# Backups and extracted installers are units: keep the entire unit if anything is recent,
|
||||||
|
# linked or inaccessible. Preflight in-use files before any deletion.
|
||||||
|
if (-not (Test-SystemCleanupPath $Root $Root)) { return }
|
||||||
|
$items = New-Object 'System.Collections.Generic.List[object]'
|
||||||
|
$pending = New-Object 'System.Collections.Generic.Stack[string]'
|
||||||
|
$pending.Push($Root)
|
||||||
|
while ($pending.Count) {
|
||||||
|
$dir = $pending.Pop()
|
||||||
|
foreach ($item in @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop)) {
|
||||||
|
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or $item.LastWriteTimeUtc -ge $Cutoff) { return }
|
||||||
|
$items.Add($item)
|
||||||
|
if ($item.PSIsContainer) { $pending.Push($item.FullName) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((Get-Item -LiteralPath $Root -Force).LastWriteTimeUtc -ge $Cutoff) { return }
|
||||||
|
if (-not $Context.Options.ReportOnly) {
|
||||||
|
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
|
||||||
|
try {
|
||||||
|
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
|
||||||
|
$probe.Dispose()
|
||||||
|
} catch { Write-SystemCleanupMessage "Retaining in-use bundle: $Root"; return }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
|
||||||
|
Remove-SystemCleanupFile $Context $Category $Root $file.FullName $Cutoff
|
||||||
|
}
|
||||||
|
if (-not $Context.Options.ReportOnly) {
|
||||||
|
foreach ($dir in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending) + @(Get-Item -LiteralPath $Root -Force)) {
|
||||||
|
if ((Test-SystemCleanupPath $dir.FullName $Root) -and @(Get-ChildItem -LiteralPath $dir.FullName -Force -ErrorAction Stop).Count -eq 0) {
|
||||||
|
# Directory.Delete without recursion cannot delete a newly populated directory.
|
||||||
|
[IO.Directory]::Delete($dir.FullName, $false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupOfficeStagingRoots {
|
||||||
|
param([string[]]$Profiles)
|
||||||
|
@(
|
||||||
|
(Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment')
|
||||||
|
(Join-Path $env:SystemRoot 'Temp\EmberkomOfficeDeployment')
|
||||||
|
(Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment')
|
||||||
|
(Join-Path $env:ProgramData 'EmberkomOfficeDeployment')
|
||||||
|
foreach ($profile in $Profiles) { Join-Path $profile 'AppData\Local\Temp\EmberkomOfficeDeployment' }
|
||||||
|
) | Sort-Object -Unique
|
||||||
|
}
|
||||||
|
|
||||||
|
function New-SystemCleanupOfficeMutex {
|
||||||
|
return New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
|
||||||
|
}
|
||||||
|
|
||||||
|
function Clear-SystemCleanupOfficeStaging {
|
||||||
|
param($Context, [string[]]$Roots, [datetime]$Cutoff)
|
||||||
|
$rootsPresent = @($Roots | Select-Object -Unique | Where-Object { Test-Path -LiteralPath $_ })
|
||||||
|
if (-not $rootsPresent.Count) { return }
|
||||||
|
$mutex = New-SystemCleanupOfficeMutex
|
||||||
|
$acquired = $false; $retained = 0
|
||||||
|
try {
|
||||||
|
try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true }
|
||||||
|
if (-not $acquired) { Set-SystemCleanupSkipped $Context 'OfficeStaging' 'Office deployment is running; staging retained.'; return }
|
||||||
|
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
|
||||||
|
if (@($processes | Where-Object { $_.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe') }).Count) {
|
||||||
|
Set-SystemCleanupSkipped $Context 'OfficeStaging' 'An installer is running; staging retained.'; return
|
||||||
|
}
|
||||||
|
# Match Install-MicrosoftOffice365's disposable artifact allowlist. Never delete
|
||||||
|
# options, logs, XML, user helpers, task markers, locks or the workspace itself.
|
||||||
|
$names = @('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json',
|
||||||
|
'MicrosoftEdgeWebview2Setup.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe')
|
||||||
|
foreach ($root in $rootsPresent) {
|
||||||
|
if (-not (Test-SystemCleanupPath $root $root)) { $retained++; continue }
|
||||||
|
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
|
||||||
|
try {
|
||||||
|
if (-not (Test-SystemCleanupPath $folder.FullName $root)) { throw 'Linked or unsafe workspace.' }
|
||||||
|
$markerPath = Join-Path $folder.FullName 'options.json'
|
||||||
|
if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { throw 'Missing deployment identity.' }
|
||||||
|
if (-not (Test-SystemCleanupPath $markerPath $root)) { throw 'Linked deployment identity.' }
|
||||||
|
$marker = Get-Item -LiteralPath $markerPath -Force -ErrorAction Stop
|
||||||
|
if ($marker.Length -gt 64KB) { throw 'Oversized deployment identity.' }
|
||||||
|
$options = Get-Content -LiteralPath $markerPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
|
||||||
|
if ($options.ProductId -notin @('O365BusinessRetail','O365BusinessEEANoTeamsRetail','O365ProPlusRetail','O365ProPlusEEANoTeamsRetail') -or
|
||||||
|
$options.OfficeArchitecture -notin @('32','64') -or $options.UpdateChannel -notin @('Current','MonthlyEnterprise','SemiAnnual')) { throw 'Unrecognized deployment identity.' }
|
||||||
|
if ($folder.LastWriteTimeUtc -ge $Cutoff -or $marker.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent deployment.' }
|
||||||
|
foreach ($process in $processes) {
|
||||||
|
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
|
||||||
|
if ($value -and $value.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0) { throw 'Workspace is referenced by a running process.' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$items = New-Object 'System.Collections.Generic.List[object]'
|
||||||
|
$pending = New-Object 'System.Collections.Generic.Stack[string]'
|
||||||
|
foreach ($name in $names) {
|
||||||
|
$target = Join-Path $folder.FullName $name
|
||||||
|
if (Test-Path -LiteralPath $target) { $pending.Push($target) }
|
||||||
|
}
|
||||||
|
while ($pending.Count) {
|
||||||
|
$target = $pending.Pop()
|
||||||
|
if (-not (Test-SystemCleanupPath $target $folder.FullName)) { throw 'Linked staging artifact.' }
|
||||||
|
$item = Get-Item -LiteralPath $target -Force -ErrorAction Stop
|
||||||
|
if ($item.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent staging artifact.' }
|
||||||
|
$items.Add($item)
|
||||||
|
if ($item.PSIsContainer) {
|
||||||
|
foreach ($child in @(Get-ChildItem -LiteralPath $target -Force -ErrorAction Stop)) { $pending.Push($child.FullName) }
|
||||||
|
} else {
|
||||||
|
# Probe in preview too; in-use data is not an eligible estimate.
|
||||||
|
$probe = [IO.File]::Open($item.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
|
||||||
|
$probe.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
|
||||||
|
Remove-SystemCleanupFile $Context 'OfficeStaging' $folder.FullName $file.FullName $Cutoff
|
||||||
|
}
|
||||||
|
if (-not $Context.Options.ReportOnly) {
|
||||||
|
foreach ($directory in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending)) {
|
||||||
|
if ((Test-SystemCleanupPath $directory.FullName $folder.FullName) -and @(Get-ChildItem -LiteralPath $directory.FullName -Force -ErrorAction Stop).Count -eq 0) {
|
||||||
|
[IO.Directory]::Delete($directory.FullName, $false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
$retained++
|
||||||
|
Write-SystemCleanupMessage "Office staging retained at $($folder.FullName): $($_.Exception.Message)" -Detail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($retained) { $Context.Stats.OfficeStaging.Notes = "$retained folder(s) retained: recent, active, unrecognized or unsafe; see verbose." }
|
||||||
|
} finally {
|
||||||
|
if ($acquired) { $mutex.ReleaseMutex() }
|
||||||
|
$mutex.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-SystemCleanupRecycleDate {
|
||||||
|
param([string]$MetadataPath)
|
||||||
|
if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' }
|
||||||
|
$bytes = [IO.File]::ReadAllBytes($MetadataPath)
|
||||||
|
if ($bytes.Length -lt 24) { throw 'Truncated Recycle Bin metadata.' }
|
||||||
|
$version = [BitConverter]::ToInt64($bytes, 0)
|
||||||
|
if ($version -notin @(1, 2)) { throw "Unknown Recycle Bin metadata version: $version" }
|
||||||
|
if ($version -eq 1 -and $bytes.Length -ne 544) { throw 'Invalid version 1 Recycle Bin metadata length.' }
|
||||||
|
if ($version -eq 2) {
|
||||||
|
if ($bytes.Length -lt 28) { throw 'Truncated version 2 Recycle Bin metadata.' }
|
||||||
|
$characters = [BitConverter]::ToUInt32($bytes, 24)
|
||||||
|
if ($characters -eq 0 -or (28L + 2L * $characters) -ne $bytes.Length) { throw 'Invalid version 2 Recycle Bin path length.' }
|
||||||
|
}
|
||||||
|
return [DateTime]::FromFileTimeUtc([BitConverter]::ToInt64($bytes, 16))
|
||||||
|
}
|
||||||
|
|
||||||
|
function Clear-SystemCleanupRecycleBin {
|
||||||
|
param($Context, [string]$Root, [datetime]$Cutoff)
|
||||||
|
foreach ($sid in @(Get-SystemCleanupChildren $Root | Where-Object { $_.PSIsContainer -and $_.Name -match '^S-1-' })) {
|
||||||
|
foreach ($metadata in @(Get-SystemCleanupFiles $sid.FullName | Where-Object { $_.Name -clike '$I*' })) {
|
||||||
|
try {
|
||||||
|
if ((Get-SystemCleanupRecycleDate $metadata.FullName) -ge $Cutoff) { continue }
|
||||||
|
$payload = Join-Path $sid.FullName ('$R' + $metadata.Name.Substring(2))
|
||||||
|
if (Test-Path -LiteralPath $payload) {
|
||||||
|
if (-not (Test-SystemCleanupPath $payload $sid.FullName)) { continue }
|
||||||
|
$item = Get-Item -LiteralPath $payload -Force -ErrorAction Stop
|
||||||
|
if ($item.PSIsContainer) {
|
||||||
|
Remove-SystemCleanupBundle $Context 'RecycleBin' $payload ([datetime]::MaxValue)
|
||||||
|
} else { Remove-SystemCleanupFile $Context 'RecycleBin' $sid.FullName $payload ([datetime]::MaxValue) }
|
||||||
|
}
|
||||||
|
# Keep metadata if the payload could not be fully removed.
|
||||||
|
if ($Context.Options.ReportOnly -or -not (Test-Path -LiteralPath $payload)) {
|
||||||
|
Remove-SystemCleanupFile $Context 'RecycleBin' $sid.FullName $metadata.FullName ([datetime]::MaxValue)
|
||||||
|
}
|
||||||
|
} catch { Write-SystemCleanupMessage "Skipping recycle item '$($metadata.FullName)': $($_.Exception.Message)" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-SystemCleanupDiskCleanup {
|
||||||
|
param($Context)
|
||||||
|
# Defence in depth: even direct helper calls cannot run cleanmgr on a server.
|
||||||
|
if ($Context.OS.IsServer) { throw 'Disk Cleanup is blocked on server OSes.' }
|
||||||
|
$selected = @($Context.Options.DiskCleanupItems)
|
||||||
|
Write-SystemCleanupMessage "Disk Cleanup selection: $($Context.Options.DiskCleanupPreset); selected items: $($selected -join ', '). Windows controls retention for these handlers." -Detail
|
||||||
|
if ($Context.Options.ReportOnly) {
|
||||||
|
$unselected = @((Get-SystemCleanupHandlers) | Where-Object { $_ -notin $selected })
|
||||||
|
Write-SystemCleanupMessage "Disk Cleanup items not selected (not run during apply): $($unselected -join ', '). Handler savings are not estimated." -Detail
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (-not $selected.Count) { return }
|
||||||
|
if (Test-SystemCleanupAppRunning @('cleanmgr')) { throw 'Another Disk Cleanup process is running.' }
|
||||||
|
$base = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches'
|
||||||
|
$keys = @(Get-ChildItem -LiteralPath $base -ErrorAction Stop)
|
||||||
|
# Pick an unused slot across ALL handlers, so a stale unrelated selection cannot run.
|
||||||
|
$used = @{}
|
||||||
|
foreach ($key in $keys) {
|
||||||
|
foreach ($valueName in $key.GetValueNames()) { $used[$valueName] = $true }
|
||||||
|
}
|
||||||
|
$slot = 0
|
||||||
|
foreach ($candidate in 1000..9999) {
|
||||||
|
if (-not $used.ContainsKey(('StateFlags{0:D4}' -f $candidate))) { $slot = $candidate; break }
|
||||||
|
}
|
||||||
|
if (-not $slot) { throw 'No unused Disk Cleanup settings slot is available.' }
|
||||||
|
$flag = 'StateFlags{0:D4}' -f $slot
|
||||||
|
$written = New-Object 'System.Collections.Generic.List[string]'
|
||||||
|
try {
|
||||||
|
foreach ($key in $keys) {
|
||||||
|
if ($key.PSChildName -in $selected) {
|
||||||
|
# Register before writing, so a partially successful write is restored too.
|
||||||
|
$written.Add($key.PSPath)
|
||||||
|
New-ItemProperty -LiteralPath $key.PSPath -Name $flag -Value 2 -PropertyType DWord -ErrorAction Stop | Out-Null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($written.Count) { Invoke-SystemCleanupProcess $Context 'cleanmgr.exe' "/sagerun:$slot" }
|
||||||
|
else { Write-SystemCleanupMessage 'None of the selected Disk Cleanup handlers are installed.' }
|
||||||
|
} finally {
|
||||||
|
# Wait for cleanmgr before removing ONLY the temporary settings owned by this run.
|
||||||
|
foreach ($path in $written) {
|
||||||
|
try { Remove-ItemProperty -LiteralPath $path -Name $flag -ErrorAction Stop }
|
||||||
|
catch { Write-SystemCleanupMessage "Could not remove temporary Disk Cleanup setting $path/$flag : $($_.Exception.Message)"; $Context.Errors++ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-SystemCleanupShadows {
|
||||||
|
param($Context)
|
||||||
|
if ($Context.OS.IsServer) { throw 'Shadow-copy deletion is blocked on server OSes.' }
|
||||||
|
$volumes = @(Get-CimInstance -ClassName Win32_Volume -ErrorAction Stop | Where-Object { $_.DriveLetter -eq $env:SystemDrive })
|
||||||
|
if ($volumes.Count -ne 1) { throw 'Could not uniquely identify the system volume.' }
|
||||||
|
$shadows = @(Get-CimInstance -ClassName Win32_ShadowCopy -ErrorAction Stop |
|
||||||
|
Where-Object { $_.VolumeName -eq $volumes[0].DeviceID } | Sort-Object InstallDate -Descending)
|
||||||
|
# Use exact IDs from the inventory; never loop /Oldest after a failed deletion.
|
||||||
|
foreach ($shadow in @($shadows | Select-Object -Skip 1)) {
|
||||||
|
if ($shadow.ID -notmatch '^\{[0-9a-fA-F-]{36}\}$') { throw 'Invalid shadow-copy identifier.' }
|
||||||
|
Invoke-SystemCleanupProcess $Context 'vssadmin.exe' "delete shadows /Shadow=$($shadow.ID) /Quiet"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-SystemCleanupSearchCompaction {
|
||||||
|
param($Context)
|
||||||
|
if ($Context.OS.IsServer) { throw 'Search compaction is blocked on server OSes.' }
|
||||||
|
$database = Join-Path $env:ProgramData 'Microsoft\Search\Data\Applications\Windows\Windows.edb'
|
||||||
|
if (-not (Test-Path -LiteralPath $database -PathType Leaf)) { return }
|
||||||
|
if (-not (Test-SystemCleanupPath $database (Split-Path -Parent $database))) { return }
|
||||||
|
if ($Context.Options.ReportOnly) {
|
||||||
|
Write-SystemCleanupMessage "Would compact $database; size savings cannot be estimated." -Detail
|
||||||
|
return
|
||||||
|
}
|
||||||
|
$drive = New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($database))
|
||||||
|
if ($drive.AvailableFreeSpace -lt ((Get-Item -LiteralPath $database).Length * 1.2)) { throw 'Insufficient free space for a temporary Search database (120% reserve required).' }
|
||||||
|
$service = Get-Service -Name WSearch -ErrorAction Stop
|
||||||
|
if ($service.Status -notin @('Running', 'Stopped')) { throw 'Windows Search is transitioning; try again later.' }
|
||||||
|
$wasRunning = $service.Status -eq 'Running'
|
||||||
|
try {
|
||||||
|
# Preserve the original startup configuration, including delayed automatic start.
|
||||||
|
if ($wasRunning) {
|
||||||
|
Stop-Service -Name WSearch -ErrorAction Stop
|
||||||
|
$service.WaitForStatus('Stopped', [timespan]::FromSeconds(30))
|
||||||
|
}
|
||||||
|
$temporary = Join-Path (Split-Path -Parent $database) ('SystemCleanup-' + [guid]::NewGuid().ToString('N') + '.edb')
|
||||||
|
Invoke-SystemCleanupProcess $Context 'esentutl.exe' ('/d "{0}" /t"{1}" /o' -f $database, $temporary)
|
||||||
|
} finally {
|
||||||
|
if ($wasRunning) { Start-Service -Name WSearch -ErrorAction Stop }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-SystemCleanup {
|
||||||
|
param([hashtable]$Options)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$os = Get-SystemCleanupOS
|
||||||
|
if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) {
|
||||||
|
throw 'Run this script in 64-bit PowerShell to avoid filesystem and registry redirection.'
|
||||||
|
}
|
||||||
|
if (-not $Options.ReportOnly) {
|
||||||
|
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
|
$principal = New-Object Security.Principal.WindowsPrincipal $identity
|
||||||
|
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Apply mode requires an elevated Administrator or SYSTEM token.' }
|
||||||
|
}
|
||||||
|
# One run per machine, including the registry slot allocation and native operations.
|
||||||
|
$mutex = New-Object Threading.Mutex($false, 'Global\Emberkom.Start-SystemCleanup')
|
||||||
|
$acquired = $false
|
||||||
|
try {
|
||||||
|
try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true }
|
||||||
|
if (-not $acquired) { throw 'Another Start-SystemCleanup run is already active.' }
|
||||||
|
$context = @{
|
||||||
|
Options = $Options; OS = $os; Stats = [ordered]@{}; Errors = 0; Candidates = @{}
|
||||||
|
Seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
}
|
||||||
|
Write-SystemCleanupMessage "OS: $($os.Caption); server: $($os.IsServer); report only: $($Options.ReportOnly)"
|
||||||
|
$now = [datetime]::UtcNow
|
||||||
|
$tempCutoff = $now.AddDays(-$Options.TempDays)
|
||||||
|
$diagnosticCutoff = $now.AddDays(-$Options.DiagnosticDays)
|
||||||
|
$backupCutoff = $now.AddDays(-$Options.BackupDays)
|
||||||
|
# Inventory registered profiles, including custom profile roots; no C:\Users wildcard.
|
||||||
|
$profiles = @(Get-CimInstance -ClassName Win32_UserProfile -ErrorAction Stop |
|
||||||
|
Where-Object { -not $_.Special -and $_.LocalPath } | Select-Object -ExpandProperty LocalPath -Unique)
|
||||||
|
$serviceProfiles = @(
|
||||||
|
(Join-Path $env:SystemRoot 'System32\config\systemprofile'),
|
||||||
|
(Join-Path $env:SystemRoot 'ServiceProfiles\LocalService'),
|
||||||
|
(Join-Path $env:SystemRoot 'ServiceProfiles\NetworkService')
|
||||||
|
)
|
||||||
|
if ([Environment]::Is64BitOperatingSystem) { $serviceProfiles += Join-Path $env:SystemRoot 'SysWOW64\config\systemprofile' }
|
||||||
|
$allProfiles = @($profiles + $serviceProfiles | Select-Object -Unique)
|
||||||
|
# Generic temp cleaning must not bypass the AutoCAD process check or dump retention.
|
||||||
|
$tempExclusions = @('*.ac$', '*.sv$', '*.dmp')
|
||||||
|
Invoke-SystemCleanupCategory $context 'SystemTemp' {
|
||||||
|
foreach ($relative in @('Temp', 'SystemTemp')) {
|
||||||
|
Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot $relative) $tempCutoff -Exclude $tempExclusions -Recurse
|
||||||
|
}
|
||||||
|
# Includes .evtx, computer-name logs, AppxErrorReport files, and Chocolatey temp.
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'OfficeStaging' {
|
||||||
|
Clear-SystemCleanupOfficeStaging $context (Get-SystemCleanupOfficeStagingRoots $allProfiles) $tempCutoff
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'UserTemp' {
|
||||||
|
$acadRunning = Test-SystemCleanupAppRunning @('acad')
|
||||||
|
foreach ($profile in $profiles) {
|
||||||
|
$root = Join-Path $profile 'AppData\Local\Temp'
|
||||||
|
Clear-SystemCleanupTree $context 'UserTemp' $root $tempCutoff -Exclude $tempExclusions -Recurse
|
||||||
|
if (-not $acadRunning) { Clear-SystemCleanupTree $context 'UserTemp' $root $tempCutoff -Include @('*.ac$') -Recurse }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'ServiceTemp' {
|
||||||
|
foreach ($profile in $serviceProfiles) {
|
||||||
|
Clear-SystemCleanupTree $context 'ServiceTemp' (Join-Path $profile 'AppData\Local\Temp') $tempCutoff -Exclude $tempExclusions -Recurse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'ActiveCBSLog' {
|
||||||
|
$cbs = Join-Path $env:SystemRoot 'Logs\CBS'
|
||||||
|
$archives = @(Get-SystemCleanupFiles $cbs | Where-Object { $_.Name -like 'CbsPersist_*.log' -or $_.Name -like 'CbsPersist_*.cab' })
|
||||||
|
$total = ($archives | Measure-Object Length -Sum).Sum
|
||||||
|
# Do not stop Windows servicing to reclaim a log. Remove only when already idle.
|
||||||
|
if ($total -ge 200MB -and (Get-Service -Name TrustedInstaller -ErrorAction Stop).Status -eq 'Stopped') {
|
||||||
|
Clear-SystemCleanupTree $context 'ActiveCBSLog' $cbs $diagnosticCutoff -Include @('CBS.log')
|
||||||
|
} else {
|
||||||
|
$context.Stats.ActiveCBSLog.Notes = 'Retained: servicing active or CBS archives below 200 MiB.'
|
||||||
|
Write-SystemCleanupMessage 'Active CBS.log retained: servicing is active or archives total less than 200 MiB.' -Detail:$Options.ReportOnly
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'CBSArchives' {
|
||||||
|
Clear-SystemCleanupTree $context 'CBSArchives' (Join-Path $env:SystemRoot 'Logs\CBS') $diagnosticCutoff -Include @('CbsPersist_*.log', 'CbsPersist_*.cab')
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'CrashDumps' {
|
||||||
|
Clear-SystemCleanupTree $context 'CrashDumps' $env:SystemRoot $diagnosticCutoff -Include @('MEMORY.DMP')
|
||||||
|
foreach ($relative in @('Minidump', 'LiveKernelReports', 'Temp')) {
|
||||||
|
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $env:SystemRoot $relative) $diagnosticCutoff -Include @('*.dmp') -Recurse
|
||||||
|
}
|
||||||
|
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $env:ProgramData 'Genetec\Dumps') $diagnosticCutoff -Recurse
|
||||||
|
foreach ($profile in $allProfiles) {
|
||||||
|
foreach ($relative in @('AppData\Local\CrashDumps', 'AppData\Local\Temp')) {
|
||||||
|
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $profile $relative) $diagnosticCutoff -Include @('*.dmp') -Recurse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'WERArchives' {
|
||||||
|
Clear-SystemCleanupTree $context 'WERArchives' (Join-Path $env:ProgramData 'Microsoft\Windows\WER\ReportArchive') $diagnosticCutoff -Recurse
|
||||||
|
foreach ($profile in $allProfiles) {
|
||||||
|
Clear-SystemCleanupTree $context 'WERArchives' (Join-Path $profile 'AppData\Local\Microsoft\Windows\WER\ReportArchive') $diagnosticCutoff -Recurse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'AutodeskInstallers' {
|
||||||
|
if (Test-SystemCleanupAppRunning @('setup', 'msiexec', 'AdskInstall', 'AdODIS')) { Set-SystemCleanupSkipped $context 'AutodeskInstallers' 'An installer is running; extracted Autodesk payloads retained.'; return }
|
||||||
|
foreach ($dir in @(Get-SystemCleanupChildren (Join-Path $env:SystemDrive 'Autodesk') | Where-Object { $_.PSIsContainer -and $_.Name -ne 'WI' })) {
|
||||||
|
Remove-SystemCleanupBundle $context 'AutodeskInstallers' $dir.FullName $tempCutoff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'RecycleBin' {
|
||||||
|
Clear-SystemCleanupRecycleBin $context (Join-Path $env:SystemDrive '$Recycle.Bin') $backupCutoff
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'DownloadedExecutables' {
|
||||||
|
foreach ($profile in $profiles) { Clear-SystemCleanupTree $context 'DownloadedExecutables' (Join-Path $profile 'Downloads') $backupCutoff -Include @('*.exe') }
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'DuplicateDownloads' {
|
||||||
|
foreach ($profile in $profiles) { Remove-SystemCleanupDuplicates $context (Join-Path $profile 'Downloads') $backupCutoff }
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'OutlookBackups' {
|
||||||
|
if (Test-SystemCleanupAppRunning @('OUTLOOK')) { Set-SystemCleanupSkipped $context 'OutlookBackups' 'Outlook is running; backups retained.'; return }
|
||||||
|
foreach ($profile in $profiles) { Clear-SystemCleanupTree $context 'OutlookBackups' (Join-Path $profile 'AppData\Local\Microsoft\Outlook') $backupCutoff -Include @('*.bak') }
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'ITunesBackups' {
|
||||||
|
if (Test-SystemCleanupAppRunning @('iTunes', 'AppleDevices')) { Set-SystemCleanupSkipped $context 'ITunesBackups' 'An Apple device application is running; backups retained.'; return }
|
||||||
|
foreach ($profile in $profiles) {
|
||||||
|
foreach ($relative in @('AppData\Roaming\Apple Computer\MobileSync\Backup', 'Apple\MobileSync\Backup')) {
|
||||||
|
foreach ($dir in @(Get-SystemCleanupChildren (Join-Path $profile $relative) | Where-Object PSIsContainer)) {
|
||||||
|
Remove-SystemCleanupBundle $context 'ITunesBackups' $dir.FullName $backupCutoff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'AppleDownloads' {
|
||||||
|
if (Test-SystemCleanupAppRunning @('iTunes', 'AppleDevices')) { Set-SystemCleanupSkipped $context 'AppleDownloads' 'An Apple device application is running; downloads retained.'; return }
|
||||||
|
foreach ($profile in $profiles) {
|
||||||
|
foreach ($device in @('iPhone', 'iPad', 'iPod')) {
|
||||||
|
Clear-SystemCleanupTree $context 'AppleDownloads' (Join-Path $profile "AppData\Roaming\Apple Computer\iTunes\$device Software Updates") $tempCutoff -Include @('*.ipsw')
|
||||||
|
}
|
||||||
|
Clear-SystemCleanupTree $context 'AppleDownloads' (Join-Path $profile 'Music\iTunes\iTunes Media\Mobile Applications') $tempCutoff -Include @('*.ipa')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'BrowserCache' {
|
||||||
|
foreach ($browser in @(@{Name='chrome'; Root='Google\Chrome\User Data'}, @{Name='msedge'; Root='Microsoft\Edge\User Data'})) {
|
||||||
|
if (Test-SystemCleanupAppRunning @($browser.Name)) {
|
||||||
|
$context.Stats.BrowserCache.Status = 'Partial'
|
||||||
|
$context.Stats.BrowserCache.EstimateStatus = 'Incomplete'
|
||||||
|
$context.Stats.BrowserCache.Notes += "$($browser.Name) is running; its cache was not assessed. "
|
||||||
|
Write-SystemCleanupMessage "$($browser.Name) is running; its caches retained." -Detail:$Options.ReportOnly
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
foreach ($profile in $profiles) {
|
||||||
|
foreach ($browserProfile in @(Get-SystemCleanupChildren (Join-Path $profile ('AppData\Local\' + $browser.Root)) | Where-Object { $_.PSIsContainer -and ($_.Name -eq 'Default' -or $_.Name -match '^Profile \d+$') })) {
|
||||||
|
foreach ($cache in @('Cache', 'Code Cache', 'GPUCache')) {
|
||||||
|
Clear-SystemCleanupTree $context 'BrowserCache' (Join-Path $browserProfile.FullName $cache) $tempCutoff -Recurse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'RevitJournals' {
|
||||||
|
if (Test-SystemCleanupAppRunning @('Revit')) { Set-SystemCleanupSkipped $context 'RevitJournals' 'Revit is running; journals retained.'; return }
|
||||||
|
foreach ($profile in $profiles) {
|
||||||
|
foreach ($version in @(Get-SystemCleanupChildren (Join-Path $profile 'AppData\Local\Autodesk\Revit') | Where-Object { $_.PSIsContainer -and $_.Name -like 'Autodesk Revit *' })) {
|
||||||
|
Clear-SystemCleanupTree $context 'RevitJournals' (Join-Path $version.FullName 'Journals') $diagnosticCutoff -Include @('journal*.txt')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'DisableHibernation' {
|
||||||
|
if (Test-Path -LiteralPath (Join-Path $env:SystemDrive 'hiberfil.sys')) { Invoke-SystemCleanupProcess $context 'powercfg.exe' '/hibernate off' }
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'CompactSearch' { Invoke-SystemCleanupSearchCompaction $context }
|
||||||
|
Invoke-SystemCleanupCategory $context 'ShadowCopies' { Invoke-SystemCleanupShadows $context }
|
||||||
|
Invoke-SystemCleanupCategory $context 'DeliveryOptimization' {
|
||||||
|
if (-not (Get-Command Delete-DeliveryOptimizationCache -ErrorAction SilentlyContinue)) {
|
||||||
|
if ($Options.ReportOnly) { Set-SystemCleanupSkipped $context 'DeliveryOptimization' 'Delivery Optimization cmdlet is not installed.' -Status 'Unavailable'; return }
|
||||||
|
throw 'Delivery Optimization cmdlet is not installed.'
|
||||||
|
}
|
||||||
|
Write-SystemCleanupMessage 'Delivery Optimization: unpinned cache only; size not estimated.' -Detail:$Options.ReportOnly
|
||||||
|
if (-not $Options.ReportOnly) { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop }
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'ComponentStore' {
|
||||||
|
Invoke-SystemCleanupProcess $context 'schtasks.exe' '/Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"'
|
||||||
|
Write-SystemCleanupMessage 'Component cleanup runs asynchronously under Task Scheduler; completion and reclaimed bytes are not measured here.' -Detail:$Options.ReportOnly
|
||||||
|
}
|
||||||
|
Invoke-SystemCleanupCategory $context 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $context }
|
||||||
|
if ($Options.ReportOnly) {
|
||||||
|
$context.Diagnostics = Get-SystemCleanupDiagnostics $context
|
||||||
|
Write-SystemCleanupReport $context
|
||||||
|
}
|
||||||
|
if ($context.Errors) { throw "$($context.Errors) cleanup category/maintenance error(s). Review the category messages above." }
|
||||||
|
return @($context.Stats.Values | Sort-Object @{Expression={ if ($_.Status -eq 'Blocked on server') { 2 } elseif ($_.Enabled) { 0 } else { 1 } }}, Category)
|
||||||
|
} finally {
|
||||||
|
if ($acquired) { $mutex.ReleaseMutex() }
|
||||||
|
$mutex.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Read inherited caller variables before entering the implementation's local scope.
|
||||||
|
# The function returns structured results for programmatic callers/tests. Do not
|
||||||
|
# let PowerShell auto-format a second, much longer report in the RMM output.
|
||||||
|
Invoke-SystemCleanup -Options (Get-SystemCleanupOptions) | Out-Null
|
||||||
@@ -219,6 +219,38 @@ Function ConvertTo-RmmBoolean {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Convert an RMM semicolon-separated text variable into individual strings.
|
||||||
|
Function ConvertTo-RmmList {
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Splits an RMM text value on semicolons and trims each item.
|
||||||
|
.DESCRIPTION
|
||||||
|
Null, blank, and empty items are omitted. Item order, case, duplicates,
|
||||||
|
internal spaces, commas, and backslashes are preserved. Values are not
|
||||||
|
evaluated, expanded, resolved, or checked for existence. Semicolons are
|
||||||
|
always separators; there is no quoting or escaping syntax.
|
||||||
|
Wrap the call in @() to obtain an array for zero, one, or many items.
|
||||||
|
.EXAMPLE
|
||||||
|
$Paths = @(ConvertTo-RmmList -Value 'C:\QB Data; \\server\Archive;')
|
||||||
|
.EXAMPLE
|
||||||
|
$Shares = @(ConvertTo-RmmList -Value $QuickBooksShareNames)
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
[OutputType([string])]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
|
||||||
|
[AllowNull()]
|
||||||
|
[AllowEmptyString()]
|
||||||
|
[string]$Value
|
||||||
|
)
|
||||||
|
process {
|
||||||
|
foreach ($Item in ([string]$Value).Split(';')) {
|
||||||
|
$Item = $Item.Trim()
|
||||||
|
if ($Item.Length -gt 0) { $Item }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# Determines whether a URL is valid
|
# Determines whether a URL is valid
|
||||||
Function IsURLValid {
|
Function IsURLValid {
|
||||||
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL)
|
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL)
|
||||||
@@ -853,6 +885,87 @@ Function Disable-Log {
|
|||||||
Catch { Write-Error $_.Exception.Message }
|
Catch { Write-Error $_.Exception.Message }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Published packages for both Install- and Update-EmberkomCloudBackup.
|
||||||
|
Function Get-EmberkomCloudBackupReleases {
|
||||||
|
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||||
|
$client = New-Object Net.WebClient
|
||||||
|
try {
|
||||||
|
$json = $client.DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/resources/EmberkomCloudBackup.json')
|
||||||
|
} finally { $client.Dispose() }
|
||||||
|
$manifest = $json | ConvertFrom-Json -ErrorAction Stop
|
||||||
|
$releases = @{}
|
||||||
|
foreach ($build in 'Windows','VM') {
|
||||||
|
$release = $manifest.$build
|
||||||
|
$version = $null
|
||||||
|
if ([version]::TryParse($release.Version, [ref]$version) -and $version.Revision -ge 0 -and $release.Url -match '^https://' -and
|
||||||
|
$release.SHA256 -match '^[a-f0-9]{64}$') {
|
||||||
|
$releases[$build] = $release
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $releases
|
||||||
|
}
|
||||||
|
|
||||||
|
Function Get-EmberkomCloudBackupRelease {
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$true)][ValidateSet('Windows','VM')][string]$Build,
|
||||||
|
[hashtable]$Releases = (Get-EmberkomCloudBackupReleases)
|
||||||
|
)
|
||||||
|
if (!$Releases[$Build]) { throw "Incomplete Emberkom Cloud Backup release for $Build." }
|
||||||
|
return $Releases[$Build]
|
||||||
|
}
|
||||||
|
|
||||||
|
Function Save-EmberkomCloudBackupInstaller {
|
||||||
|
param([Parameter(Mandatory=$true)]$Release, [Parameter(Mandatory=$true)][string]$Path)
|
||||||
|
$ProgressPreference = 'SilentlyContinue'
|
||||||
|
$sourceHost = ([uri]$Release.Url).Host
|
||||||
|
$maxAttempts = 2
|
||||||
|
$timeoutSeconds = 240
|
||||||
|
Write-Host "MSP360 $($Release.Version) installer target: $Path (expected SHA-256 $($Release.SHA256))."
|
||||||
|
try {
|
||||||
|
for ($attempt = 1; $attempt -le $maxAttempts; $attempt++) {
|
||||||
|
$elapsed = [Diagnostics.Stopwatch]::StartNew()
|
||||||
|
$utc = [datetime]::UtcNow.ToString('u')
|
||||||
|
Write-Host "$utc $env:COMPUTERNAME - MSP360 installer download from $sourceHost (attempt $attempt of $maxAttempts, request timeout $timeoutSeconds seconds)."
|
||||||
|
try {
|
||||||
|
Invoke-WebRequest -UseBasicParsing -Uri $Release.Url -OutFile $Path -TimeoutSec $timeoutSeconds -ErrorAction Stop
|
||||||
|
break
|
||||||
|
} catch {
|
||||||
|
$failure = $_.Exception
|
||||||
|
while ($failure.InnerException -and $failure -isnot [Net.WebException]) { $failure = $failure.InnerException }
|
||||||
|
$failureHost = $sourceHost
|
||||||
|
if ($failure -is [Net.WebException]) {
|
||||||
|
$reason = [string]$failure.Status
|
||||||
|
$retry = $reason -in @('Timeout','NameResolutionFailure','ProxyNameResolutionFailure','ConnectFailure',
|
||||||
|
'ConnectionClosed','KeepAliveFailure','SendFailure','ReceiveFailure','PipelineFailure')
|
||||||
|
if ($failure.Response -is [Net.HttpWebResponse]) {
|
||||||
|
$status = [int]$failure.Response.StatusCode
|
||||||
|
$failureHost = $failure.Response.ResponseUri.Host
|
||||||
|
$failure.Response.Close()
|
||||||
|
$reason = "HTTP $status"
|
||||||
|
$retry = $status -in @(408,429,500,502,503,504)
|
||||||
|
}
|
||||||
|
} elseif ($failure -is [Net.Sockets.SocketException]) {
|
||||||
|
$reason = [string]$failure.SocketErrorCode
|
||||||
|
$retry = $true
|
||||||
|
} else { throw }
|
||||||
|
$bytes = if (Test-Path -LiteralPath $Path) { (Get-Item -LiteralPath $Path).Length } else { 0 }
|
||||||
|
$detail = "MSP360 download attempt $attempt of $maxAttempts from $failureHost failed ($reason) after $([int]$elapsed.Elapsed.TotalSeconds)s, $bytes bytes saved."
|
||||||
|
if (!$retry -or $attempt -eq $maxAttempts) { throw $detail }
|
||||||
|
Write-Host "$detail Retrying in 3 seconds."
|
||||||
|
if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Force -ErrorAction Stop }
|
||||||
|
Start-Sleep -Seconds 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((Get-FileHash -LiteralPath $Path -Algorithm SHA256 -ErrorAction Stop).Hash -ne $Release.SHA256) {
|
||||||
|
throw 'The installer SHA-256 does not match the published release.'
|
||||||
|
}
|
||||||
|
Write-Host 'MSP360 installer download complete. SHA-256 verified.'
|
||||||
|
} catch {
|
||||||
|
if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Force -ErrorAction Stop }
|
||||||
|
throw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# Function to install the MSP360 Powershell module
|
# Function to install the MSP360 Powershell module
|
||||||
Function Import-MSP360Module {
|
Function Import-MSP360Module {
|
||||||
Try {
|
Try {
|
||||||
|
|||||||
@@ -19,19 +19,23 @@ End-Process -Name 'Teams' -Match -Force
|
|||||||
# URL to the OffscrubC2R.vbs script
|
# URL to the OffscrubC2R.vbs script
|
||||||
$UninstallScriptURL = 'https://github.com/OfficeDev/Office-IT-Pro-Deployment-Scripts/raw/master/Office-ProPlus-Deployment/Deploy-OfficeClickToRun/OffScrubc2r.vbs'
|
$UninstallScriptURL = 'https://github.com/OfficeDev/Office-IT-Pro-Deployment-Scripts/raw/master/Office-ProPlus-Deployment/Deploy-OfficeClickToRun/OffScrubc2r.vbs'
|
||||||
|
|
||||||
# The path to the local script once downloaded
|
# Use an owned, unique file so partial downloads can also be removed in finally.
|
||||||
$UninstallScript = Download-File -URL $UninstallScriptURL
|
$UninstallScript = Join-Path (Get-TempPath) ('OfficeUninstall-' + [guid]::NewGuid().ToString('N') + '.vbs')
|
||||||
|
|
||||||
# Args to pass to the OffscrubC2R.vbs script
|
# Args to pass to the OffscrubC2R.vbs script
|
||||||
$ScriptArgs = "/ALL /QUIET /NOCANCEL"
|
$ScriptArgs = "/ALL /QUIET /NOCANCEL"
|
||||||
|
|
||||||
# Run the script
|
try {
|
||||||
Write-Output "Uninstalling all Click2Run versions of Office"
|
$null = Download-File -URL $UninstallScriptURL -File $UninstallScript
|
||||||
Try { Start-Process "cscript.exe" -ArgumentList "//nologo ""${UninstallScript}"" ${ScriptArgs}" -Wait }
|
Write-Output 'Uninstalling all Click2Run versions of Office'
|
||||||
Catch { Write-Error $_.Exception.Message }
|
Start-Process 'cscript.exe' -ArgumentList "//nologo `"$UninstallScript`" $ScriptArgs" -Wait -WindowStyle Hidden -ErrorAction Stop
|
||||||
|
} catch {
|
||||||
# Delete the downloaded script
|
Write-Error $_.Exception.Message -ErrorAction Continue
|
||||||
If ( Test-Path $UninstallScript ) {
|
throw
|
||||||
Write-Output "Deleting downloaded script: ""${UninstallScript}"""
|
} finally {
|
||||||
Remove-Item -Path $UninstallScript -Force -ErrorAction SilentlyContinue
|
if (Test-Path -LiteralPath $UninstallScript -PathType Leaf) {
|
||||||
|
Write-Output "Deleting downloaded script: $UninstallScript"
|
||||||
|
try { Remove-Item -LiteralPath $UninstallScript -Force -ErrorAction Stop }
|
||||||
|
catch { Write-Error "Could not delete $UninstallScript : $($_.Exception.Message)" -ErrorAction Continue }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#Requires -Version 4.0
|
||||||
|
# Update an existing Emberkom MSP360 Managed Backup agent during an idle RMM window.
|
||||||
|
|
||||||
|
function Get-CloudBackupInstallation {
|
||||||
|
# MSP360's managed-agent registration points to the branded uninstall key.
|
||||||
|
# Open the registry view explicitly so a 32-bit RMM host can see a 64-bit agent.
|
||||||
|
$views = if ([Environment]::Is64BitOperatingSystem) { 'Registry64', 'Registry32' } else { 'Registry32' }
|
||||||
|
foreach ($view in $views) {
|
||||||
|
$registry = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', $view)
|
||||||
|
$marker = $product = $null
|
||||||
|
try {
|
||||||
|
$marker = $registry.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}')
|
||||||
|
if (!$marker) { continue }
|
||||||
|
$product = $registry.OpenSubKey([string]$marker.GetValue('UninstallKey'))
|
||||||
|
if (!$product -or !$product.GetValue('')) { throw 'The MSP360 agent registration has no executable path.' }
|
||||||
|
if ($product.GetValue('Publisher') -ne 'Emberkom') { throw 'The registered backup agent belongs to a different publisher.' }
|
||||||
|
$cli = Join-Path (Split-Path -LiteralPath $product.GetValue('')) 'cbb.exe'
|
||||||
|
return [pscustomobject]@{
|
||||||
|
Cli = $cli
|
||||||
|
Version = [version][Diagnostics.FileVersionInfo]::GetVersionInfo($cli).FileVersion
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if ($product) { $product.Dispose() }
|
||||||
|
if ($marker) { $marker.Dispose() }
|
||||||
|
$registry.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Read-CloudBackupAgent {
|
||||||
|
param($Installation)
|
||||||
|
if (!$Installation) { return }
|
||||||
|
$details = & $Installation.Cli ver
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "MSP360 could not report the installed agent details (exit $LASTEXITCODE)." }
|
||||||
|
$edition = $service = $null
|
||||||
|
foreach ($line in $details) {
|
||||||
|
if ($line -match '^Backup Agent Edition:\s*(.+)$') { $edition = $Matches[1].Trim() }
|
||||||
|
if ($line -match '^Service name:\s*(.+)$') { $service = $Matches[1].Trim() }
|
||||||
|
}
|
||||||
|
if ($edition -in @('VMware','VMEdition','VM','Virtual Machine Edition')) {
|
||||||
|
$build = 'VM'
|
||||||
|
} elseif ($edition -in @('Desktop','DesktopIBB','FileBackup','BareMetal','Server','MsSql','SqlServer',
|
||||||
|
'Exchange','MsExchange','SqlExchange','MsSqlExchange','MsSqlMsExchange','Enterprise','Ultimate')) {
|
||||||
|
$build = 'Windows'
|
||||||
|
} else {
|
||||||
|
throw "Unrecognized MSP360 agent edition '$edition'. Cannot choose a published package."
|
||||||
|
}
|
||||||
|
if (!$service) { throw 'MSP360 did not report its backup service name.' }
|
||||||
|
[pscustomobject]@{
|
||||||
|
Version = $Installation.Version
|
||||||
|
Build = $build
|
||||||
|
Service = $service
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-CloudBackupUpdateWindow {
|
||||||
|
param([string]$Window, [datetime]$Now = (Get-Date))
|
||||||
|
if ([string]::IsNullOrWhiteSpace($Window)) { return $true }
|
||||||
|
if ($Window.Trim() -notmatch '^((?:[01]\d|2[0-3]):[0-5]\d)-((?:[01]\d|2[0-3]):[0-5]\d)$') {
|
||||||
|
throw 'MSP360UpdateWindow must be a local 24-hour interval such as 12:00-13:00.'
|
||||||
|
}
|
||||||
|
$start = [timespan]::ParseExact($Matches[1], 'hh\:mm', $null)
|
||||||
|
$end = [timespan]::ParseExact($Matches[2], 'hh\:mm', $null)
|
||||||
|
if ($start -eq $end) { throw 'MSP360UpdateWindow needs different start and end times.' }
|
||||||
|
$time = $Now.TimeOfDay
|
||||||
|
if ($start -lt $end) { return ($time -ge $start -and $time -lt $end) }
|
||||||
|
return ($time -ge $start -or $time -lt $end)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-CloudBackupPlanRunning {
|
||||||
|
# The agent launches CBBackupPlan.exe for plan execution. This also works on
|
||||||
|
# CLI-password-protected agents, without passing credentials to a child process.
|
||||||
|
return [bool](Get-CimInstance -ClassName Win32_Process -Filter "Name = 'CBBackupPlan.exe'" -Property ProcessId -ErrorAction Stop)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-CloudBackupUpdate {
|
||||||
|
param([string]$Window)
|
||||||
|
if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host "Deferred. Outside the local update window $Window."; return 0 }
|
||||||
|
$installation = Get-CloudBackupInstallation
|
||||||
|
if (!$installation) { Write-Host 'Skipped. MSP360 Managed Backup is not installed.'; return 0 }
|
||||||
|
$releases = Get-EmberkomCloudBackupReleases
|
||||||
|
# If neither package is newer, the daily check can finish without launching cbb.exe.
|
||||||
|
if ($releases.Count -eq 2 -and $installation.Version -ge [version]$releases.Windows.Version -and
|
||||||
|
$installation.Version -ge [version]$releases.VM.Version) {
|
||||||
|
Write-Host "No update needed. Installed $($installation.Version), published Windows $($releases.Windows.Version), VM $($releases.VM.Version)."
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
$agent = Read-CloudBackupAgent $installation
|
||||||
|
$release = Get-EmberkomCloudBackupRelease -Build $agent.Build -Releases $releases
|
||||||
|
$target = [version]$release.Version
|
||||||
|
if ($agent.Version -ge $target) {
|
||||||
|
Write-Host "No update needed. Installed $($agent.Version), published $($agent.Build) build $target."
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker is active.'; return 0 }
|
||||||
|
|
||||||
|
$installer = Join-Path ([IO.Path]::GetTempPath()) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid())
|
||||||
|
try {
|
||||||
|
Write-Host "Downloading the published $($agent.Build) update from $($agent.Version) to $target."
|
||||||
|
Save-EmberkomCloudBackupInstaller -Release $release -Path $installer
|
||||||
|
# A scheduled plan or the agent's own updater could have started during download.
|
||||||
|
$current = Read-CloudBackupAgent (Get-CloudBackupInstallation)
|
||||||
|
if (!$current -or $current.Build -ne $agent.Build) { throw 'The installed agent changed during download.' }
|
||||||
|
if ($current.Version -ge $target) { Write-Host "Already updated to $($current.Version)."; return 0 }
|
||||||
|
if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host 'Deferred. The update window ended during download.'; return 0 }
|
||||||
|
if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker started during download.'; return 0 }
|
||||||
|
$setup = Start-Process -FilePath $installer -ArgumentList '/S' -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
|
||||||
|
if ($setup.ExitCode -eq 3010) { Write-Host 'MSP360 setup requires a restart to finish. Run the check again after restart.'; return 3010 }
|
||||||
|
if ($setup.ExitCode -ne 0) { throw "MSP360 setup returned exit code $($setup.ExitCode)." }
|
||||||
|
$updated = Read-CloudBackupAgent (Get-CloudBackupInstallation)
|
||||||
|
if (!$updated -or $updated.Build -ne $agent.Build -or $updated.Version -lt $target) {
|
||||||
|
throw "Setup exited successfully but the installed $($agent.Build) agent could not be verified at $target or newer."
|
||||||
|
}
|
||||||
|
$service = Get-Service -Name $updated.Service -ErrorAction Stop
|
||||||
|
$service.WaitForStatus('Running', [timespan]::FromSeconds(60))
|
||||||
|
Write-Host "Updated MSP360 $($updated.Build) from $($agent.Version) to $($updated.Version). $($updated.Service) is running."
|
||||||
|
return 0
|
||||||
|
} finally {
|
||||||
|
if (Test-Path -LiteralPath $installer) { Remove-Item -LiteralPath $installer -Force -ErrorAction Stop }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$updateLock = New-Object -TypeName System.Threading.Mutex -ArgumentList $false,'Global\EmberkomCloudBackupUpdate'
|
||||||
|
$ownsLock = $false
|
||||||
|
try {
|
||||||
|
try { $ownsLock = $updateLock.WaitOne(0) }
|
||||||
|
catch [Threading.AbandonedMutexException] { $ownsLock = $true }
|
||||||
|
if (!$ownsLock) { Write-Host 'Deferred. Another Emberkom Cloud Backup update check is running.'; exit 0 }
|
||||||
|
$windowInput = Get-Variable -Name MSP360UpdateWindow -ErrorAction SilentlyContinue
|
||||||
|
exit (Invoke-CloudBackupUpdate -Window ([string]$windowInput.Value))
|
||||||
|
} catch {
|
||||||
|
Microsoft.PowerShell.Utility\Write-Error "Emberkom Cloud Backup update failed. $($_.Exception.Message)" -ErrorAction Continue
|
||||||
|
exit 1
|
||||||
|
} finally {
|
||||||
|
if ($ownsLock) { $updateLock.ReleaseMutex() }
|
||||||
|
$updateLock.Dispose()
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Updating Emberkom Cloud Backup between plans
|
||||||
|
|
||||||
|
Publish the repository changes to the live `master` branch, then upload [the RMM caller](../rmm/Update-EmberkomCloudBackup.ps1) to Syncro. The caller and updater require Windows PowerShell 4.0 or later. Replace any previously uploaded caller that still declares 5.1. PowerShell checks that declaration before the caller can fetch the live scripts. Run it as SYSTEM on endpoints with Emberkom Cloud Backup. Schedule it in a gap long enough for the download, installation, and backup service restart. Include restore plans and consistency checks when choosing that gap.
|
||||||
|
|
||||||
|
For endpoints that might receive a delayed RMM job, configure the optional **string** variable `MSP360UpdateWindow`. For example, `12:00-13:00` admits installation starts from noon until just before 1 p.m. in the endpoint's local time. Overnight windows such as `23:30-00:30` also work. With an omitted or blank value, Syncro controls the timing. Allow enough time after the last permitted start for setup to finish.
|
||||||
|
|
||||||
|
On each daily run, the updater reads the installed executable's file version and fetches the small release file once. If the installed version is at least as new as both published builds, it immediately reports **No update needed** and returns success (exit code 0). If either build might be newer, it asks the agent for its edition and compares the matching build.
|
||||||
|
|
||||||
|
Only a newer matching build triggers a plan check and installer download. Immediately before launching setup, the updater checks again for MSP360's `CBBackupPlan.exe` worker. A busy endpoint defers to the next scheduled run. A plan can still start after the final check, so keep the RMM slot clear of scheduled plans. [MSP360 plan worker documentation](https://help.mspbackups.com/troubleshooting)
|
||||||
|
|
||||||
|
The installer download uses a 240-second request timeout and retries once after a timeout or transient network failure. Syncro reports the endpoint name, UTC start time, source hostname, temporary installer path and expected SHA-256. For a failed network attempt, it also reports the reason, elapsed time and bytes saved. An endpoint security provider can use these details to look for a matching event. If both attempts time out, check outbound HTTPS from the endpoint under SYSTEM to the console download host and the redirected storage host. The Windows 8.7.1.177 link redirects from `console.msp360.com` to `s3.us-east-1.amazonaws.com`.
|
||||||
|
|
||||||
|
**Syncro output and exit codes**
|
||||||
|
|
||||||
|
| Code | Meaning |
|
||||||
|
| --- | --- |
|
||||||
|
| 0 | Update verified, version already current or newer, agent absent, or run deferred. The output gives the outcome. |
|
||||||
|
| 1 | Update failed. The output identifies the failed check or installer exit code. |
|
||||||
|
| 3010 | Setup requested a restart. Recheck after the endpoint restarts. |
|
||||||
|
|
||||||
|
MSP360 also checks for updates at the start of plans when its console policy allows it. To make Syncro the sole update path on selected computers, use **Downloads → Options → Exclude from auto-update** in MSP360 after the RMM job is in service. Review the scope because this console setting also covers the MSP360 RMM Agent. [MSP360 agent update policy](https://help.mspbackups.com/downloads/agent-update)
|
||||||
|
|
||||||
|
## Publishing a build
|
||||||
|
|
||||||
|
Both the existing installer and the updater read [the shared release file](../resources/EmberkomCloudBackup.json). When approving a new public build, update its four-part version, console download URL, and SHA-256 in the corresponding `Windows` or `VM` entry. Take the version from the published build and compute the hash from that exact installer using `Get-FileHash -Algorithm SHA256`. Publish the three values together. The generated setup executables can have empty Windows file-version fields.
|
||||||
@@ -6,7 +6,7 @@ The selection identifies the client's purchased subscription; it does not discov
|
|||||||
|
|
||||||
## Publish and configure
|
## Publish and configure
|
||||||
|
|
||||||
1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v4`, which handles per-user Teams add-ins advertised in HKLM and protects reinstalled apps from deferred cleanup. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself.
|
1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v5`, which runs from memory and uses ProgramData only for synchronization state. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself.
|
||||||
2. Paste/upload **rmm/Install-MicrosoftOffice365.ps1** as the Syncro **Windows PowerShell 5.1** script. Select **Run As: System** and set the execution limit to **120 minutes (2 hours)**. PowerShell 7 is not required or launched. Allow enough disk space for both the download and installation. A clean deployment downloads several GB per endpoint and requires internet access throughout companion app installation. Syncro's limit covers the entire run, including downloads, cleanup, and installation.
|
2. Paste/upload **rmm/Install-MicrosoftOffice365.ps1** as the Syncro **Windows PowerShell 5.1** script. Select **Run As: System** and set the execution limit to **120 minutes (2 hours)**. PowerShell 7 is not required or launched. Allow enough disk space for both the download and installation. A clean deployment downloads several GB per endpoint and requires internet access throughout companion app installation. Syncro's limit covers the entire run, including downloads, cleanup, and installation.
|
||||||
3. Use **Add Script Variable**, type **Dropdown**, then **Edit Dropdown Values** for each variable below. Enter names without `$`. Syncro stores dropdown definitions separately; uploading a `.ps1` does not create them. See [Syncro's script editor documentation](https://docs.syncrosecure.com/scripting-apis/manage-scripts).
|
3. Use **Add Script Variable**, type **Dropdown**, then **Edit Dropdown Values** for each variable below. Enter names without `$`. Syncro stores dropdown definitions separately; uploading a `.ps1` does not create them. See [Syncro's script editor documentation](https://docs.syncrosecure.com/scripting-apis/manage-scripts).
|
||||||
4. First run with `ValidateBeforeChanges=true` and review the result. To deploy, rerun with `false` during the maintenance window. Pilot on a disposable VM with representative Office, user profiles, and companion apps. Then run against the intended endpoint or asset selection. Group endpoints by subscription and architecture so each run's selections apply correctly.
|
4. First run with `ValidateBeforeChanges=true` and review the result. To deploy, rerun with `false` during the maintenance window. Pilot on a disposable VM with representative Office, user profiles, and companion apps. Then run against the intended endpoint or asset selection. Group endpoints by subscription and architecture so each run's selections apply correctly.
|
||||||
@@ -23,7 +23,7 @@ The selection identifies the client's purchased subscription; it does not discov
|
|||||||
|
|
||||||
All variables configured in Syncro must have a nonempty value. Set the dropdown defaults above in Syncro; the shim reads the injected strings without assigning over them. `Select a subscription` is a nonempty placeholder that the main script rejects before deployment.
|
All variables configured in Syncro must have a nonempty value. Set the dropdown defaults above in Syncro; the shim reads the injected strings without assigning over them. `Select a subscription` is a nonempty placeholder that the main script rejects before deployment.
|
||||||
|
|
||||||
`ValidateBeforeChanges` uses the existing `ConvertTo-RmmBoolean` helper from `Tools.ps1`. Missing, null, or blank input defaults to `true`; invalid text fails. The workload requires a parsed Boolean, preventing an omitted or unparsed value from enabling changes. `false` still performs prerequisite and download validation before cleanup. It does not skip those checks.
|
`ValidateBeforeChanges` uses the existing `ConvertTo-RmmBoolean` helper from `Tools.ps1`. Missing, null, or blank input defaults to `true`; invalid text fails. The workload requires a parsed Boolean, preventing an omitted or unparsed value from enabling changes. `false` still verifies prerequisites and fresh downloads before removing installed apps.
|
||||||
|
|
||||||
Syncro supplies `COMPANY` automatically with the endpoint's company name in this environment. Preserve that existing mapping; no company dropdown is needed. The shim passes it through to the main script, which includes `<AppSettings><Setup Name="Company" Value="..." /></AppSettings>` in the ODT configuration, retaining the original installer's company setting. Outside Syncro, a missing value (or `None`) omits this setting. No product key, password, or tenant credentials are needed in Syncro.
|
Syncro supplies `COMPANY` automatically with the endpoint's company name in this environment. Preserve that existing mapping; no company dropdown is needed. The shim passes it through to the main script, which includes `<AppSettings><Setup Name="Company" Value="..." /></AppSettings>` in the ODT configuration, retaining the original installer's company setting. Outside Syncro, a missing value (or `None`) omits this setting. No product key, password, or tenant credentials are needed in Syncro.
|
||||||
|
|
||||||
@@ -60,15 +60,23 @@ Business Basic, E1, frontline/web-only plans, education/government variants, con
|
|||||||
|
|
||||||
## Download, removal, and installation
|
## Download, removal, and installation
|
||||||
|
|
||||||
With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, and availability of registered user profiles. It downloads and verifies ODT, the user cleanup helper, the full Office payload, and the selected companion bootstrappers. It writes the installation/removal XML and options, and returns `ValidationPassed` with `OfficeRemovalMethod=SilentODT`, the selected product, version, company, Teams choice, existing Office inventory, and running apps. It does **not** close apps, uninstall, clear identity/credentials, load user hives, register cleanup tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps in this mode; `Abort` fails validation if any are running.
|
With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, registered profile availability, free space, writable paths, and HTTP availability. It returns `ValidationPassed` with the deployment plan, existing Office inventory, Click-to-Run state, running apps, `WritablePaths` and `DownloadChecks`. It creates no deployment directory and downloads no response bodies, release metadata or installation files. It does not clean old artifacts, close apps, uninstall, clear credentials, register tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps; `Abort` fails if any are running.
|
||||||
|
|
||||||
Validation writes logs and staging files, secures its workspace, and runs ODT extraction and `/download`; it is not a zero-write inventory scan. Allow several GB and the same download time as deployment. A later `false` run downloads fresh media and repeats the checks. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time.
|
Assessment sends HTTP HEAD requests, follows redirects, and requires status 200 for the ODT discovery page, helper, conditional Get Help recovery download, selected channel's Office CDN manifest, selected companion installer links, and Windows 10 release-history page when applicable. A refused HEAD request fails assessment; there is no GET fallback. The current versioned ODT executable URL and exact Windows 10 build require reading metadata, so those are resolved only in deployment mode. `OfficeVersion` is empty, `MetadataResolved=false`, `Workspace` is null and `MediaDownloaded=false`. HEAD success does not prove payload integrity, future installation or activation. The normal Tools/core bootstrap still loads live, and the normal Tools log is written. Writable-path checks create a zero-byte delete-on-close probe in the nearest existing parent of staging, ProgramData state, and Program Files paths; they leave no probe or deployment folder behind.
|
||||||
|
|
||||||
|
With `ValidateBeforeChanges=false`, the script checks prerequisites, retires previous idle user cleanup tasks, removes previous deployment artifacts while preserving logs, checks available space, and creates a fresh protected workspace. It downloads and verifies the full Office payload and selected bootstrappers, rechecks free space and running apps, performs removal/installation, verifies results, and removes all non-log staging files in `finally`. Download failures occur before installed apps are removed. An active prior installer/task or unsafe/locked artifact stops preparation; cached content is never a fallback.
|
||||||
|
|
||||||
|
Disk-space checks reserve **10 GB for installation and companion apps**, plus **6 GB for a fresh media download** on the staging drive. When staging, Windows, and Program Files share C:, validation and initial deployment checks require 16 GB free; installation also requires 10 GB remaining after staging. Separate installation volumes are checked independently. These are adjustable headroom values in `Get-OfficeDeploymentDefinitions`, not Microsoft's minimum requirements or a guarantee against concurrent disk use. Low space fails before app removal. Deployment clears prior staging before this check; assessment never performs housekeeping.
|
||||||
|
|
||||||
The script resolves the current versioned ODT download from the [Microsoft Download Center](https://www.microsoft.com/en-us/download/details.aspx?id=49117). It does not depend on the Emberkom-hosted setup.exe or a frozen Microsoft binary URL. If the page format changes, it stops before removal. The downloaded ODT package and extracted setup.exe must have valid Microsoft signatures.
|
The script resolves the current versioned ODT download from the [Microsoft Download Center](https://www.microsoft.com/en-us/download/details.aspx?id=49117). It does not depend on the Emberkom-hosted setup.exe or a frozen Microsoft binary URL. If the page format changes, it stops before removal. The downloaded ODT package and extracted setup.exe must have valid Microsoft signatures.
|
||||||
|
|
||||||
**Unattended deployment does not download or launch Get Help.** The Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even when its parent ran hidden under SYSTEM. Hiding the parent did not hide that child, and Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). The script uses ODT's supported silent removal instead; an interactive scrub is an attended troubleshooting step only.
|
**ODT remains the normal removal path. Get Help is downloaded and run only for conditional recovery.** The command-line scrub is noninteractive, but it is not guaranteed to be invisible: the Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even with a hidden SYSTEM parent. Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal, so the script does not add it. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). Normal successful deployments and assessment runs do not download the scrubber.
|
||||||
|
|
||||||
ODT downloads the current build in the selected channel first. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel.
|
On Windows 11, the download and installation XML omit `Version`, letting ODT select the latest available build in the selected channel. ODT may fetch newer files at installation time if the channel advances during the run. Verification accepts the staged build or a newer build and reports the actual installed version. There is no fixed build number to maintain.
|
||||||
|
|
||||||
|
Windows 10 is the exception: Microsoft limits it to [Office feature release 2608 with subsequent security updates](https://learn.microsoft.com/en-us/microsoft-365-apps/end-of-support/windows-10-support). In deployment mode, before downloading installers or removing apps, the script resolves the highest published 2608 build for the selected channel from [Microsoft's release history](https://learn.microsoft.com/en-us/officeupdates/update-history-microsoft365-apps-by-date). Only Windows 10 specifies that build in the download/install XML. Missing release data or a mismatched download stops before removal. The feature release and history/channel definitions are centralized at the top of the script; patch build numbers are not hardcoded. Server editions are not classified as Windows 10 by their build number.
|
||||||
|
|
||||||
|
Installation uses English (`en-us`), enables updates, and uses `Display Level="None"`. No `Updates TargetVersion` is set, so installation selection does not freeze future updates. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel.
|
||||||
|
|
||||||
The companion apps remain excluded from ODT because the main script installs the selected companions explicitly for all users after Office. Their installers are downloaded from Microsoft's evergreen links and their Microsoft Authenticode signatures checked before any removal; Teams is staged only when the subscription includes it. Teams, new Outlook, and WebView2 use online bootstrappers: only their installer executables are staged, and their payload downloads can still fail later. The complete Office suite payload is staged before removal.
|
The companion apps remain excluded from ODT because the main script installs the selected companions explicitly for all users after Office. Their installers are downloaded from Microsoft's evergreen links and their Microsoft Authenticode signatures checked before any removal; Teams is staged only when the subscription includes it. Teams, new Outlook, and WebView2 use online bootstrappers: only their installer executables are staged, and their payload downloads can still fail later. The complete Office suite payload is staged before removal.
|
||||||
|
|
||||||
@@ -83,24 +91,60 @@ 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.
|
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.
|
||||||
|
|
||||||
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).
|
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. For registered Click-to-Run products, ODT then runs `setup.exe /configure remove.xml` with `<Remove All="TRUE" />` and `<Display Level="None" AcceptEULA="TRUE" />` to remove Office, Visio, and Project. 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. When no Click-to-Run product is registered, it skips this removal pass and the scrub fallback. A surviving ClickToRunSvc or servicing registry key does not establish an installed product. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options).
|
||||||
|
|
||||||
|
Before replacement, `Assert-OfficeRemovalComplete` requires no active installer/removal workers and no registered Click-to-Run products. It logs remaining source references and working-configuration markers as diagnostics. It no longer requires Microsoft's internal registry metadata to disappear: successful local-media installations can retain source paths, and metadata alone does not prove an operation is active. Unreadable process/product/registry state still stops deployment. Fresh media is enforced by clearing prior run downloads, creating a unique workspace, and generating this run's SourcePath; the script never deletes Microsoft's internal servicing registry/cache to force a check to pass.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
This is a supported uninstall and reinstall with our targeted Office identity cleanup, rather than a deep scrub of every Office artifact. A failed ODT removal or remaining non-MSI Office stops before replacement installation; remaining MSI Office after `RemoveMSI` fails the deployment even if the new suite has already installed. The error reports the remaining products and links to [Microsoft's attended scrub guidance](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall). Get Help is never an automatic fallback. Corrupt, unsupported, orphaned, or unusually packaged installations may require that repair. A removal restart result follows `DeferReboot` as described above; no automatic reboot or resume task is created. A deployment already running an older script continues using that downloaded code: let it finish before starting a new deployment.
|
Automatic recovery is limited to **one Get Help Office scrub per deployment**, before replacement installation begins. It is selected only for these conditions:
|
||||||
|
|
||||||
The former Get Help 30-minute background-wait cutoff has been removed with the scrubber. Native installer processes, including ODT download/removal/installation, are awaited until they exit; there is no separate 30-minute installer cutoff. Syncro's two-hour limit remains the overall limit and is not reset between phases. Main-script registration checks now allow five minutes instead of one. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes instead of five; the per-user scheduled task limit is 30 minutes instead of 15. Those tasks may also run later for absent users. These allowances improve tolerance for slow operations but do not guarantee every endpoint finishes within two hours. If the RMM terminates a run, check for surviving installer processes before rerunning; the script does not kill an active installer to meet a time budget.
|
- ODT removal exits `17002` or `17004`, a current native log entry identifies `InvalidDirectory` in `REMOVEINSTALLATION`, and Click-to-Run products remain registered. If products are gone and workers have finished, skip the scrub and report `3010`; `DeferReboot` controls whether installation continues. Historical entries, generic exit-code wrappers and download failures do not qualify.
|
||||||
|
- ODT exits zero, but non-MSI Office registrations remain after the bounded verification wait.
|
||||||
|
|
||||||
|
Service presence, working markers, and deployment source references alone never select removal or scrub recovery.
|
||||||
|
|
||||||
|
Recovery downloads a fresh package from Microsoft's evergreen Get Help link into this run's workspace and validates ZIP paths and the executable's Microsoft signature. Only after recovery is selected, it runs `GetHelpCmd.exe -?` and validates the downloaded tool's own usage. It invokes `-S OfficeScrubScenario -AcceptEula`, adding `-OfficeVersion All` only when that switch is advertised. This restores the earlier scrubber's runtime argument detection; observed builds reject the documented optional switch while returning zero. Usage and removal output are logged separately. The scenario must remove all detected Office registrations, including MSI Office, Visio and Project. It does not retry the scrub.
|
||||||
|
|
||||||
|
Logs include the trigger, native evidence where available, process result, and scenario result. The management log records stdout/stderr byte counts and bounded beginning/end excerpts; original stream logs retain full output. Get Help must return `0` or `3010` with numbered result `00` or `Scenario completed successfully.`; explicit error text, usage errors, contradictory results and `66`/`68` not-found results stop installation. Every accepted response still requires workers to finish, all detected Office registrations to disappear, and no installer/removal workers to remain. Read/verification failures stop deployment. The `gethelp-usage.*.log` and `office-scrub.*.log` files survive cleanup; downloaded non-log files are removed by the same guarded `finally` cleanup as other media.
|
||||||
|
|
||||||
|
When Get Help reports `Uninstall office is running in the background.`, the script now waits instead of failing immediately. It restores the earlier **30-minute background wait** and **60-second quiet interval**. Baseline process identities exclude pre-existing unrelated consoles; newly launched script/installer workers and explicitly identified scrub workers block completion. At least one identified scrub worker must be observed. Worker disappearance alone is insufficient: the script retains process handles to verify identified workers exited with `0` or `3010`, checks all Office registrations, and requires all conditions to stay clear for the quiet interval. Failed/interrupted workers, inaccessible exit status, no observed worker, remaining products or a timeout stop installation. The overall Syncro limit still applies.
|
||||||
|
|
||||||
|
**Visible last-resort window:** Get Help may launch `powershell.exe -File ...\GetHelpElevated\<id>\Run.ps1` outside the deployment workspace and display it in a user's session. Leave it open during cleanup. The observed Microsoft launcher waits for a key in `finally` after either success or failure; dismiss a completed `Press any key to exit` prompt so verification can proceed. The window is not locked against closure. Get Help exposes no documented Office-scrub switch for that, and a handler registered in the RMM parent cannot protect another process; Windows still terminates a console process after a close signal ([console handler behavior](https://learn.microsoft.com/en-us/windows/console/handlerroutine)). The script monitors worker exit codes and endpoint state instead of modifying signed vendor scripts or injecting UI input. A successful process exit alone never proves removal. Get Help's diagnostic reports, when produced, are directly in the worker account's `%LOCALAPPDATA%\DAFs` as `cse.amplify.diagaction.gethelp.officeuninstallalda_<timestamp>.log`. Existing active workers block a new deployment; never reuse their payloads for the next run.
|
||||||
|
|
||||||
|
The wait checks fresh Get Help reports in each identified worker's account (both SYSTEM profile locations when applicable). A complete `GH_OfficeUninstallALDA` report with `ExecutionResult=Failed` stops immediately with its detail and path, even if the worker is still waiting for a key. Old reports, partial JSON, and reports for other scenarios are ignored. A report never authorizes killing the worker or skipping process/product checks. Successful scrub workers may still require the completed keypress prompt to be dismissed; fully unattended fallback is not established for that launcher. A timeout ends the deployment before installation and does not schedule automatic resume.
|
||||||
|
|
||||||
|
A verified scrub reports `3010` because Microsoft recommends a restart to finish cleanup. With `DeferReboot=true`, installation can continue after verification and the final receipt preserves the restart requirement. With `false`, the script returns `RestartRequiredBeforeInstall`. Returned Office-removal/install receipts include `ScrubRecoveryAttempted` and `ScrubRecoveryReason`. No automatic reboot or resume task is created. See [Microsoft's Office scrub guidance](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall).
|
||||||
|
|
||||||
|
Other ODT errors still stop for diagnosis. No automatic scrub is attempted after replacement installation begins, including a failed `RemoveMSI` check that could occur after the new suite is installed. A deployment already running an older script continues using that downloaded code: let it finish before starting another deployment.
|
||||||
|
|
||||||
|
Native installer processes, including ODT and the conditional scrub, are awaited using `Start-Process -Wait`; there is no separate 30-minute installer cutoff. Get Help can detach a worker beyond that wait, as described above. Syncro's two-hour limit remains the overall limit and is not reset between phases. After a terminal scrub result, verification allows five minutes for registration and background-worker state to settle. Surviving Get Help/OffScrub workers, including `GetHelpElevated\...\Run.ps1`, block installation, new deployment downloads, and artifact deletion even outside the current workspace. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes; the per-user scheduled task limit is 30 minutes. Those tasks may also run later for absent users. These allowances do not guarantee every endpoint finishes within two hours. If the RMM terminates a run, check for surviving installer processes before rerunning; the script does not kill an active installer to meet a time budget.
|
||||||
|
|
||||||
Transient failures get bounded recovery before deployment stops:
|
Transient failures get bounded recovery before deployment stops:
|
||||||
|
|
||||||
- HTTP downloads, including the ODT discovery page, get three attempts. ODT `/download` also gets three attempts using the same staging folder, before any app removal. An unrecognized discovery page, invalid signature, or invalid staged payload still fails validation.
|
- HTTP downloads, including the ODT discovery page, get three attempts. Recoverable failures and successful retries are recorded in the Tools diagnostic log with the URL and destination, without emitting errors to Syncro. If all attempts fail, the final error identifies the URL, destination, attempt count, and last failure. ODT `/download` also gets three attempts using the same staging folder, before any app removal. An unrecognized discovery page, invalid signature, or invalid staged payload still fails validation.
|
||||||
- Direct machine and per-user companion MSI removal retry Windows Installer's [busy result, `1618`](https://learn.microsoft.com/en-us/windows/win32/msi/error-codes), up to five attempts with 15 seconds between attempts. Other installer failure codes retain their existing handling. This retry applies to `msiexec.exe`, not ODT's internal `RemoveMSI` operation. The script does not kill an unrelated installer or blindly repeat an Office removal or installation.
|
- Direct machine and per-user companion MSI removal retry Windows Installer's [busy result, `1618`](https://learn.microsoft.com/en-us/windows/win32/msi/error-codes), up to five attempts with 15 seconds between attempts. Other installer failure codes retain their existing handling. This retry applies to `msiexec.exe`, not ODT's internal `RemoveMSI` operation. The script does not kill an unrelated installer or blindly repeat an Office removal or installation.
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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`.
|
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`.
|
||||||
|
|
||||||
|
## Investigating a failed deployment without rerunning it
|
||||||
|
|
||||||
|
`Get-OfficeDeploymentDiagnostics.ps1` collects evidence without importing or executing the installer. Copy this root script to the endpoint and run it in elevated PowerShell, or publish it and use `rmm/Get-OfficeDeploymentDiagnostics.ps1` as SYSTEM. The RMM caller fetches Tools and the core live and needs no inputs. It writes a ZIP under `C:\ProgramData\Emberkom\Logs\OfficeDiagnostics` and prints the full path. No deployment folder, payload download, uninstall, repair, process termination, registry write, or task registration is performed by the collector. The normal RMM Tools bootstrap still initializes its management logs.
|
||||||
|
|
||||||
|
The ZIP includes the last 72 hours of native Office logs from Windows and user temp folders, Office-related management logs, deployment logs/configuration XML, and Get Help DAF reports across all discovered profiles. It includes the GetHelpElevated launcher/support scripts for inspection, even when their package timestamps are older. Current boot time, process owners/sessions, Click-to-Run service state, selected Office registry values from both views, installed Office entries, and Emberkom cleanup tasks are captured separately in `endpoint.json`. It excludes installation executables and media, user documents, and identity/licensing-store exports. Logs can contain user names and paths. `manifest.json` records original paths/timestamps; `collection-issues.json` records access failures and collection limits (64 MB/file, 512 MB total, 2000 files). Live files are copied with shared access and are not an atomic snapshot.
|
||||||
|
|
||||||
|
Compare timestamps inside the native logs for the failed `REMOVEINSTALLATION` and successful installation operations. Running the same staged `setup.exe /configure install.xml` successfully establishes that this media/configuration can install in the later endpoint state and execution context. It does not prove removal completed at the earlier timeout, nor establish behavior under SYSTEM. A reboot after a scrub and a reboot before a deployment that launches another scrub are different sequences. Current registry/service/process state cannot reconstruct the earlier state by itself. Preserve a now-working installation while collecting this evidence; use a disposable VM with a restored baseline for destructive comparisons.
|
||||||
|
|
||||||
## Identity cleanup and absent users
|
## Identity cleanup and absent users
|
||||||
|
|
||||||
The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage.
|
The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage.
|
||||||
@@ -113,7 +157,21 @@ A file lock serializes user uninstallers with the transition to reinstallation.
|
|||||||
|
|
||||||
Windows work/school registration, WAM/AAD BrokerPlugin, generic Windows credentials, and device enrollment are preserved. This intentionally does not remove every Microsoft sign-in token. Microsoft's [activation reset guide](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365-apps/activation/reset-activation-state) distinguishes Office caches from shared WAM and workplace registration state.
|
Windows work/school registration, WAM/AAD BrokerPlugin, generic Windows credentials, and device enrollment are preserved. This intentionally does not remove every Microsoft sign-in token. Microsoft's [activation reset guide](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365-apps/activation/reset-activation-state) distinguishes Office caches from shared WAM and workplace registration state.
|
||||||
|
|
||||||
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 remain registered; an administrator can confirm their marker/task result and unregister those exact tasks afterward. Do not delete their helper while any cleanup is pending.
|
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 remain registered but do no cleanup after success. An administrator can confirm completion and remove those exact tasks and their synchronization folder 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.
|
||||||
|
|
||||||
|
These logon tasks fetch the version-matched user helper live over HTTPS and execute it in memory; sign-in cleanup therefore requires network access to the repository. No helper script or installer is cached for them. Only the empty lock and reinstall-phase marker remain in `%ProgramData%\EmberkomOfficeDeployment\<deployment-id>` while tasks are pending. These are required synchronization state, separate from the logs-only download workspace. The receipt identifies this folder as `UserCleanupWorkspace`. If no tasks remain after a successful deployment, the folder is removed too. A new deployment retires previous idle tasks and clears their state before creating fresh tasks for the currently registered profiles; active tasks block redeployment. If preparation then fails, the retired tasks are not recreated until deployment reaches user cleanup again.
|
||||||
|
|
||||||
|
## Temporary media and cleanup during deployment
|
||||||
|
|
||||||
|
- Each actual installation uses a fresh protected `EmberkomOfficeDeployment\<deployment-id>` directory in the execution account's `[IO.Path]::GetTempPath()`. Under SYSTEM this can be `C:\Windows\SystemTemp`. There is no cross-run reuse of media, manifests, options or XML.
|
||||||
|
- Before creating it, deployment cleans prior GUID workspaces under execution/profile temp, Windows Temp/SystemTemp and legacy ProgramData roots. There is no minimum age. Non-GUID folders outside this managed scope are untouched.
|
||||||
|
- `finally` removes every non-log file from the current download workspace on success, failed download/install, and early restart exits. This includes payloads, bootstrappers, helper scripts, XML, options and locks. `.log` and `.etl` files and their parent directories remain. The selected options are recorded in `deployment-options.log`.
|
||||||
|
- Before deleting artifacts, cleanup rejects reparse points, inventories processes, and probes all candidate files for exclusive access. Active installers or processes referencing the workspace block cleanup. Process-inventory failures also retain the files. A new deployment stops if prior artifacts cannot be cleared safely.
|
||||||
|
- Receipts include `ArtifactCleanupPending=true` when cleanup fails. An otherwise clean install then returns exit `2` and `InstalledWithArtifactCleanupPending`; existing errors, partial-user-cleanup statuses and required-restart results remain intact. The original installation exception is never replaced by a cleanup error.
|
||||||
|
- Pending logon tasks retain only their separate synchronization state, as described above. No downloaded code or media is intentionally retained for them.
|
||||||
|
- Hard RMM termination or power loss can bypass `finally`. The next deployment clears the abandoned artifacts before downloading anything new. No scheduled housekeeping job is created. `Start-SystemCleanup.ps1` retains its separate conservative, age-based cleanup behavior for legacy workspaces; it is not required before redeployment.
|
||||||
|
|
||||||
## Results and troubleshooting
|
## Results and troubleshooting
|
||||||
|
|
||||||
@@ -121,25 +179,33 @@ A deployment is reported as **InstalledWithUserCleanupPending** if any user task
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `0` | `ValidationPassed`: validation only, no deployment performed. `Installed`: Office and companion installations verified; user cleanup completed for the enumerated profiles. |
|
| `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. |
|
| `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. |
|
| `2` | Installation completed with pending work: `InstalledWithUserCleanupPending` lists users needing sign-in; `InstalledWithUserCleanupIncomplete` lists task-registration failures; `InstalledWithArtifactCleanupPending` indicates artifacts could not be removed safely. Inspect the receipt and logs. 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. |
|
| `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.
|
||||||
|
|
||||||
|
ODT's redirected `stdout`/`stderr` files can be empty even when installation fails. Microsoft writes native setup/Click-to-Run logs in the execution account's temp directory and `C:\Windows\Temp`; SYSTEM's temp may be `C:\Windows\SystemTemp`. On an ODT failure, the script searches those folders for recent, nonempty Office/setup or computer-name logs and appends bounded error excerpts and their full paths to the existing Tools diagnostic log. Look for `Native Office log:` and `Native Office detail:`. Collection is read-only, creates no task or additional resident helper, and cannot override the original installer exit code. Excerpts are clues; retain the full native logs when diagnosing a failure.
|
||||||
|
|
||||||
|
Exit `17004` is documented as `ERROR_COMPLETING_SCENARIO_NEED_CLEAN_UP`, with possible reasons including unknown SKUs or unavailable CDN content. It does not establish that an old Office installation needs a scrub. Inspect the native error details before changing removal behavior or repeating a destructive deployment. See [Microsoft's Office CSP error table](https://learn.microsoft.com/en-us/windows/client-management/mdm/office-csp) and [ODT troubleshooting log locations](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/deploy-microsoft-365-apps-local-source).
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
The main script uses the overridden `Write-Output` and `Write-Error` from `Tools.ps1` for actions, retries, failures, and the final receipt, writing to its existing `$Global:LogFile`. Internal action messages suppress the logger's echoed success output to keep function results separate from diagnostics. The mode notice, log location, and final receipt use `Microsoft.PowerShell.Utility\Write-Output` for Syncro. Errors are logged and also printed to Syncro. Native PowerShell relaunch reloads Tools and restores the caller's log path. Run the core through the shim/Tools execution context, not as an independent file without Tools.
|
The main script uses the overridden `Write-Output` and `Write-Error` from `Tools.ps1` for actions, retries, failures, and the final receipt, writing to its existing `$Global:LogFile`. Internal action messages suppress the logger's echoed success output to keep function results separate from diagnostics. The mode notice, log location, and final receipt use `Microsoft.PowerShell.Utility\Write-Output` for Syncro. Errors are logged and also printed to Syncro. Native PowerShell relaunch reloads Tools and restores the caller's log path. Run the core through the shim/Tools execution context, not as an independent file without Tools.
|
||||||
|
|
||||||
Process stdout/stderr logs, options, generated XML, and downloaded media remain in `%ProgramData%\EmberkomOfficeDeployment\<deployment-id>`. ODT removal uses `office-remove.stdout.log` / `.stderr.log` and `remove.xml`; installation uses `office-install.stdout.log` / `.stderr.log` and `install.xml`. The main script records this folder in the Tools log and receipt. The separate limited-user cleanup task does not share the elevated Tools execution context; its transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\<deployment-id>.log` for each user. Retained media can consume several GB per attempt. A validation-only folder can be removed after reviewing its results; for deployment folders, first remove all associated scheduled tasks. ODT may also write diagnostic logs to the executing account's temp directory.
|
Process stdout/stderr logs and `deployment-options.log` remain in the reported `Workspace`. Generated `remove.xml` and `install.xml` are deleted along with downloaded content after each attempt; assessment creates no workspace. ODT removal logs are `office-remove.stdout.log` / `.stderr.log`; installation logs are `office-install.stdout.log` / `.stderr.log`. The main Tools log retains the actions, results, and receipt and is not deleted. The separate limited-user cleanup task writes its transcript in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\<deployment-id>.log`. Do not manually delete `UserCleanupWorkspace` synchronization state while its logon tasks are pending.
|
||||||
|
|
||||||
|
The separate legacy `Uninstall-MicrosoftOffice.ps1` deletes its downloaded VBS in `finally`, including after a failed/partial download or launch error. It is not part of the modern installer workflow. Registry-only Office fixes do not stage installers, and RMM shims execute their downloaded PowerShell source in memory.
|
||||||
|
|
||||||
The installer verifies the selected Office product, bitness, and downloaded version in Click-to-Run registration, plus selected companion deployment as listed above. The final receipt includes `CompanionApps` versions and `TeamsSelected`; when Teams is skipped, it has no installed version in that receipt. Any selected companion installer or verification failure fails the deployment, even if Office installed successfully. It does not claim that the subscription has activated. It does not delete mail profiles, revoke cloud sessions, or roll back a removed Office installation.
|
The installer verifies the selected Office product, bitness, and downloaded version in Click-to-Run registration, plus selected companion deployment as listed above. The final receipt includes `CompanionApps` versions and `TeamsSelected`; when Teams is skipped, it has no installed version in that receipt. Any selected companion installer or verification failure fails the deployment, even if Office installed successfully. It does not claim that the subscription has activated. It does not delete mail profiles, revoke cloud sessions, or roll back a removed Office installation.
|
||||||
|
|
||||||
## Verification
|
## Verification
|
||||||
|
|
||||||
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. ODT removal tests cover silent XML, absent Office, mixed MSI/Click-to-Run installations, leftovers, read errors, MSI verification after installation, restart results, and absence of an interactive fallback. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. Tests use a separate mutex and do not run Microsoft installers or clear actual credentials.
|
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks in Windows PowerShell 5.1. Coverage includes HEAD-only assessment and status failures, temporary write probes, no metadata/staging/housekeeping during assessment, prior-run cleanup with nested-log preservation, active-process/task and locked-file protection, live user-helper execution, orphaned Click-to-Run removal and stale-state rejection. Recovery checks cover the observed InvalidDirectory error, exclusion of stale/unrelated evidence, ZIP containment, signature failures, one-attempt enforcement, ambiguous/failed/not-found scrub results, zero-exit argument/usage errors, bounded stream excerpts without changing parser input, surviving workers, all-product removal verification, log preservation and both restart policies. Existing checks cover strings through the real shim/Tools loader, exit-code propagation, native-host relaunch, deployment order, companion verification, retries and identity cleanup boundaries. Tests mock downloads and disruptive actions; they do not run Microsoft installers, change actual registry state, or clear credentials.
|
||||||
|
|
||||||
`Run-Script` is unchanged. Its existing local execution can read the Syncro variables from the enclosing caller scope. The Office workload validates those values and reports its own result and exit code. The shim only sets TLS, dot-sources `Tools.ps1`, and invokes the workload. Existing `Run-Script` bootstrap failure behavior also remains unchanged.
|
`Run-Script` is unchanged. Its existing local execution can read the Syncro variables from the enclosing caller scope. The Office workload validates those values and reports its own result and exit code. The shim only sets TLS, dot-sources `Tools.ps1`, and invokes the workload. Existing `Run-Script` bootstrap failure behavior also remains unchanged.
|
||||||
|
|
||||||
|
Restored scrub tests cover advertised/unsupported arguments, both result formats, background acknowledgement, delayed inventory, a restarted quiet interval, a worker left at the keypress prompt, closed/failed workers, unknown worker identity, missing observed workers, stale state, and the 30-minute bound. An inert PowerShell child verifies that the retained process handle preserves a nonzero exit code after the child terminates. No actual scrubber is executed by the suite.
|
||||||
|
|
||||||
Endpoint acceptance still requires a VM pilot: existing MSI/C2R/Store Office, machine/per-user Teams and OneDrive, a logged-off profile, standard-user sign-in, wrong-license rejection, download failure, and the restart path. Verify new Outlook and Teams registration at sign-in, OneDrive migration, and that delayed cleanup preserves reinstalled apps. The implementation has not been run destructively against a real endpoint during development.
|
Endpoint acceptance still requires a VM pilot: existing MSI/C2R/Store Office, machine/per-user Teams and OneDrive, a logged-off profile, standard-user sign-in, wrong-license rejection, download failure, and the restart path. Verify new Outlook and Teams registration at sign-in, OneDrive migration, and that delayed cleanup preserves reinstalled apps. The implementation has not been run destructively against a real endpoint during development.
|
||||||
|
|
||||||
## Maintaining deployment definitions
|
## Maintaining deployment definitions
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
# System cleanup
|
||||||
|
|
||||||
|
`Start-SystemCleanup.ps1` combines the operations of `Cleanup-SystemTempFiles.ps1`
|
||||||
|
and `Start-Cleanup.ps1`, with additional cache and diagnostic targets. The old
|
||||||
|
scripts remain unchanged. Upload `rmm/Start-SystemCleanup.ps1` to the RMM and run
|
||||||
|
as SYSTEM under **64-bit Windows PowerShell 5.1**. No reboot is initiated.
|
||||||
|
On 64-bit Windows the core rejects a 32-bit host before changes.
|
||||||
|
|
||||||
|
## First run and configuration
|
||||||
|
|
||||||
|
Define the script variables in Syncro using the names below **without `$`**.
|
||||||
|
Use Dropdown variables with `true` and `false` choices for boolean options, and
|
||||||
|
a single-selection Dropdown for `CleanupDiskCleanupItems` with the five presets
|
||||||
|
below. Select `Standard` for the usual Disk Cleanup behavior. The three day counts
|
||||||
|
can be Runtime variables, requiring a nonempty number each run; omit those variable
|
||||||
|
definitions if you want the core's defaults instead. Syncro supplies all values as
|
||||||
|
strings. Uploading the shim does not create these variable definitions in Syncro.
|
||||||
|
|
||||||
|
Remove the former `CleanupDiskCleanup` variable from Syncro and any manual callers.
|
||||||
|
`CleanupDiskCleanupItems=None` is now the only operator setting to disable native
|
||||||
|
Disk Cleanup. A caller still supplying the removed boolean fails before cleanup,
|
||||||
|
with migration instructions, so an old `false` value cannot be silently ignored.
|
||||||
|
|
||||||
|
Like `rmm/Install-MicrosoftOffice365.ps1`, the shim documents the variables but
|
||||||
|
does not assign them. It loads Tools.ps1 and calls
|
||||||
|
`Run-Script -LivePSScript Start-SystemCleanup`, preserving Syncro's injected
|
||||||
|
variables through the dot-sourced caller scope; do not add `-Arguments`. The core
|
||||||
|
parses these strings and supplies defaults for absent variables, including direct
|
||||||
|
use. The core does not need to download Tools.ps1 itself.
|
||||||
|
|
||||||
|
Run once with `CleanupReportOnly=true`, then set it to `false` to apply. Report
|
||||||
|
mode assesses **all categories regardless of their enablement**, using the current
|
||||||
|
retention settings. It leaves the enablement variables unchanged. The compact
|
||||||
|
report starts with the unique enabled savings and additional disabled savings,
|
||||||
|
followed by a component-store note, then every category once in three sections:
|
||||||
|
|
||||||
|
- **Enabled:** eligible for cleanup on an apply run, subject to the reported conditions.
|
||||||
|
- **Disabled:** potential savings only; these categories will not run during apply
|
||||||
|
unless you enable their corresponding `Cleanup*` variables.
|
||||||
|
- **Blocked on server:** listed for visibility, without scanning or executing their
|
||||||
|
actions. These cannot be enabled on a server.
|
||||||
|
|
||||||
|
For example, `CleanupDownloadedExecutables=false` still reports old downloaded
|
||||||
|
executables in the Disabled section on a client. With `CleanupReportOnly=false`,
|
||||||
|
that category is skipped entirely until explicitly enabled.
|
||||||
|
|
||||||
|
File categories report their independent eligible file counts and logical bytes.
|
||||||
|
These category estimates can overlap (for example, a duplicate downloaded EXE).
|
||||||
|
The enabled total counts each file path once. The disabled total shows additional
|
||||||
|
unique file bytes beyond those already counted in enabled categories. Native
|
||||||
|
operations such as Disk Cleanup, Search compaction, Delivery Optimization,
|
||||||
|
and component cleanup show `-` and **not estimated**, not
|
||||||
|
zero. Disk Cleanup shows its preset (or Custom) and selected handler count.
|
||||||
|
`None` places Disk Cleanup in the Disabled section. Servers always place it in
|
||||||
|
the Blocked section, regardless of the preset.
|
||||||
|
Skipped/unavailable categories say **not assessed**; failed or partially assessed
|
||||||
|
categories are labeled incomplete. In-use application checks remain enforced, so
|
||||||
|
close those applications and rerun to obtain their estimates. Unknown savings are
|
||||||
|
excluded from the totals, and file sizes do not guarantee physical space savings.
|
||||||
|
|
||||||
|
The report-only diagnostics run regardless of the corresponding cleanup flags:
|
||||||
|
|
||||||
|
- **DisableHibernation:** the category's MiB column shows the current system-drive
|
||||||
|
`hiberfil.sys` size, or `0.00` when absent. Its note identifies this as file size.
|
||||||
|
- **ShadowCopies:** the category's MiB column shows used shadow storage for the
|
||||||
|
system volume, or `0.00` when no storage association exists. Its note identifies
|
||||||
|
VSS usage and the drive where the data resides. Storage on another drive is
|
||||||
|
labeled accordingly; it does not represent space occupied on C:. Allocation
|
||||||
|
details remain available in verbose output.
|
||||||
|
- **ComponentStore:** a short note that removing superseded updates may free
|
||||||
|
substantial space, or little/none. The component store is not analyzed, and no
|
||||||
|
Yes/No recommendation or package count is calculated. The note appears even if
|
||||||
|
`CleanupComponentStore=false` or `CleanupDiskCleanupItems=None`.
|
||||||
|
|
||||||
|
There are no separate Hibernation or ShadowStorage diagnostic lines. The two
|
||||||
|
native rows keep `-` in the Files column. Failed/unsupported inspections show `-`
|
||||||
|
for MiB and **unavailable**, never zero. Structured results expose these usage
|
||||||
|
measurements as `UsageBytes`, separately from `CandidateBytes`.
|
||||||
|
|
||||||
|
These are **current usage and potential, not extra reclaimable bytes**;
|
||||||
|
they are excluded from both savings totals. VSS data may be shared between
|
||||||
|
snapshots, and the script retains the newest snapshot. Hibernation/VSS diagnostics
|
||||||
|
remain unassessed on servers under the existing server policy. The component-store
|
||||||
|
note appears on both clients and servers. Diagnostics are skipped in
|
||||||
|
apply mode and require no new Syncro variables.
|
||||||
|
|
||||||
|
Report mode does not launch DISM analysis, avoiding its additional runtime on slow
|
||||||
|
endpoints. Component cleanup removes superseded updates, so potential savings
|
||||||
|
depend on accumulated updates and previous Windows maintenance. A large WinSxS
|
||||||
|
folder alone does not indicate how much is reclaimable. Actual cleanup still uses
|
||||||
|
the existing background task when `CleanupComponentStore=true` in apply mode.
|
||||||
|
|
||||||
|
The default output is designed for Syncro's limited script output: one line per
|
||||||
|
category, including zero results, without a second PowerShell object dump or
|
||||||
|
per-category progress chatter. Column sizes are in MiB; positive sizes below
|
||||||
|
0.01 MiB display as `<0.01`. The group identifies whether a category is enabled;
|
||||||
|
its variable is `Cleanup<Category>`, except Disk Cleanup uses
|
||||||
|
`CleanupDiskCleanupItems`. Skip, failure, and partial-assessment reasons remain
|
||||||
|
visible. Long diagnostic notes are shortened to one line.
|
||||||
|
|
||||||
|
To troubleshoot, set `$VerbosePreference = 'Continue'` in the caller before
|
||||||
|
`Run-Script`. Verbose output includes progress, full diagnostic notes, and the
|
||||||
|
selected/unselected Disk Cleanup handler lists; it can exceed Syncro's output
|
||||||
|
limit, so use a local PowerShell capture when full detail is needed. No additional
|
||||||
|
Syncro variable is required. The `Invoke-SystemCleanup` function still returns
|
||||||
|
structured results for programmatic callers; the script entry suppresses their
|
||||||
|
automatic formatting after printing the human-readable report.
|
||||||
|
|
||||||
|
Report mode performs no cleanup, changes no cleanup registry settings, stops no
|
||||||
|
services, launches no native programs, and requests no scheduled maintenance.
|
||||||
|
Acquiring a named mutex prevents overlapping
|
||||||
|
runs; the RMM bootstrap still downloads Tools/core and may produce its usual logs.
|
||||||
|
Native cleanup savings cannot be estimated from these usage measurements alone.
|
||||||
|
|
||||||
|
Boolean options accept native booleans or true/false, yes/no, 1/0 strings. Blank
|
||||||
|
or unrecognized boolean values fail before cleanup. Retention values must be
|
||||||
|
whole days from 1 through 3650. Unknown Disk Cleanup presets/handler names, blank
|
||||||
|
selections, and mixtures of presets with other values also fail before cleanup.
|
||||||
|
|
||||||
|
| Variable | Default | Purpose |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `CleanupReportOnly` | true | Assess all categories versus apply enabled categories only |
|
||||||
|
| `CleanupTempDays` | 7 | Temp files, installers, abandoned Office staging, browser cache, Apple downloads |
|
||||||
|
| `CleanupDiagnosticDays` | 30 | CBS, WER archives, dumps, Revit journals |
|
||||||
|
| `CleanupBackupDays` | 30 | Downloads, backups, time spent in Recycle Bin |
|
||||||
|
| `CleanupSystemTemp` | true | Windows Temp and SystemTemp, including EVTX, misc logs, AppxErrorReport, Chocolatey; excludes Office staging |
|
||||||
|
| `CleanupOfficeStaging` | true | Recognized abandoned Office deployment media, using CleanupTempDays; preserves diagnostics and deferred-user helpers |
|
||||||
|
| `CleanupUserTemp` | true | Registered user profiles' Local Temp; AutoCAD `.ac$` only with AutoCAD closed |
|
||||||
|
| `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders |
|
||||||
|
| `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` |
|
||||||
|
| `CleanupActiveCBSLog` | false | Old CBS.log, only with TrustedInstaller already stopped and archives >=200 MiB |
|
||||||
|
| `CleanupCrashDumps` | true | MEMORY.DMP, Minidump, LiveKernelReports including PDCRevocation, Genetec Dumps, user/service CrashDumps and temp `.dmp` |
|
||||||
|
| `CleanupWERArchives` | true | System/user/service WER ReportArchive; queues retained |
|
||||||
|
| `CleanupAutodeskInstallers` | false | Old extracted directories under system drive Autodesk, excluding WI |
|
||||||
|
| `CleanupRecycleBin` | false | System-drive recycle items, using deletion date from `$I` metadata |
|
||||||
|
| `CleanupDisableHibernation` | false | `powercfg /hibernate off` |
|
||||||
|
| `CleanupCompactSearch` | false | Compact Windows.edb with esentutl; temporarily stop WSearch |
|
||||||
|
| `CleanupShadowCopies` | false | Delete all but newest system-volume shadow copy |
|
||||||
|
| `CleanupDownloadedExecutables` | false | Old `.exe` files in each profile's Downloads |
|
||||||
|
| `CleanupDuplicateDownloads` | false | Old `name (number).ext` files with a matching original and SHA-256 |
|
||||||
|
| `CleanupOutlookBackups` | false | Old Outlook `.bak` files, with Outlook closed |
|
||||||
|
| `CleanupITunesBackups` | false | Old complete MobileSync backup directories, with Apple apps closed |
|
||||||
|
| `CleanupAppleDownloads` | false | Old IPSW/IPA files from the previously commented-out iTunes block |
|
||||||
|
| `CleanupBrowserCache` | false | Chrome/Edge Cache, Code Cache, GPUCache in Default/Profile N, with that browser closed |
|
||||||
|
| `CleanupRevitJournals` | true | Old journal*.txt only, with Revit closed |
|
||||||
|
| `CleanupDeliveryOptimization` | false | Supported cache cmdlet, retaining pinned content |
|
||||||
|
| `CleanupComponentStore` | false | Request Windows StartComponentCleanup scheduled task; asynchronous |
|
||||||
|
| `CleanupDiskCleanupItems` | Standard | Disk Cleanup preset; None disables it; clients only. Exact handler lists/arrays also accepted |
|
||||||
|
|
||||||
|
## Disk Cleanup presets
|
||||||
|
|
||||||
|
Configure these exact dropdown choices for `CleanupDiskCleanupItems`:
|
||||||
|
|
||||||
|
| Preset | Selected handlers |
|
||||||
|
| --- | --- |
|
||||||
|
| `Standard` (default) | Downloaded Program Files; Internet Cache Files; Thumbnail Cache; Active Setup Temp Folders; Temporary Setup Files; Windows Defender; RetailDemo Offline Content |
|
||||||
|
| `StandardAndUpdates` | All Standard handlers, plus Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
|
||||||
|
| `StandardUpdatesAndDiagnostics` | All StandardAndUpdates handlers, plus Memory Dump Files; Old ChkDsk Files; System error memory dump files; System error minidump files; Setup Log Files; Windows Error Reporting Archive Files; Windows Error Reporting Queue Files; Windows Error Reporting System Archive Files; Windows Error Reporting System Queue Files; Windows Error Reporting Temp Files |
|
||||||
|
| `All` | All 35 supported legacy handlers listed below, including Recycle Bin, user file versions, previous installations, and Windows ESD installation files |
|
||||||
|
| `None` | No handlers; native Disk Cleanup does not run |
|
||||||
|
|
||||||
|
Presets are cumulative and case-insensitive; surrounding whitespace is ignored.
|
||||||
|
`Standard` preserves the previous default selection. `All` selects the explicit
|
||||||
|
supported list, not arbitrary additional handlers installed on an endpoint.
|
||||||
|
No preset changes other `Cleanup*` flags or bypasses the server exclusion.
|
||||||
|
|
||||||
|
Exact comma-separated handler names and arrays remain supported for manual or
|
||||||
|
existing callers, for example `Thumbnail Cache,Internet Cache Files`. They are
|
||||||
|
reported as a custom selection. Use one preset or a list of exact handlers; do
|
||||||
|
not mix them. A supplied blank/null value is invalid; an absent variable defaults
|
||||||
|
to `Standard`. Use the nonempty value `None` to disable native Disk Cleanup.
|
||||||
|
|
||||||
|
## Server policy
|
||||||
|
|
||||||
|
`Win32_OperatingSystem.ProductType` identifies clients (1), domain controllers
|
||||||
|
(2), and other servers (3). Both server types are blocked from these categories,
|
||||||
|
even if enabled or selected by a Disk Cleanup preset:
|
||||||
|
|
||||||
|
- ShadowCopies
|
||||||
|
- DisableHibernation
|
||||||
|
- CompactSearch
|
||||||
|
- DownloadedExecutables and DuplicateDownloads
|
||||||
|
- OutlookBackups and ITunesBackups
|
||||||
|
- DiskCleanup (every handler, including any newly selected items)
|
||||||
|
|
||||||
|
Unknown or failed OS identification stops the run before changes. There is no
|
||||||
|
override. Disk Cleanup availability varies by Server version/installation; the
|
||||||
|
OS gate is enforced even if cleanmgr.exe exists. Native and file categories
|
||||||
|
outside this list can run on both clients and servers when enabled.
|
||||||
|
|
||||||
|
## All legacy Disk Cleanup operations
|
||||||
|
|
||||||
|
Every handler from Start-Cleanup.ps1 remains selectable, including those that
|
||||||
|
were disabled there. The old groups are listed here for migration; select a
|
||||||
|
preset above or exact handler names in `CleanupDiskCleanupItems`. The old group
|
||||||
|
names themselves are not accepted as presets.
|
||||||
|
|
||||||
|
| Old group | Handler names |
|
||||||
|
| --- | --- |
|
||||||
|
| User | Downloaded Program Files; Internet Cache Files; Offline Pages Files; Recycle Bin; Temporary Files; Thumbnail Cache; User file versions |
|
||||||
|
| System | Active Setup Temp Folders; BranchCache; Memory Dump Files; Old ChkDsk Files; RetailDemo Offline Content; Temporary Files; System error memory dump files; System error minidump files; Temporary Setup Files; Windows Defender; Windows Error Reporting Archive Files; Windows Error Reporting Queue Files; Windows Error Reporting System Archive Files; Windows Error Reporting System Queue Files; Windows Error Reporting Temp Files |
|
||||||
|
| WindowsUpdate | Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
|
||||||
|
| WindowsPreviousVersions | Previous Installations; Setup Log Files |
|
||||||
|
| Invasive | Windows ESD installation files |
|
||||||
|
| Misc | Content Indexer Cleaner; Delivery Optimization Files; Device Driver Packages; GameNewsFiles; GameStatisticsFiles; GameUpdateFiles; Temporary Sync Files |
|
||||||
|
|
||||||
|
Selecting a handler explicitly permits Windows to apply that handler's own
|
||||||
|
retention rules. The script's day settings **do not apply to cleanmgr**. For
|
||||||
|
example, its Recycle Bin/dump/WER handlers can remove recent data; its previous
|
||||||
|
installation/service pack/ESD handlers can remove rollback or recovery options.
|
||||||
|
`/sagerun` enumerates drives; it is not restricted to the system drive. The
|
||||||
|
default selection omits those recovery and diagnostic handlers.
|
||||||
|
|
||||||
|
Instead of persistent sageset flags or legacy NoSettings/NoCleaning/DeleteSettings
|
||||||
|
modes, each live run allocates an unused settings slot across all registered
|
||||||
|
handlers, writes only selected handlers, waits for cleanmgr, then removes its own
|
||||||
|
temporary flags in finally. Existing settings are preserved. Abnormal process
|
||||||
|
termination can leave a temporary slot behind; future runs skip occupied slots.
|
||||||
|
|
||||||
|
## Deletion and operational boundaries
|
||||||
|
|
||||||
|
- `OfficeStaging` checks the execution account's temp directory, Windows Temp and
|
||||||
|
SystemTemp, registered user/service profile temp directories, and legacy
|
||||||
|
ProgramData, under `EmberkomOfficeDeployment`. It runs on clients and servers.
|
||||||
|
The deployment mutex must be available, process inventory must succeed, and no
|
||||||
|
recognized installer may be running. Each workspace must have a GUID name and a
|
||||||
|
bounded, recognizable `options.json`; its directory, identity and every payload
|
||||||
|
artifact must be older than `CleanupTempDays`. Recent, linked, locked, unrecognized
|
||||||
|
or process-referenced workspaces are retained, including in report-only estimates.
|
||||||
|
- Office cleanup deletes only named payload artifacts (ODT, companion installers,
|
||||||
|
old GetHelp downloads and cache manifests). It preserves logs, options, XML,
|
||||||
|
helper scripts, locks, task markers, unknown files and the workspace itself.
|
||||||
|
Generic temp scans exclude this subtree, so they cannot bypass the dedicated
|
||||||
|
option, retention or active-deployment checks. Report-only lists eligible media
|
||||||
|
even when `CleanupOfficeStaging=false`; apply skips that disabled category.
|
||||||
|
Process and mutex skips remain visible in the compact report; per-folder
|
||||||
|
retention reasons are available through verbose output.
|
||||||
|
- Inspect each file's modification time; an old parent never authorizes deletion
|
||||||
|
of newer children. Ordinary cache/temp directories are retained.
|
||||||
|
- Use literal local paths, verify containment, and skip reparse points and linked
|
||||||
|
ancestors (including OneDrive placeholders). UNC paths and redirected profile
|
||||||
|
folders reached through links are skipped. No ownership or ACL changes.
|
||||||
|
- Skip in-use files. A category inventory failure is reported and later categories
|
||||||
|
continue; the run fails at the end if a category/maintenance operation failed.
|
||||||
|
- Generic temp cleanup excludes `.dmp`, `.ac$`, and AutoCAD `.sv$` autosaves.
|
||||||
|
Dumps get diagnostic retention; `.ac$` gets a separate closed-app check;
|
||||||
|
`.sv$` is retained. Revit model/recovery files and browser site storage are
|
||||||
|
outside the dedicated cache/journal targets.
|
||||||
|
- Backup/installer directories are inspected as complete units. Recent content
|
||||||
|
or links retain the unit, and apply mode probes for in-use files before deleting
|
||||||
|
any part of a unit. No recursive Remove-Item is used. Failed file deletion
|
||||||
|
retains the remaining directory; there is no transaction or rollback.
|
||||||
|
- Recycle Bin cleanup uses `$I` FILETIME metadata and removes the paired `$R`
|
||||||
|
content before its metadata. Unsupported/corrupt metadata is retained.
|
||||||
|
- Downloads are not discovered via redirected Known Folders. Duplicate matching
|
||||||
|
requires extension, size, and SHA-256 equality. Read handles prevent concurrent
|
||||||
|
writes during hashing/deletion; filesystem activity outside the script can still
|
||||||
|
rename or delete files, so this remains an opt-in operation.
|
||||||
|
- Active CBS cleanup never stops TrustedInstaller. Search compaction preserves
|
||||||
|
service startup settings, requires free space for a temporary database, and
|
||||||
|
restarts WSearch in finally only if it was originally running. An interrupted
|
||||||
|
native compaction can leave its uniquely named temporary database for inspection.
|
||||||
|
- VSS deletion uses exact inventoried snapshot IDs and preserves the newest;
|
||||||
|
native failures stop that category. Backup-managed snapshots may refuse deletion.
|
||||||
|
- Component cleanup uses Windows' scheduled task, with no ResetBase or direct
|
||||||
|
WinSxS deletion. Task submission is reported separately from completion.
|
||||||
|
- Native operations report exit codes and use hidden windows. No hard execution
|
||||||
|
timeout is imposed; allow adequate RMM runtime if enabling maintenance work.
|
||||||
|
- Byte counters are file lengths, not guaranteed physical disk savings (compression,
|
||||||
|
sparse files, hard links, and native cleanup affect actual reclaimed space).
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Run `powershell.exe -NoProfile -File tests/Start-SystemCleanup.Tests.ps1`.
|
||||||
|
Tests load function definitions via the AST, use disposable fixture directories,
|
||||||
|
and mock OS, registry, native processes, and service operations. They do not run
|
||||||
|
cleanup against the host's Windows folders or invoke maintenance programs.
|
||||||
|
Coverage includes disabled-category estimates, separate report groups, unique
|
||||||
|
totals for overlapping categories, and disabled categories remaining untouched in
|
||||||
|
apply mode. Preset tests verify exact handler membership, cumulative selections,
|
||||||
|
RMM scope preservation, None disabling native work, and the server exclusions.
|
||||||
|
Output tests cover the duplicate-object regression, a 23-category preview under
|
||||||
|
4 KiB including diagnostics, separate enabled/disabled sections, and preservation
|
||||||
|
of diagnostic notes. Regression checks ensure DISM analysis is absent and report
|
||||||
|
diagnostics launch no native programs.
|
||||||
|
Hibernation/VSS tests cover usage in category MiB columns, zero for absence,
|
||||||
|
unknown sizes after access failures, cross-drive storage, server exclusions, no
|
||||||
|
duplicate diagnostic lines, and usage staying out of savings totals.
|
||||||
|
Office staging tests cover Windows SystemTemp and legacy ProgramData, complete
|
||||||
|
artifact selection, identity/age/link/lock/process guards, deployment mutex
|
||||||
|
contention, disabled categories, server support, generic-temp exclusion, and
|
||||||
|
preservation of diagnostics and deferred-user files.
|
||||||
|
|
||||||
|
References: [OS ProductType](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem),
|
||||||
|
[Disk Cleanup](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cleanmgr),
|
||||||
|
[component cleanup](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/clean-up-the-winsxs-folder),
|
||||||
|
[component analysis](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/determine-the-actual-size-of-the-winsxs-folder?view=windows-11),
|
||||||
|
[shadow-storage measurements](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/vsswmi/win32-shadowstorage),
|
||||||
|
[Windows Search](https://learn.microsoft.com/troubleshoot/windows-client/shell-experience/windows-search-performance-issues).
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"Windows": {
|
||||||
|
"Version": "8.7.1.177",
|
||||||
|
"Url": "https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VmK3VHNmxBVEZTQkxhMFhNR2ZuZzJCeE80MDJxVkRSWXdNa0dqSHdpbUN1bE01c3BWNFBVUmt2Q1c4endncjVZemFSSjEyYmFNL3hESHR2eWpVYXpBVlV2eU1kZVZFaEpvalk2Rk40Wk96UG9QdUwxYnZrRHREMmhLeTZoMW5Rbz0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4",
|
||||||
|
"SHA256": "1EC7E1FAF23DE3D5C23BC147823D8A41A7A75B631E5E041EDEDF0A76233BF2FE"
|
||||||
|
},
|
||||||
|
"VM": {
|
||||||
|
"Version": "8.7.1.177",
|
||||||
|
"Url": "https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNwOTFVa3h6WUdoeVVod1JmT2lRQ1FlVTE3Y0pnUncwSEJwS3FFcDBmTWt3cEdnSy9YemRsSTRiQWJHNi96cUtWbzZsc25QVllaR1QyQ21VVS95dFFVTkNndXdPVStGQXBIT0FZb2FIUzFuZy9mMU5qZUd5emhab1hFYjZWODB4ND0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4",
|
||||||
|
"SHA256": "F247D73C30CCE522FDE6FCEB0F00984BB88D0010D657BC379A673BACAD32F804"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
#Requires -Version 5.1
|
#Requires -Version 5.1
|
||||||
# EmberkomOfficeUserCleanup-v4
|
# EmberkomOfficeUserCleanup-v5
|
||||||
# Run only as the affected user, at limited privilege; staged by the Office installer.
|
# Run only as the affected user, at limited privilege; fetched live by its logon task.
|
||||||
param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId)
|
param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId)
|
||||||
|
|
||||||
function Get-OfficeUserCleanupDefinitions {
|
function Get-OfficeUserCleanupDefinitions {
|
||||||
@@ -184,7 +184,9 @@ $null = Start-Transcript -Path (Join-Path $logFolder "$DeploymentId.log") -Appen
|
|||||||
try {
|
try {
|
||||||
$null = New-Item -Path $marker -Force
|
$null = New-Item -Path $marker -Force
|
||||||
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Running'
|
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Running'
|
||||||
Invoke-OfficeUserCleanup -Workspace $PSScriptRoot
|
# The scheduled action fetches this helper live into memory. Only protected
|
||||||
|
# synchronization state persists on disk; PSScriptRoot is empty in this mode.
|
||||||
|
Invoke-OfficeUserCleanup -Workspace (Join-Path $env:ProgramData "EmberkomOfficeDeployment\$DeploymentId")
|
||||||
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Complete'
|
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Complete'
|
||||||
} catch {
|
} catch {
|
||||||
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Failed'
|
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Failed'
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
|
||||||
|
Run-Script -LivePSScript Get-AllNetworkDrives
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
# Run as SYSTEM. Collects the last 72 hours of Office logs and current state into
|
||||||
|
# ProgramData\Emberkom\Logs\OfficeDiagnostics. No operator inputs are required.
|
||||||
|
# Does not install, uninstall, close apps, or launch the deployment script.
|
||||||
|
$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 Get-OfficeDeploymentDiagnostics
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
[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')))
|
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
|
||||||
|
|
||||||
# Set the edition of the ECB agent.
|
# Set the edition of the ECB agent.
|
||||||
|
|||||||
@@ -4,6 +4,15 @@
|
|||||||
# See docs/Office365-Deployment.md.
|
# See docs/Office365-Deployment.md.
|
||||||
# Configure these [string] Dropdown variables in Syncro:
|
# Configure these [string] Dropdown variables in Syncro:
|
||||||
# [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall)
|
# [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall)
|
||||||
|
# Assessment checks writable paths and HTTP HEAD 200; it creates no deployment directory or downloads.
|
||||||
|
# Deployment clears prior run artifacts, downloads fresh media before uninstalling, and leaves only logs.
|
||||||
|
# Only registered Click-to-Run products require removal; service/registry remnants alone do not.
|
||||||
|
# Failed removal with products remaining can trigger one Microsoft Get Help scrub.
|
||||||
|
# Scrub downloads are on demand, may display a child window, and honor DeferReboot after verification.
|
||||||
|
# Background scrub waits up to 30 minutes plus verification within Syncro's overall limit.
|
||||||
|
# Leave its window open during removal; dismiss a completed 'Press any key to exit' prompt.
|
||||||
|
# The child window cannot be reliably locked; failed/interrupted monitored workers stop installation.
|
||||||
|
# Pending user tasks keep synchronization markers and fetch their helper live. Active installers block cleanup.
|
||||||
# [string]$OfficeSubscription - Required; use the exact subscription names in the guide.
|
# [string]$OfficeSubscription - Required; use the exact subscription names in the guide.
|
||||||
# [string]$OfficeArchitecture - Auto (default), 64, 32
|
# [string]$OfficeArchitecture - Auto (default), 64, 32
|
||||||
# [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual
|
# [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
# Configure these [string] Dropdown variables in Syncro, each with true/false choices:
|
||||||
|
# [string]$CleanupReportOnly - true (default: assess all), false (apply enabled only)
|
||||||
|
# [string]$CleanupSystemTemp - true (default), false
|
||||||
|
# [string]$CleanupOfficeStaging - true (default), false; uses CleanupTempDays
|
||||||
|
# [string]$CleanupUserTemp - true (default), false
|
||||||
|
# [string]$CleanupServiceTemp - true (default), false
|
||||||
|
# [string]$CleanupCBSArchives - true (default), false
|
||||||
|
# [string]$CleanupActiveCBSLog - false (default), true
|
||||||
|
# [string]$CleanupCrashDumps - true (default), false
|
||||||
|
# [string]$CleanupWERArchives - true (default), false
|
||||||
|
# [string]$CleanupAutodeskInstallers - false (default), true
|
||||||
|
# [string]$CleanupRecycleBin - false (default), true
|
||||||
|
# [string]$CleanupDisableHibernation - false (default), true
|
||||||
|
# [string]$CleanupCompactSearch - false (default), true
|
||||||
|
# [string]$CleanupShadowCopies - false (default), true
|
||||||
|
# [string]$CleanupDownloadedExecutables - false (default), true
|
||||||
|
# [string]$CleanupDuplicateDownloads - false (default), true
|
||||||
|
# [string]$CleanupOutlookBackups - false (default), true
|
||||||
|
# [string]$CleanupITunesBackups - false (default), true
|
||||||
|
# [string]$CleanupAppleDownloads - false (default), true
|
||||||
|
# [string]$CleanupBrowserCache - false (default), true
|
||||||
|
# [string]$CleanupRevitJournals - true (default), false
|
||||||
|
# [string]$CleanupDeliveryOptimization - false (default), true
|
||||||
|
# [string]$CleanupComponentStore - false (default), true
|
||||||
|
# Configure this [string] Dropdown variable in Syncro with these exact choices:
|
||||||
|
# [string]$CleanupDiskCleanupItems - Standard (default)
|
||||||
|
# StandardAndUpdates
|
||||||
|
# StandardUpdatesAndDiagnostics
|
||||||
|
# All
|
||||||
|
# None
|
||||||
|
# None disables native Disk Cleanup. All includes Recycle Bin and recovery data.
|
||||||
|
# Configure these [string] Runtime variables if you need custom retention values:
|
||||||
|
# [string]$CleanupTempDays - 7 (default); whole days, 1-3650
|
||||||
|
# [string]$CleanupDiagnosticDays - 30 (default); whole days, 1-3650
|
||||||
|
# [string]$CleanupBackupDays - 30 (default); whole days, 1-3650
|
||||||
|
# Runtime values must be entered each run; omit these variables to use core defaults.
|
||||||
|
# Uploading this file does not define the variables or their selections in Syncro.
|
||||||
|
# Syncro injects the variables into the caller scope. Do not assign over them here.
|
||||||
|
# The main script parses the injected strings and supplies defaults for absent variables.
|
||||||
|
# Every variable configured in Syncro needs a nonempty value.
|
||||||
|
# Report-only assesses enabled AND disabled categories in separate report sections.
|
||||||
|
# Compact output shows totals first and one row per category; no duplicate object dump.
|
||||||
|
# Hibernation/VSS usage appears in the category MiB column (0.00 if absent).
|
||||||
|
# Report-only also notes potential component-store savings without estimating them.
|
||||||
|
# Usage is excluded from savings. Hibernation/VSS remain unassessed on servers.
|
||||||
|
# Reports do not run DISM analysis; savings from superseded updates are not estimated.
|
||||||
|
# For full diagnostics, set $VerbosePreference = 'Continue' before Run-Script.
|
||||||
|
# Verbose output can exceed Syncro's output limit. No new Syncro variables are needed.
|
||||||
|
# Server-blocked categories are listed without assessment. Native savings may be unknown.
|
||||||
|
# Server exclusions cannot be overridden by these variables. No reboot is initiated.
|
||||||
|
# OfficeStaging checks Windows Temp/SystemTemp, execution/profile temp and legacy ProgramData.
|
||||||
|
# Only recognized, aged installer media is eligible; active deployments and user helpers are protected.
|
||||||
|
|
||||||
|
$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')))
|
||||||
|
# No -Arguments: Run-Script must dot-source the core into this caller's scope.
|
||||||
|
Run-Script -LivePSScript Start-SystemCleanup
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#Requires -Version 4.0
|
||||||
|
# Syncro: run as SYSTEM at a time reserved between backup, restore and consistency plans.
|
||||||
|
# Optional string $MSP360UpdateWindow, e.g. '12:00-13:00' in endpoint local time.
|
||||||
|
# Leave blank to use the Syncro schedule alone. See docs/EmberkomCloudBackup-Updates.md.
|
||||||
|
$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 Update-EmberkomCloudBackup
|
||||||
|
exit $LASTEXITCODE
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
# Offline binding tests: keep the real parameter declaration and shim, replace
|
||||||
|
# the inventory body with a probe, and mock downloads. No registry/COM operations.
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$DriveTestRepo = Split-Path $PSScriptRoot -Parent
|
||||||
|
$DriveTestTokens = $null
|
||||||
|
$DriveTestErrors = $null
|
||||||
|
$DriveTestToolsAst = [Management.Automation.Language.Parser]::ParseFile(
|
||||||
|
(Join-Path $DriveTestRepo 'Tools.ps1'), [ref]$DriveTestTokens, [ref]$DriveTestErrors)
|
||||||
|
If ($DriveTestErrors.Count) { Throw ($DriveTestErrors | Out-String) }
|
||||||
|
$DriveTestRunDefinition = $DriveTestToolsAst.Find({
|
||||||
|
param($Node)
|
||||||
|
$Node -is [Management.Automation.Language.FunctionDefinitionAst] -and $Node.Name -eq 'Run-Script'
|
||||||
|
}, $true)
|
||||||
|
If (!$DriveTestRunDefinition) { Throw 'Missing helper: Run-Script' }
|
||||||
|
. ([scriptblock]::Create($DriveTestRunDefinition.Extent.Text))
|
||||||
|
|
||||||
|
$DriveTestInventoryAst = [Management.Automation.Language.Parser]::ParseFile(
|
||||||
|
(Join-Path $DriveTestRepo 'Get-AllNetworkDrives.ps1'), [ref]$DriveTestTokens, [ref]$DriveTestErrors)
|
||||||
|
If ($DriveTestErrors.Count) { Throw ($DriveTestErrors | Out-String) }
|
||||||
|
$DriveTestProbeSource = $DriveTestInventoryAst.ParamBlock.Extent.Text + [Environment]::NewLine + @'
|
||||||
|
[pscustomobject]@{
|
||||||
|
Probe = 'NetworkDrives'
|
||||||
|
SavedOnly = $SavedOnly.IsPresent
|
||||||
|
CallerValue = $DriveTestCallerValue
|
||||||
|
}
|
||||||
|
'@
|
||||||
|
$DriveTestProbe = [scriptblock]::Create($DriveTestProbeSource)
|
||||||
|
|
||||||
|
Function IsURLValid { Return $true }
|
||||||
|
Function Download-File { Throw 'This fix must retain the existing Run-Script download path.' }
|
||||||
|
Function New-Object {
|
||||||
|
param([string]$TypeName)
|
||||||
|
If ($TypeName -ne 'Net.WebClient') { Throw "Unexpected object in test: $TypeName" }
|
||||||
|
$Client = [pscustomobject]@{}
|
||||||
|
$Client | Add-Member -MemberType ScriptMethod -Name DownloadString -Value {
|
||||||
|
param($URL)
|
||||||
|
$script:DriveTestWebDownloads++
|
||||||
|
Switch ($URL) {
|
||||||
|
'https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1' {
|
||||||
|
Return $script:DriveTestRunDefinition.Extent.Text
|
||||||
|
}
|
||||||
|
'https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Get-AllNetworkDrives.ps1' {
|
||||||
|
Return $script:DriveTestProbeSource
|
||||||
|
}
|
||||||
|
default { Throw "Unexpected URL in test: $URL" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Return $Client
|
||||||
|
}
|
||||||
|
|
||||||
|
Function Test-DriveRmmBinding {
|
||||||
|
param([string]$Name, [hashtable]$Parameters, [switch]$UseShim)
|
||||||
|
$script:DriveTestWebDownloads = 0
|
||||||
|
$DriveTestCallerValue = 'Caller value with spaces & symbols'
|
||||||
|
$Output = @(If ($UseShim) {
|
||||||
|
. (Join-Path $DriveTestRepo 'rmm\Get-AllNetworkDrives.ps1')
|
||||||
|
} Else {
|
||||||
|
Run-Script -LivePSScript Get-AllNetworkDrives @Parameters
|
||||||
|
})
|
||||||
|
$Probe = @($Output | Where-Object { $_.PSObject.Properties['Probe'] })
|
||||||
|
If ($Probe.Count -ne 1 -or $Probe[0].SavedOnly -ne $false -or
|
||||||
|
$Probe[0].CallerValue -cne $DriveTestCallerValue) {
|
||||||
|
Throw "${Name}: must run with SavedOnly false and retain access to caller variables."
|
||||||
|
}
|
||||||
|
$ExpectedDownloads = If ($UseShim) { 2 } Else { 1 }
|
||||||
|
If ($script:DriveTestWebDownloads -ne $ExpectedDownloads) { Throw "${Name}: unexpected download path." }
|
||||||
|
Write-Host "PASS: ${Name}: empty argument tolerated, caller variables visible, existing download path retained."
|
||||||
|
}
|
||||||
|
|
||||||
|
Test-DriveRmmBinding -Name 'Omitted Arguments' -Parameters @{}
|
||||||
|
Test-DriveRmmBinding -Name 'Null Arguments' -Parameters @{Arguments=$null}
|
||||||
|
Test-DriveRmmBinding -Name 'Empty Arguments' -Parameters @{Arguments=''}
|
||||||
|
Test-DriveRmmBinding -Name 'Legacy null sentinel' -Parameters @{Arguments='null'}
|
||||||
|
Test-DriveRmmBinding -Name 'Whitespace Arguments' -Parameters @{Arguments=" `t`r`n "}
|
||||||
|
Test-DriveRmmBinding -Name 'Real Syncro shim' -UseShim
|
||||||
|
|
||||||
|
$DriveTestCallerValue = 'Direct caller'
|
||||||
|
Foreach ($Case in @(
|
||||||
|
@{Name='No parameters'; Parameters=@{}; Expected=$false}
|
||||||
|
@{Name='SavedOnly true'; Parameters=@{SavedOnly=$true}; Expected=$true}
|
||||||
|
@{Name='SavedOnly false'; Parameters=@{SavedOnly=$false}; Expected=$false}
|
||||||
|
)) {
|
||||||
|
$Parameters = $Case.Parameters
|
||||||
|
$Probe = @(& $DriveTestProbe @Parameters)
|
||||||
|
If ($Probe.Count -ne 1 -or $Probe[0].SavedOnly -ne $Case.Expected) { Throw "Direct invocation failed: $($Case.Name)" }
|
||||||
|
}
|
||||||
|
$Probe = & $DriveTestProbe -SavedOnly
|
||||||
|
If ($Probe.SavedOnly -ne $true) { Throw 'The bare -SavedOnly switch must still enable saved-only inventory.' }
|
||||||
|
& {
|
||||||
|
$Probe = . $DriveTestProbe -SavedOnly:$false
|
||||||
|
If ($Probe.SavedOnly -ne $false -or $Probe.CallerValue -cne $DriveTestCallerValue) {
|
||||||
|
Throw 'Dot-sourced invocation must preserve switch behavior and caller-variable access.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-Host 'PASS: direct and dot-sourced invocations preserve optional SavedOnly behavior.'
|
||||||
|
|
||||||
|
Foreach ($UnexpectedArgument in @('false', 'true', '-SavedOnly', 'unexpected')) {
|
||||||
|
$Caught = $null
|
||||||
|
Try { Invoke-Command -ScriptBlock $DriveTestProbe -ArgumentList $UnexpectedArgument | Out-Null }
|
||||||
|
Catch { $Caught = $_ }
|
||||||
|
If ($null -eq $Caught) { Throw "Unexpected positional input was silently accepted: $UnexpectedArgument" }
|
||||||
|
}
|
||||||
|
Write-Host 'PASS: nonblank positional input is rejected instead of silently ignored.'
|
||||||
|
Write-Host "All Get-AllNetworkDrives binding tests passed on PowerShell $($PSVersionTable.PSVersion), $([IntPtr]::Size * 8)-bit."
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
if ($PSVersionTable.PSEdition -ne 'Desktop') { throw 'Run with Windows PowerShell 5.1.' }
|
||||||
|
$repo = Split-Path -Parent $PSScriptRoot
|
||||||
|
$testRoot = Join-Path $env:TEMP ('OfficeDiagnosticsTests-' + [guid]::NewGuid().ToString('N'))
|
||||||
|
$originalTemp = [IO.Path]::GetFullPath($env:TEMP).TrimEnd('\') + '\'
|
||||||
|
$nativePowerShell = Join-Path $env:windir 'System32\WindowsPowerShell\v1.0\powershell.exe'
|
||||||
|
$null = New-Item -ItemType Directory -Path $testRoot
|
||||||
|
$script:assertions = 0
|
||||||
|
function Assert-DiagnosticTest { param([bool]$Condition, [string]$Message) $script:assertions++; if (!$Condition) { throw $Message } }
|
||||||
|
function Read-DiagnosticAst {
|
||||||
|
param([string]$Path)
|
||||||
|
$tokens=$null; $errors=$null
|
||||||
|
$ast=[Management.Automation.Language.Parser]::ParseFile($Path,[ref]$tokens,[ref]$errors)
|
||||||
|
if ($errors.Count) { throw ($errors | Out-String) }
|
||||||
|
$ast
|
||||||
|
}
|
||||||
|
function Read-ZipText {
|
||||||
|
param($Archive,[string]$Name)
|
||||||
|
$reader=New-Object IO.StreamReader($Archive.GetEntry($Name).Open())
|
||||||
|
try { $reader.ReadToEnd() } finally { $reader.Dispose() }
|
||||||
|
}
|
||||||
|
$savedEnvironment=@{}
|
||||||
|
try {
|
||||||
|
$coreAst=Read-DiagnosticAst (Join-Path $repo 'Get-OfficeDeploymentDiagnostics.ps1')
|
||||||
|
$shimAst=Read-DiagnosticAst (Join-Path $repo 'rmm\Get-OfficeDeploymentDiagnostics.ps1')
|
||||||
|
Assert-DiagnosticTest (!$coreAst.ParamBlock -and !$shimAst.ParamBlock) 'RMM scripts must not introduce script parameters.'
|
||||||
|
$definitions=@($coreAst.FindAll({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst]},$false))
|
||||||
|
foreach ($definition in $definitions) { . ([scriptblock]::Create($definition.Extent.Text)) }
|
||||||
|
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||||
|
$source=Join-Path $testRoot 'source'; $null=New-Item -ItemType Directory -Path "$source\nested\deep" -Force
|
||||||
|
[IO.File]::WriteAllText("$source\live.log",'fixture with Unicode: caf'+[char]0xE9)
|
||||||
|
[IO.File]::WriteAllText("$source\install.xml",'<Configuration />')
|
||||||
|
[IO.File]::WriteAllText("$source\media.dat",'not diagnostics')
|
||||||
|
[IO.File]::WriteAllText("$source\nested\child.log",'child log')
|
||||||
|
[IO.File]::WriteAllText("$source\nested\deep\excluded.log",'too deep')
|
||||||
|
$issues=New-Object 'Collections.Generic.List[string]'
|
||||||
|
$files=@(Get-OfficeDiagnosticFiles $source @('*.log','install.xml') ([datetime]::UtcNow.AddHours(-1)) 1 $issues)
|
||||||
|
Assert-DiagnosticTest ($files.Count -eq 3 -and !@($files | Where-Object {$_.Name -in @('media.dat','excluded.log')}).Count) 'Only requested diagnostics within the recursion depth may be collected.'
|
||||||
|
Assert-DiagnosticTest (@(Get-OfficeDiagnosticFiles $source @('*.log') ([datetime]::UtcNow.AddHours(1)) 1 $issues).Count -eq 0) 'Old files must be excluded by the time window.'
|
||||||
|
$before=(Get-FileHash -LiteralPath "$source\live.log").Hash
|
||||||
|
$held=[IO.File]::Open("$source\live.log",[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::ReadWrite)
|
||||||
|
try { New-OfficeDiagnosticArchive "$testRoot\fixture.zip" ($files + $files) @{CurrentStateOnly=$true} $issues }
|
||||||
|
finally { $held.Dispose() }
|
||||||
|
$zip=[IO.Compression.ZipFile]::OpenRead("$testRoot\fixture.zip")
|
||||||
|
try {
|
||||||
|
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
|
||||||
|
Assert-DiagnosticTest ($manifest.Count -eq 3 -and @($manifest | Where-Object {$_.Status -notlike 'Captured*'}).Count -eq 0) 'Duplicate paths must be collected once, including a log open by another writer.'
|
||||||
|
$entry=@($manifest | Where-Object {$_.Source -eq "$source\live.log"})[0]
|
||||||
|
Assert-DiagnosticTest ((Read-ZipText $zip $entry.Entry) -eq [IO.File]::ReadAllText("$source\live.log")) 'Captured bytes must preserve source encoding/content.'
|
||||||
|
Assert-DiagnosticTest ($null -ne $zip.GetEntry('endpoint.json') -and $null -ne $zip.GetEntry('collection-issues.json')) 'Metadata and collection omissions must accompany the logs.'
|
||||||
|
} finally { $zip.Dispose() }
|
||||||
|
Assert-DiagnosticTest ((Get-FileHash -LiteralPath "$source\live.log").Hash -eq $before) 'Source logs must remain unchanged.'
|
||||||
|
$big=[IO.File]::Create("$source\oversize.log"); try {$big.SetLength(64MB+1)} finally {$big.Dispose()}
|
||||||
|
$issues=New-Object 'Collections.Generic.List[string]'
|
||||||
|
New-OfficeDiagnosticArchive "$testRoot\limits.zip" @((Get-Item "$source\oversize.log")) @{} $issues
|
||||||
|
Assert-DiagnosticTest ($issues.Count -eq 1 -and $issues[0] -match 'Collection limit') 'Oversize logs must be reported as omitted, not silently lost.'
|
||||||
|
|
||||||
|
# Exercise the actual Run-Script helper with mocked live downloads and queries.
|
||||||
|
# The core's registry reader is replaced only in the fixture downloaded by this test.
|
||||||
|
$toolsAst=Read-DiagnosticAst (Join-Path $repo 'Tools.ps1')
|
||||||
|
$runDefinition=$toolsAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script'},$false)
|
||||||
|
. ([scriptblock]::Create($runDefinition.Extent.Text))
|
||||||
|
function IsURLValid { param($URL) $true }
|
||||||
|
function Download-File { param($URL) Assert-DiagnosticTest ($URL -like '*/Get-OfficeDeploymentDiagnostics.ps1') 'Caller must request the diagnostic core.'; "$testRoot\downloaded-core.ps1" }
|
||||||
|
$fixtureCore=($definitions | Where-Object {$_.Name -ne 'Get-OfficeDiagnosticRegistry'} | ForEach-Object {$_.Extent.Text}) -join "`r`n"
|
||||||
|
$fixtureCore += "`r`nInvoke-OfficeDiagnosticCollection"
|
||||||
|
[IO.File]::WriteAllText("$testRoot\downloaded-core.ps1",$fixtureCore)
|
||||||
|
function New-Object {
|
||||||
|
param([string]$TypeName,[object[]]$ArgumentList)
|
||||||
|
if ($TypeName -eq 'Security.Principal.WindowsPrincipal') {
|
||||||
|
$principal=[pscustomobject]@{}
|
||||||
|
$principal | Add-Member ScriptMethod IsInRole { $true }
|
||||||
|
return $principal
|
||||||
|
}
|
||||||
|
if ($TypeName -eq 'Net.WebClient') {
|
||||||
|
$client=[pscustomobject]@{}
|
||||||
|
$client | Add-Member ScriptMethod DownloadString {param($Url) if ($Url -notlike '*/Get-OfficeDeploymentDiagnostics.ps1') {throw "Unexpected URL $Url"}; [IO.File]::ReadAllText("$testRoot\downloaded-core.ps1")}
|
||||||
|
return $client
|
||||||
|
}
|
||||||
|
Microsoft.PowerShell.Utility\New-Object @PSBoundParameters
|
||||||
|
}
|
||||||
|
function Get-OfficeDiagnosticRegistry { [pscustomobject]@{Name='ProductReleaseIds';Value='FixtureOffice'} }
|
||||||
|
function Get-CimInstance {
|
||||||
|
param($ClassName,$Filter,$ErrorAction)
|
||||||
|
switch ($ClassName) {
|
||||||
|
Win32_OperatingSystem { [pscustomobject]@{Caption='Fixture';LastBootUpTime=[datetime]'2026-10-30T08:00:00'} }
|
||||||
|
Win32_UserProfile { [pscustomobject]@{SID='S-1-fixture';LocalPath="$testRoot\other-user";Loaded=$false;Special=$false} }
|
||||||
|
Win32_Process { [pscustomobject]@{Name='powershell.exe';ProcessId=456;SessionId=2;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\fixture\Run.ps1'} }
|
||||||
|
Win32_Service { [pscustomobject]@{Name='ClickToRunSvc';State='Running'} }
|
||||||
|
default { throw "Unexpected CIM query $ClassName" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function Invoke-CimMethod { [pscustomobject]@{Domain='Fixture';User='OtherUser';ReturnValue=0} }
|
||||||
|
function Get-ScheduledTask { @() }
|
||||||
|
foreach ($name in @('TEMP','LOCALAPPDATA','ProgramData','windir','COMPUTERNAME')) { $savedEnvironment[$name]=[Environment]::GetEnvironmentVariable($name,'Process') }
|
||||||
|
$env:TEMP="$testRoot\temp"; $env:LOCALAPPDATA="$testRoot\current-user"; $env:ProgramData="$testRoot\programdata"; $env:windir="$testRoot\Windows"; $env:COMPUTERNAME='FIXTURE'
|
||||||
|
foreach ($directory in @($env:TEMP,"$testRoot\other-user\AppData\Local\DAFs","$env:windir\Temp","$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT")) { $null=New-Item -ItemType Directory -Path $directory -Force }
|
||||||
|
[IO.File]::WriteAllText("$testRoot\other-user\AppData\Local\DAFs\cse.amplify.diagaction.gethelp.officeuninstallalda_fixture.log",'Report from another user')
|
||||||
|
[IO.File]::WriteAllText("$env:windir\Temp\FIXTURE-20261030-0900.log",'Native install fixture')
|
||||||
|
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\install.xml",'<Configuration />')
|
||||||
|
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT\setup.exe",'Excluded executable fixture')
|
||||||
|
$result=@(Run-Script -LivePSScript Get-OfficeDeploymentDiagnostics)
|
||||||
|
$bundle=@(Get-ChildItem -LiteralPath "$env:ProgramData\Emberkom\Logs\OfficeDiagnostics" -Filter '*.zip')
|
||||||
|
Assert-DiagnosticTest ($bundle.Count -eq 1 -and ($result -join "`n") -match 'Office diagnostic ZIP') 'The real RMM loader must execute the diagnostic core and return its ZIP path.'
|
||||||
|
$zip=[IO.Compression.ZipFile]::OpenRead($bundle[0].FullName)
|
||||||
|
try {
|
||||||
|
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
|
||||||
|
$report=Read-ZipText $zip 'endpoint.json' | ConvertFrom-Json
|
||||||
|
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*other-user*DAFs*'}).Count -eq 1) 'DAF reports from profiles other than the caller must be captured.'
|
||||||
|
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*FIXTURE-20261030-0900.log'}).Count -eq 1) 'Native logs must be captured.'
|
||||||
|
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*install.xml'}).Count -eq 1 -and !@($manifest | Where-Object {$_.Source -like '*.exe'}).Count) 'Archive configurations but never installation media.'
|
||||||
|
Assert-DiagnosticTest ($report.Workers[0].Owner -eq 'Fixture\OtherUser' -and $report.Workers[0].SessionId -eq 2) 'Worker ownership and session must be recorded.'
|
||||||
|
Assert-DiagnosticTest ($report.OfficeRegistry[0].Value -eq 'FixtureOffice') 'Current Office state must be recorded separately from historical logs.'
|
||||||
|
} finally { $zip.Dispose() }
|
||||||
|
# Core failures must signal failure to RMM instead of claiming a ZIP was created.
|
||||||
|
$entry=$coreAst.EndBlock.Statements[-1].Extent.Text
|
||||||
|
[IO.File]::WriteAllText("$testRoot\failure.ps1", "function Invoke-OfficeDiagnosticCollection { throw 'Fixture collection failure' }`r`n$entry")
|
||||||
|
$ErrorActionPreference='Continue'
|
||||||
|
try { & $nativePowerShell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$testRoot\failure.ps1" *> "$testRoot\failure-output.log" }
|
||||||
|
finally { $ErrorActionPreference='Stop' }
|
||||||
|
Assert-DiagnosticTest ($LASTEXITCODE -eq 1) 'A failed diagnostic collection must exit 1.'
|
||||||
|
Write-Output "PASS: $script:assertions diagnostic assertions. Queries/downloads mocked; no Office changes."
|
||||||
|
} finally {
|
||||||
|
foreach ($name in $savedEnvironment.Keys) { [Environment]::SetEnvironmentVariable($name,$savedEnvironment[$name],'Process') }
|
||||||
|
$resolved=[IO.Path]::GetFullPath($testRoot)
|
||||||
|
if (!$resolved.StartsWith($originalTemp,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notlike 'OfficeDiagnosticsTests-*') { throw 'Unsafe test cleanup path.' }
|
||||||
|
Remove-Item -LiteralPath $resolved -Recurse -Force -ErrorAction Stop
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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" }
|
||||||
|
}
|
||||||
@@ -0,0 +1,708 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
# Offline: AST-load cleanup functions; mock shim downloads and native operations.
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$repo = Split-Path -Parent $PSScriptRoot
|
||||||
|
$testRoot = Join-Path $env:TEMP ('SystemCleanupTests-' + [guid]::NewGuid().ToString('N'))
|
||||||
|
$null = New-Item -ItemType Directory -Path $testRoot
|
||||||
|
$script:assertions = 0
|
||||||
|
function Assert-Cleanup { param([bool]$Condition, [string]$Message) $script:assertions++; if (-not $Condition) { throw $Message } }
|
||||||
|
function Assert-CleanupThrows {
|
||||||
|
param([scriptblock]$Action, [string]$Pattern)
|
||||||
|
$caught = $null
|
||||||
|
try { & $Action | Out-Null } catch { $caught = $_ }
|
||||||
|
Assert-Cleanup ($null -ne $caught -and $caught.Exception.Message -match $Pattern) "Expected '$Pattern', got '$caught'."
|
||||||
|
}
|
||||||
|
function Read-CleanupAst {
|
||||||
|
param([string]$File)
|
||||||
|
$tokens = $null; $errors = $null
|
||||||
|
$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $repo $File), [ref]$tokens, [ref]$errors)
|
||||||
|
if ($errors.Count) { throw ($errors | Out-String) }
|
||||||
|
return $ast
|
||||||
|
}
|
||||||
|
function New-CleanupFixture {
|
||||||
|
param([string]$Relative, [string]$Content = 'fixture', [int]$Days = 60)
|
||||||
|
$path = Join-Path $testRoot $Relative
|
||||||
|
$null = [IO.Directory]::CreateDirectory((Split-Path -Parent $path))
|
||||||
|
[IO.File]::WriteAllText($path, $Content)
|
||||||
|
[IO.File]::SetLastWriteTimeUtc($path, [datetime]::UtcNow.AddDays(-$Days))
|
||||||
|
return $path
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$core = Read-CleanupAst 'Start-SystemCleanup.ps1'
|
||||||
|
$shim = Read-CleanupAst 'rmm/Start-SystemCleanup.ps1'
|
||||||
|
Assert-Cleanup ($core.Extent.Text -notmatch '(?i)AnalyzeComponentStore|dism\.exe') 'Reports must not ship a DISM analysis invocation.'
|
||||||
|
foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) {
|
||||||
|
. ([scriptblock]::Create($definition.Extent.Text))
|
||||||
|
}
|
||||||
|
# Never contend with a real deployment on the test host.
|
||||||
|
function New-SystemCleanupOfficeMutex { return [Threading.Mutex]::new($false) }
|
||||||
|
$messageWriter = ${function:Write-SystemCleanupMessage}
|
||||||
|
$script:messages = @(); $script:details = @()
|
||||||
|
function Write-SystemCleanupMessage {
|
||||||
|
param($Message, [switch]$Detail)
|
||||||
|
if ($Detail) { $script:details += $Message } else { $script:messages += $Message }
|
||||||
|
}
|
||||||
|
& {
|
||||||
|
$VerbosePreference = 'SilentlyContinue'
|
||||||
|
$visible = @(& $messageWriter 'compact output' 6>&1)
|
||||||
|
$hidden = @(& $messageWriter 'handler inventory' -Detail 4>&1 6>&1)
|
||||||
|
Assert-Cleanup ($visible.Count -eq 1 -and [string]$visible[0] -match 'compact output' -and $hidden.Count -eq 0) 'Verbose diagnostics must not consume the normal RMM output budget.'
|
||||||
|
$VerbosePreference = 'Continue'
|
||||||
|
$verbose = @(& $messageWriter 'handler inventory' -Detail 4>&1)
|
||||||
|
Assert-Cleanup ($verbose.Count -eq 1 -and $verbose[0] -is [Management.Automation.VerboseRecord]) 'Full diagnostics must remain available on the verbose stream.'
|
||||||
|
}
|
||||||
|
& {
|
||||||
|
# Run the actual entry statement with an inert function. The host summary
|
||||||
|
# must survive, while success-stream objects must not become a second report.
|
||||||
|
function Invoke-SystemCleanup {
|
||||||
|
param($Options)
|
||||||
|
Write-SystemCleanupMessage 'entry summary'
|
||||||
|
[pscustomobject]@{Category='Fixture'; Enabled=$true; CandidateFiles=1}
|
||||||
|
}
|
||||||
|
$script:messages = @()
|
||||||
|
$output = @(& ([scriptblock]::Create($core.EndBlock.Statements[-1].Extent.Text)))
|
||||||
|
Assert-Cleanup ($output.Count -eq 0 -and $script:messages -contains 'entry summary') 'Core entry must suppress the duplicate object dump without suppressing the summary.'
|
||||||
|
}
|
||||||
|
function New-CleanupContext {
|
||||||
|
param([bool]$ReportOnly = $true, [bool]$Server = $false)
|
||||||
|
return @{
|
||||||
|
Options = Get-SystemCleanupOptions; OS = [pscustomobject]@{IsServer=$Server; Caption='Fixture'}
|
||||||
|
Stats=[ordered]@{}; Errors=0
|
||||||
|
Seen=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
} | ForEach-Object { $_.Options.ReportOnly=$ReportOnly; $_ }
|
||||||
|
}
|
||||||
|
# Defaults and RMM shared scope: values defined outside the loader must survive.
|
||||||
|
$options = Get-SystemCleanupOptions
|
||||||
|
Assert-Cleanup ($options.ReportOnly -and $options.TempDays -eq 7 -and $options.DiagnosticDays -eq 30) 'Unsafe defaults.'
|
||||||
|
Assert-Cleanup ($options.DiskCleanupPreset -eq 'Standard' -and -not $options.ContainsKey('DiskCleanup')) 'Disk Cleanup must use a single selection, defaulting to Standard.'
|
||||||
|
# Lock down the intended policy: adding handlers changes what operators permit.
|
||||||
|
$expectedStandard = @('Downloaded Program Files','Internet Cache Files','Thumbnail Cache','Active Setup Temp Folders','Temporary Setup Files','Windows Defender','RetailDemo Offline Content')
|
||||||
|
$expectedUpdates = @('Service Pack Cleanup','Update Cleanup','Upgrade Discarded Files','Windows Upgrade Log Files')
|
||||||
|
$expectedDiagnostics = @('Memory Dump Files','Old ChkDsk Files','System error memory dump files','System error minidump files','Setup Log Files','Windows Error Reporting Archive Files','Windows Error Reporting Queue Files','Windows Error Reporting System Archive Files','Windows Error Reporting System Queue Files','Windows Error Reporting Temp Files')
|
||||||
|
$expectedPresets = [ordered]@{
|
||||||
|
Standard = $expectedStandard
|
||||||
|
StandardAndUpdates = @($expectedStandard + $expectedUpdates)
|
||||||
|
StandardUpdatesAndDiagnostics = @($expectedStandard + $expectedUpdates + $expectedDiagnostics)
|
||||||
|
All = @(Get-SystemCleanupHandlers)
|
||||||
|
None = @()
|
||||||
|
}
|
||||||
|
foreach ($presetName in $expectedPresets.Keys) {
|
||||||
|
& {
|
||||||
|
$CleanupDiskCleanupItems = ' ' + $presetName.ToLowerInvariant() + ' '
|
||||||
|
$parsed = Get-SystemCleanupOptions
|
||||||
|
Assert-Cleanup ($parsed.DiskCleanupPreset -ceq $presetName) "Preset normalization failed: $presetName"
|
||||||
|
Assert-Cleanup (($parsed.DiskCleanupItems -join '|') -ceq ($expectedPresets[$presetName] -join '|')) "Unexpected cleanup scope for $presetName"
|
||||||
|
Assert-Cleanup ($parsed.DiskCleanupItems -is [array]) "Preset $presetName did not produce an array."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
& {
|
||||||
|
$CleanupDiskCleanupItems = @(' thumbnail cache ', 'INTERNET CACHE FILES', 'Thumbnail Cache')
|
||||||
|
$parsed = Get-SystemCleanupOptions
|
||||||
|
Assert-Cleanup ($parsed.DiskCleanupPreset -eq 'Custom' -and ($parsed.DiskCleanupItems -join ',') -ceq 'Thumbnail Cache,Internet Cache Files') 'Custom arrays must normalize and deduplicate handlers.'
|
||||||
|
foreach ($invalid in @('Standrad', 'None,Thumbnail Cache', 'Standard,All', 'Standard,Internet Cache Files')) {
|
||||||
|
$CleanupDiskCleanupItems = $invalid
|
||||||
|
Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup preset or item'
|
||||||
|
}
|
||||||
|
foreach ($blank in @('', ' ', ',', $null, @())) {
|
||||||
|
$CleanupDiskCleanupItems = $blank
|
||||||
|
Assert-CleanupThrows { Get-SystemCleanupOptions } 'cannot be blank'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
& {
|
||||||
|
foreach ($oldValue in @('false', 'true')) {
|
||||||
|
$CleanupDiskCleanup = $oldValue
|
||||||
|
Assert-CleanupThrows { Get-SystemCleanupOptions } 'CleanupDiskCleanup has been removed'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
& {
|
||||||
|
$CleanupReportOnly = 'false'; $CleanupShadowCopies = ' no '; $CleanupTempDays = '14'
|
||||||
|
$CleanupDiskCleanupItems = 'Thumbnail Cache,Internet Cache Files'
|
||||||
|
$o = Get-SystemCleanupOptions
|
||||||
|
Assert-Cleanup (-not $o.ReportOnly -and -not $o.ShadowCopies -and $o.TempDays -eq 14 -and $o.DiskCleanupItems.Count -eq 2) 'Caller scope/text parsing failed.'
|
||||||
|
Assert-Cleanup ($CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14') 'Caller variables were overwritten.'
|
||||||
|
$CleanupReportOnly = 'maybe'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'must be true or false'
|
||||||
|
$CleanupReportOnly = $true; $CleanupTempDays = 0; Assert-CleanupThrows { Get-SystemCleanupOptions } 'whole number'
|
||||||
|
$CleanupTempDays = 7; $CleanupDiskCleanupItems = 'Unknown handler'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup'
|
||||||
|
}
|
||||||
|
$legacy = Get-Content -LiteralPath (Join-Path $repo 'Start-Cleanup.ps1') -Raw
|
||||||
|
$legacyHandlers = @([regex]::Matches($legacy, '"([^"\r\n]+)"\s*=\s*\$(?:true|false);') | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique)
|
||||||
|
foreach ($handler in $legacyHandlers) { Assert-Cleanup ($handler -in (Get-SystemCleanupHandlers)) "Lost legacy cleanup handler: $handler" }
|
||||||
|
Assert-Cleanup ($legacyHandlers.Count -eq (Get-SystemCleanupHandlers).Count) 'Unexpected handler inventory mismatch.'
|
||||||
|
$runCommand = $shim.Find({param($n) $n -is [Management.Automation.Language.CommandAst] -and $n.GetCommandName() -eq 'Run-Script'}, $true)
|
||||||
|
Assert-Cleanup ($runCommand.Extent.Text -eq 'Run-Script -LivePSScript Start-SystemCleanup') 'Shim must use dot-sourcing Run-Script without Arguments.'
|
||||||
|
& {
|
||||||
|
# Exercise the actual shim and real Run-Script with Syncro-style strings.
|
||||||
|
# Both download implementations return inert source; no real WebClient is created.
|
||||||
|
$toolsAst=Read-CleanupAst 'Tools.ps1'
|
||||||
|
$runner=$toolsAst.Find({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Run-Script'}, $true)
|
||||||
|
$script:cleanupMockTools=$runner.Extent.Text
|
||||||
|
$fixtureWorkload=New-CleanupFixture 'rmm-scope.ps1' 'Get-SystemCleanupOptions'
|
||||||
|
function IsURLValid { return $true }
|
||||||
|
function Download-File { return $fixtureWorkload }
|
||||||
|
function New-Object {
|
||||||
|
param($TypeName)
|
||||||
|
if ($TypeName -ne 'Net.WebClient') { throw "Unexpected object in shim probe: $TypeName" }
|
||||||
|
$client=[pscustomobject]@{}
|
||||||
|
$client | Add-Member ScriptMethod DownloadString {
|
||||||
|
param($URL)
|
||||||
|
if ($URL -match '/Tools\.ps1$') { return $script:cleanupMockTools }
|
||||||
|
if ($URL -match '/Start-SystemCleanup\.ps1$') { return 'Get-SystemCleanupOptions' }
|
||||||
|
throw "Unexpected URL in shim probe: $URL"
|
||||||
|
}
|
||||||
|
return $client
|
||||||
|
}
|
||||||
|
[string]$CleanupReportOnly='false'
|
||||||
|
[string]$CleanupSystemTemp='false'
|
||||||
|
[string]$CleanupTempDays='14'
|
||||||
|
foreach ($selectionName in @($expectedPresets.Keys) + @('Thumbnail Cache')) {
|
||||||
|
[string]$CleanupDiskCleanupItems=$selectionName
|
||||||
|
$output=@(. ([scriptblock]::Create($shim.Extent.Text)))
|
||||||
|
$selected=@($output | Where-Object { $_ -is [hashtable] })
|
||||||
|
Assert-Cleanup ($selected.Count -eq 1) 'Shim did not return the inert workload result.'
|
||||||
|
$injectedOptions=$selected[0]
|
||||||
|
Assert-Cleanup (-not $injectedOptions.ReportOnly -and -not $injectedOptions.SystemTemp -and $injectedOptions.TempDays -eq 14) 'Run-Script lost Syncro-injected strings.'
|
||||||
|
$expectedItems = if ($selectionName -eq 'Thumbnail Cache') { @('Thumbnail Cache') } else { @($expectedPresets[$selectionName]) }
|
||||||
|
Assert-Cleanup (($injectedOptions.DiskCleanupItems -join '|') -ceq ($expectedItems -join '|')) "Run-Script lost the injected selection: $selectionName"
|
||||||
|
Assert-Cleanup ($injectedOptions.DiagnosticDays -eq 30 -and $CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14' -and $CleanupDiskCleanupItems -ceq $selectionName) 'Absent defaults or original caller variables changed.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# All server/DC gates, including when enabled, and unknown OS failure.
|
||||||
|
$blocked = @('ShadowCopies','DisableHibernation','CompactSearch','DownloadedExecutables','DuplicateDownloads','OutlookBackups','ITunesBackups','DiskCleanup')
|
||||||
|
& {
|
||||||
|
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=$script:productType; Caption='Fixture OS'} } }
|
||||||
|
foreach ($script:productType in @(1,2,3)) {
|
||||||
|
$os = Get-SystemCleanupOS
|
||||||
|
Assert-Cleanup ($os.IsServer -eq ($script:productType -ne 1)) 'ProductType classification failed.'
|
||||||
|
$c = New-CleanupContext -Server $os.IsServer
|
||||||
|
foreach ($name in $blocked) {
|
||||||
|
if ($name -ne 'DiskCleanup') { $c.Options[$name]=$true }
|
||||||
|
$script:ran=$false
|
||||||
|
Invoke-SystemCleanupCategory $c $name { $script:ran=$true }
|
||||||
|
Assert-Cleanup ($script:ran -eq (-not $os.IsServer)) "Incorrect server gate for $name / $script:productType"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($script:productType in @(0,4,$null)) { Assert-CleanupThrows { Get-SystemCleanupOS } 'Cannot identify OS' }
|
||||||
|
function Get-CimInstance { throw 'Synthetic CIM failure' }
|
||||||
|
Assert-CleanupThrows { Get-SystemCleanupOS } 'Synthetic CIM failure'
|
||||||
|
}
|
||||||
|
$serverContext = New-CleanupContext -Server $true
|
||||||
|
Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $serverContext } 'blocked on server'
|
||||||
|
Assert-CleanupThrows { Invoke-SystemCleanupShadows $serverContext } 'blocked on server'
|
||||||
|
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $serverContext } 'blocked on server'
|
||||||
|
$script:serverAssessmentRan=$false
|
||||||
|
Invoke-SystemCleanupCategory $serverContext 'ShadowCopies' { $script:serverAssessmentRan=$true }
|
||||||
|
Assert-Cleanup (-not $script:serverAssessmentRan -and -not $serverContext.Stats.ShadowCopies.Enabled -and $serverContext.Stats.ShadowCopies.Status -eq 'Blocked on server' -and $null -eq $serverContext.Stats.ShadowCopies.CandidateBytes) 'A default-disabled server operation must be listed without assessment.'
|
||||||
|
& {
|
||||||
|
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=3; Caption='Fixture Server'} } }
|
||||||
|
function Invoke-SystemCleanupDiskCleanup { throw 'SERVER GUARD BYPASSED' }
|
||||||
|
function Invoke-SystemCleanupShadows { throw 'SERVER GUARD BYPASSED' }
|
||||||
|
function Invoke-SystemCleanupSearchCompaction { throw 'SERVER GUARD BYPASSED' }
|
||||||
|
function Invoke-SystemCleanupProcess { throw 'SERVER GUARD BYPASSED' }
|
||||||
|
# Substitute inert actions so the expanded report cannot inspect host paths.
|
||||||
|
$dispatcher=${function:Invoke-SystemCleanupCategory}
|
||||||
|
$script:assessed=@()
|
||||||
|
function Invoke-SystemCleanupCategory {
|
||||||
|
param($Context,$Name,$Action)
|
||||||
|
& $dispatcher $Context $Name { $script:assessed += $Name }
|
||||||
|
}
|
||||||
|
$o=Get-SystemCleanupOptions
|
||||||
|
foreach ($key in @($o.Keys)) { if ($o[$key] -is [bool]) { $o[$key]=$false } }
|
||||||
|
$o.ReportOnly=$true
|
||||||
|
foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } }
|
||||||
|
$result = @(Invoke-SystemCleanup $o)
|
||||||
|
Assert-Cleanup ($result.Count -eq 23 -and @($result | Where-Object Status -eq 'Blocked on server').Count -eq $blocked.Count) 'Server report must list every blocked category.'
|
||||||
|
Assert-Cleanup (@($script:assessed | Where-Object { $_ -in $blocked }).Count -eq 0) 'Server report must not assess blocked categories.'
|
||||||
|
}
|
||||||
|
|
||||||
|
# None is disabled in reports and apply; every nonempty preset remains blocked
|
||||||
|
# on both server types. No host inventories, registry operations or native calls.
|
||||||
|
foreach ($server in @($false, $true)) {
|
||||||
|
foreach ($reportOnly in @($false, $true)) {
|
||||||
|
foreach ($presetName in $expectedPresets.Keys) {
|
||||||
|
& {
|
||||||
|
$CleanupDiskCleanupItems = $presetName
|
||||||
|
$c = New-CleanupContext -Server $server -ReportOnly $reportOnly
|
||||||
|
$script:ran = $false
|
||||||
|
Invoke-SystemCleanupCategory $c 'DiskCleanup' { $script:ran = $true }
|
||||||
|
$shouldRun = -not $server -and ($reportOnly -or $presetName -ne 'None')
|
||||||
|
Assert-Cleanup ($script:ran -eq $shouldRun) "Incorrect Disk Cleanup dispatch: $presetName / server=$server / report=$reportOnly"
|
||||||
|
if ($reportOnly) {
|
||||||
|
Assert-Cleanup ($c.Stats.DiskCleanup.Enabled -eq ($presetName -ne 'None')) 'Disk Cleanup enablement must follow its selection.'
|
||||||
|
Assert-Cleanup ($c.Stats.DiskCleanup.Setting -ceq "CleanupDiskCleanupItems=$presetName") 'Report must identify the real operator setting.'
|
||||||
|
if ($server) { Assert-Cleanup ($c.Stats.DiskCleanup.Status -eq 'Blocked on server') 'Presets must not bypass the server block.' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
& {
|
||||||
|
$CleanupDiskCleanupItems = 'None'
|
||||||
|
$c = New-CleanupContext
|
||||||
|
function Get-ChildItem { throw 'None must not access the registry.' }
|
||||||
|
function Test-SystemCleanupAppRunning { throw 'None must not probe native cleanup.' }
|
||||||
|
function Invoke-SystemCleanupProcess { throw 'None must not launch cleanmgr.' }
|
||||||
|
$script:messages = @(); $script:details = @()
|
||||||
|
Invoke-SystemCleanupCategory $c 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $c }
|
||||||
|
Write-SystemCleanupReport $c
|
||||||
|
$report = $script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($report -match '(?s)DISABLED -.*DiskCleanup\s+-\s+-\s+.*None \(0 handlers\); will not run') 'None must appear in the disabled report section with a clear explanation.'
|
||||||
|
Assert-Cleanup (($script:details -join "`n") -match 'items not selected.*Previous Installations' -and $report -notmatch 'Previous Installations|CleanupDiskCleanup=') 'Unselected handler inventories belong in verbose diagnostics, not the compact report.'
|
||||||
|
$c.Options.ReportOnly = $false
|
||||||
|
Invoke-SystemCleanupDiskCleanup $c
|
||||||
|
Assert-Cleanup ($c.Errors -eq 0) 'None must not attempt native cleanup, even through the helper directly.'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Report diagnostics remain independent of enablement and never inflate savings.
|
||||||
|
& {
|
||||||
|
$script:fileReads=0; $script:storageReads=0; $script:diagnosticProcesses=0
|
||||||
|
function Start-Process { $script:diagnosticProcesses++; throw 'Report diagnostics must not launch native programs.' }
|
||||||
|
$script:hiberState='present'; $script:storageState='present'
|
||||||
|
$sourceId='\\?\Volume{11111111-1111-1111-1111-111111111111}\'
|
||||||
|
$otherId='\\?\Volume{22222222-2222-2222-2222-222222222222}\'
|
||||||
|
$script:storageTarget=$sourceId
|
||||||
|
function Get-Item {
|
||||||
|
param($LiteralPath)
|
||||||
|
$script:fileReads++
|
||||||
|
if ($script:hiberState -eq 'missing') { throw [Management.Automation.ItemNotFoundException]::new('fixture absent') }
|
||||||
|
if ($script:hiberState -eq 'denied') { throw [UnauthorizedAccessException]::new('fixture denied') }
|
||||||
|
[pscustomobject]@{Length=4GB; PSIsContainer=$false; Attributes=[IO.FileAttributes]::Hidden}
|
||||||
|
}
|
||||||
|
function Get-CimInstance {
|
||||||
|
param($ClassName)
|
||||||
|
$script:storageReads++
|
||||||
|
if ($script:storageState -eq 'denied') { throw 'Synthetic CIM access failure' }
|
||||||
|
if ($ClassName -eq 'Win32_Volume') {
|
||||||
|
[pscustomobject]@{DeviceID=$sourceId; DriveLetter=$env:SystemDrive}
|
||||||
|
[pscustomobject]@{DeviceID=$otherId; DriveLetter='Z:'}
|
||||||
|
} elseif ($ClassName -eq 'Win32_ShadowStorage' -and $script:storageState -ne 'empty') {
|
||||||
|
# Source as escaped WMI path; destination as embedded CIM-style object.
|
||||||
|
[pscustomobject]@{Volume='Win32_Volume.DeviceID="\\\\?\\Volume{11111111-1111-1111-1111-111111111111}\\"'; DiffVolume=[pscustomobject]@{DeviceID=$script:storageTarget}; UsedSpace=$(if ($script:storageState -eq 'invalid') { $null } else { 2GB }); AllocatedSpace=3GB}
|
||||||
|
[pscustomobject]@{Volume=[pscustomobject]@{DeviceID=$otherId}; DiffVolume=[pscustomobject]@{DeviceID=$otherId}; UsedSpace=99GB; AllocatedSpace=100GB}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$c=New-CleanupContext
|
||||||
|
foreach ($name in @('DisableHibernation','ShadowCopies','ComponentStore')) {
|
||||||
|
$c.Options[$name]=$false
|
||||||
|
Invoke-SystemCleanupCategory $c $name {}
|
||||||
|
}
|
||||||
|
$c.Diagnostics=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($c.Stats.DisableHibernation.UsageBytes -eq 4GB -and $c.Stats.ShadowCopies.UsageBytes -eq 2GB -and $c.Diagnostics.ComponentStore -match 'not analyzed;.*superseded updates.*substantial.*little/none') 'Disabled options must still receive usage measurements and an honest note about potential component-store savings.'
|
||||||
|
Assert-Cleanup ($c.Stats.ShadowCopies.UsageNote.EndsWith("stored on $env:SystemDrive") -and ($script:details -join "`n") -match '3,072.00 MiB allocated') 'VSS must select the system volume, label its storage location and leave allocation details in verbose output.'
|
||||||
|
$totals=Get-SystemCleanupReportTotals $c
|
||||||
|
Assert-Cleanup ($totals.EnabledBytes -eq 0 -and $totals.AdditionalDisabledBytes -eq 0 -and -not $c.Options.ShadowCopies -and $c.Errors -eq 0) 'Diagnostic usage is not reclaimable savings and must not enable cleanup.'
|
||||||
|
$script:messages=@()
|
||||||
|
Write-SystemCleanupReport $c
|
||||||
|
$report=$script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($report -notmatch '\bHibernation:|ShadowStorage:' -and [regex]::Matches($report,'(?m)^ ComponentStore:').Count -eq 1) 'Hibernation and VSS must not produce separate diagnostic lines.'
|
||||||
|
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+4,096.00\s+file size; excluded from totals' -and $report -match 'ShadowCopies\s+-\s+2,048.00\s+VSS used; excluded from totals; newest retained') 'Measured usage must appear in the category MiB column with its meaning and exclusion from totals.'
|
||||||
|
Assert-Cleanup ($report -notmatch '(DisableHibernation|ShadowCopies).*not estimated|GiB|MiB allocated') 'Measured rows must not say not estimated or repeat allocation diagnostics.'
|
||||||
|
$c.Options.ComponentStore=$true
|
||||||
|
$d=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($script:diagnosticProcesses -eq 0 -and $d.ComponentStore -eq $c.Diagnostics.ComponentStore) 'Enabling component cleanup must not launch analysis or fabricate a measured recommendation in report mode.'
|
||||||
|
$script:storageTarget=$otherId
|
||||||
|
$null=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($c.Stats.ShadowCopies.UsageBytes -eq 2GB -and $c.Stats.ShadowCopies.UsageNote -match 'stored on Z:') 'Shadow storage on another drive must not be attributed to the system drive.'
|
||||||
|
$script:storageState='empty'; $script:hiberState='missing'
|
||||||
|
$d=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($c.Stats.DisableHibernation.UsageBytes -eq 0 -and $c.Stats.ShadowCopies.UsageBytes -eq 0) 'Absent hibernation or a missing shadow-storage association must measure zero bytes.'
|
||||||
|
$script:messages=@(); Write-SystemCleanupReport $c
|
||||||
|
$report=$script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+0.00\s' -and $report -match 'ShadowCopies\s+-\s+0.00\s' -and $report -notmatch 'hiberfil.sys not present|no shadow-storage association|\bHibernation:|ShadowStorage:') 'Absent usage must appear as zero MiB in the two rows without separate absence messages.'
|
||||||
|
$script:storageState='invalid'
|
||||||
|
$null=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($null -eq $c.Stats.ShadowCopies.UsageBytes -and $c.Stats.ShadowCopies.UsageNote -match 'unavailable') 'Missing VSS measurements must not become zero.'
|
||||||
|
$script:storageState='denied'; $script:hiberState='denied'
|
||||||
|
$d=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($null -eq $c.Stats.DisableHibernation.UsageBytes -and $null -eq $c.Stats.ShadowCopies.UsageBytes -and $c.Stats.DisableHibernation.UsageNote -match 'unavailable' -and $c.Stats.ShadowCopies.UsageNote -match 'unavailable' -and $d.ComponentStore -match 'not analyzed' -and $c.Errors -eq 0) 'Diagnostic failures must clear old measurements, preserve the component note and not fail reporting.'
|
||||||
|
$script:messages=@(); Write-SystemCleanupReport $c
|
||||||
|
$report=$script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+-\s+unavailable' -and $report -match 'ShadowCopies\s+-\s+-\s+unavailable') 'Failed inspections must display unknown size rather than zero MiB.'
|
||||||
|
$script:fileReads=0; $script:storageReads=0
|
||||||
|
$c=New-CleanupContext -Server $true
|
||||||
|
foreach ($name in @('DisableHibernation','ShadowCopies')) { Invoke-SystemCleanupCategory $c $name {} }
|
||||||
|
$d=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0 -and $null -eq $c.Stats.DisableHibernation.UsageBytes -and $null -eq $c.Stats.ShadowCopies.UsageBytes -and $d.Count -eq 1 -and $d.ComponentStore -match 'not analyzed') 'Server reports must block hibernation/VSS assessment and only note potential component-store savings.'
|
||||||
|
$script:messages=@(); Write-SystemCleanupReport $c
|
||||||
|
$report=$script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+-\s+not assessed' -and $report -match 'ShadowCopies\s+-\s+-\s+not assessed') 'Server-blocked rows must remain unassessed rather than showing zero usage.'
|
||||||
|
$c.Options.ReportOnly=$false
|
||||||
|
$d=Get-SystemCleanupDiagnostics $c
|
||||||
|
Assert-Cleanup ($d.Count -eq 0 -and $script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0) 'Apply mode must not run report diagnostics.'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Abandoned Office payloads: report/apply, disabled options, server support,
|
||||||
|
# identity, retention, process/lock/link protection, and durable helper survival.
|
||||||
|
& {
|
||||||
|
$officeAst=Read-CleanupAst 'Install-MicrosoftOffice365.ps1'
|
||||||
|
foreach ($definition in $officeAst.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -in @('Get-OfficeDeploymentDefinitions','Get-OfficeStagingNames')},$false)) {
|
||||||
|
. ([scriptblock]::Create($definition.Extent.Text))
|
||||||
|
}
|
||||||
|
$names=@(Get-OfficeStagingNames)
|
||||||
|
$script:officeProcesses=@(); $script:officeInventoryFails=$false
|
||||||
|
function Get-CimInstance { if ($script:officeInventoryFails) { throw 'Synthetic process inventory failure' }; $script:officeProcesses }
|
||||||
|
function New-StageFixture {
|
||||||
|
param($Parent,$Id)
|
||||||
|
$relative=$Parent+'\'+($Id*32)
|
||||||
|
$null=New-CleanupFixture ($relative+'\options.json') '{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}'
|
||||||
|
foreach ($name in $names) {
|
||||||
|
$leaf=if ($name -in @('ODT','GetHelp')) { $name+'\payload.dat' } else { $name }
|
||||||
|
$null=New-CleanupFixture ($relative+'\'+$leaf)
|
||||||
|
}
|
||||||
|
foreach ($name in @('Office-UserCleanup.ps1','user-cleanup.lock','install.xml','office-install.stdout.log','unknown.exe')) { $null=New-CleanupFixture ($relative+'\'+$name) }
|
||||||
|
$folder=Join-Path $testRoot $relative
|
||||||
|
foreach ($dir in @(Get-ChildItem -LiteralPath $folder -Recurse -Directory)+@(Get-Item -LiteralPath $folder)) { [IO.Directory]::SetLastWriteTimeUtc($dir.FullName,[datetime]::UtcNow.AddDays(-60)) }
|
||||||
|
return $folder
|
||||||
|
}
|
||||||
|
function Test-StageCleanup {
|
||||||
|
param([bool]$ReportOnly=$true,[bool]$Enabled=$true,[bool]$Server=$false)
|
||||||
|
$c=New-CleanupContext -ReportOnly $ReportOnly -Server $Server; $c.Options.OfficeStaging=$Enabled
|
||||||
|
Invoke-SystemCleanupCategory $c 'OfficeStaging' { Clear-SystemCleanupOfficeStaging $c $stageRoots ([datetime]::UtcNow.AddDays(-7)) }
|
||||||
|
return $c
|
||||||
|
}
|
||||||
|
$folder=New-StageFixture 'office-fixture\Windows\SystemTemp\EmberkomOfficeDeployment' 'a'
|
||||||
|
$legacy=New-StageFixture 'office-fixture\ProgramData\EmberkomOfficeDeployment' 'b'
|
||||||
|
$stageRoots=@((Split-Path -Parent $folder),(Split-Path -Parent $legacy))
|
||||||
|
Assert-Cleanup ((Get-SystemCleanupOfficeStagingRoots @()) -contains (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment')) 'SystemTemp must be a supported Office staging root.'
|
||||||
|
$c=Test-StageCleanup -Enabled $false
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq (2*$names.Count) -and !$c.Stats.OfficeStaging.Enabled -and (Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat'))) 'Disabled report must measure every installer artifact without deleting it.'
|
||||||
|
$c=Test-StageCleanup -Server $true
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq (2*$names.Count) -and $c.Errors -eq 0) 'Owned staging cleanup must support server OSes.'
|
||||||
|
$c=New-CleanupContext
|
||||||
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' (Split-Path -Parent $stageRoots[0]) ([datetime]::UtcNow.AddDays(-7)) -Recurse }
|
||||||
|
Assert-Cleanup ($c.Stats.SystemTemp.CandidateFiles -eq 0) 'Generic temp traversal must exclude Office staging entirely.'
|
||||||
|
$c=Test-StageCleanup -ReportOnly $false -Enabled $false
|
||||||
|
Assert-Cleanup ((Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat')) -and !$c.Stats.Count) 'Disabled apply must preserve staged media.'
|
||||||
|
$script:officeProcesses=@([pscustomobject]@{Name='setup.exe'})
|
||||||
|
$c=Test-StageCleanup
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.Status -eq 'Skipped' -and $c.Stats.OfficeStaging.EstimateStatus -eq 'Not assessed') 'An installer without a workspace path must block staging cleanup.'
|
||||||
|
$script:officeProcesses=@([pscustomobject]@{Name='worker.exe'; ExecutablePath=(Join-Path $folder 'ODT\worker.exe')})
|
||||||
|
$c=Test-StageCleanup
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count -and $c.Stats.OfficeStaging.Notes -match 'retained') 'A running process must retain its workspace while allowing other abandoned media.'
|
||||||
|
$script:officeProcesses=@(); $script:officeInventoryFails=$true
|
||||||
|
$c=Test-StageCleanup -ReportOnly $false
|
||||||
|
Assert-Cleanup ($c.Errors -eq 1 -and (Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat'))) 'Failed process inventory must prevent deletion.'
|
||||||
|
$script:officeInventoryFails=$false
|
||||||
|
& {
|
||||||
|
function New-SystemCleanupOfficeMutex {
|
||||||
|
$m=[pscustomobject]@{}
|
||||||
|
$m | Add-Member ScriptMethod WaitOne { param($Timeout) return $false }
|
||||||
|
$m | Add-Member ScriptMethod Dispose { }
|
||||||
|
return $m
|
||||||
|
}
|
||||||
|
$c=Test-StageCleanup -ReportOnly $false
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.Status -eq 'Skipped' -and (Test-Path -LiteralPath (Join-Path $folder 'odt.exe'))) 'Active deployment mutex must block cleanup.'
|
||||||
|
}
|
||||||
|
$payload=Join-Path $folder 'ODT\payload.dat'
|
||||||
|
$handle=[IO.File]::Open($payload,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None)
|
||||||
|
try { $c=Test-StageCleanup; Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'Locked media must not count as reclaimable.' } finally { $handle.Dispose() }
|
||||||
|
[IO.File]::SetLastWriteTimeUtc($payload,[datetime]::UtcNow)
|
||||||
|
$c=Test-StageCleanup
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'A fresh payload must retain the whole workspace media set.'
|
||||||
|
[IO.File]::SetLastWriteTimeUtc($payload,[datetime]::UtcNow.AddDays(-60))
|
||||||
|
$outside=New-CleanupFixture 'office-outside\keep.dat'
|
||||||
|
$junction=Join-Path $folder 'ODT\linked'
|
||||||
|
$null=New-Item -ItemType Junction -Path $junction -Target (Split-Path -Parent $outside)
|
||||||
|
try {
|
||||||
|
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $junction),[datetime]::UtcNow.AddDays(-60))
|
||||||
|
$c=Test-StageCleanup
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count -and (Test-Path -LiteralPath $outside)) 'Linked artifacts must retain the whole media set without traversing the link.'
|
||||||
|
} finally { [IO.Directory]::Delete($junction,$false); [IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $junction),[datetime]::UtcNow.AddDays(-60)) }
|
||||||
|
$marker=Join-Path $folder 'options.json'; [IO.File]::WriteAllText($marker,'{}'); [IO.File]::SetLastWriteTimeUtc($marker,[datetime]::UtcNow.AddDays(-60))
|
||||||
|
$c=Test-StageCleanup
|
||||||
|
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'Unrecognized folders must not be deleted based only on their names.'
|
||||||
|
[IO.File]::WriteAllText($marker,'{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}'); [IO.File]::SetLastWriteTimeUtc($marker,[datetime]::UtcNow.AddDays(-60))
|
||||||
|
$c=Test-StageCleanup -ReportOnly $false
|
||||||
|
Assert-Cleanup ($c.Errors -eq 0 -and $c.Stats.OfficeStaging.RemovedFiles -eq (2*$names.Count) -and !(Test-Path -LiteralPath (Join-Path $folder 'ODT')) -and !(Test-Path -LiteralPath (Join-Path $legacy 'ODT'))) 'Apply must remove known aged media from SystemTemp and legacy ProgramData.'
|
||||||
|
foreach ($workspace in @($folder,$legacy)) {
|
||||||
|
foreach ($name in @('options.json','Office-UserCleanup.ps1','user-cleanup.lock','install.xml','office-install.stdout.log','unknown.exe')) {
|
||||||
|
Assert-Cleanup (Test-Path -LiteralPath (Join-Path $workspace $name)) "Office staging cleanup removed protected data: $name"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# File ages, literal brackets, nested fresh files, no changes in preview.
|
||||||
|
$root=Join-Path $testRoot 'temps'
|
||||||
|
$old=New-CleanupFixture 'temps\old[1].tmp'
|
||||||
|
$fresh=New-CleanupFixture 'temps\parent\fresh.tmp' 'fresh' 0
|
||||||
|
$nestedOld=New-CleanupFixture 'temps\parent\old.tmp'
|
||||||
|
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $fresh), [datetime]::UtcNow.AddDays(-90))
|
||||||
|
$cutoff=[datetime]::UtcNow.AddDays(-7)
|
||||||
|
$c=New-CleanupContext
|
||||||
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
||||||
|
Assert-Cleanup ($c.Stats.SystemTemp.CandidateFiles -eq 2 -and $c.Stats.SystemTemp.RemovedFiles -eq 0) 'Preview counts incorrect.'
|
||||||
|
Assert-Cleanup ((Test-Path -LiteralPath $old) -and (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Preview changed files.'
|
||||||
|
$c=New-CleanupContext -ReportOnly $false
|
||||||
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
||||||
|
Assert-Cleanup (-not (Test-Path -LiteralPath $old) -and -not (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Age/leaf deletion failure.'
|
||||||
|
Assert-Cleanup ($c.Stats.SystemTemp.RemovedFiles -eq 2) 'Removed files were not counted.'
|
||||||
|
|
||||||
|
# Disabled categories get independent report estimates, even when files overlap an
|
||||||
|
# enabled category later in the run. Apply mode still ignores disabled categories.
|
||||||
|
$potentialRoot=Join-Path $testRoot 'potential'
|
||||||
|
$potentialOriginal=New-CleanupFixture 'potential\install.exe' 'abc'
|
||||||
|
$potentialDuplicate=New-CleanupFixture 'potential\install (1).exe' 'abc'
|
||||||
|
$potentialRecent=New-CleanupFixture 'potential\recent.exe' 'fresh' 0
|
||||||
|
$c=New-CleanupContext
|
||||||
|
$c.Options.DownloadedExecutables=$false; $c.Options.DuplicateDownloads=$true
|
||||||
|
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
|
||||||
|
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c $potentialRoot $cutoff }
|
||||||
|
Assert-Cleanup (-not $c.Stats.DownloadedExecutables.Enabled -and $c.Stats.DownloadedExecutables.CandidateFiles -eq 2 -and $c.Stats.DownloadedExecutables.CandidateBytes -eq 6) 'Disabled download estimate is missing or includes recent files.'
|
||||||
|
Assert-Cleanup ($c.Stats.DuplicateDownloads.Enabled -and $c.Stats.DuplicateDownloads.CandidateFiles -eq 1 -and $c.Stats.DuplicateDownloads.CandidateBytes -eq 3) 'Disabled preview consumed an enabled category candidate.'
|
||||||
|
Assert-Cleanup (-not $c.Options.DownloadedExecutables -and (Test-Path -LiteralPath $potentialDuplicate)) 'Preview enabled a disabled option or deleted data.'
|
||||||
|
$totals=Get-SystemCleanupReportTotals $c
|
||||||
|
Assert-Cleanup ($totals.EnabledBytes -eq 3 -and $totals.EnabledFiles -eq 1 -and $totals.AdditionalDisabledBytes -eq 3 -and $totals.AdditionalDisabledFiles -eq 1) 'Overlapping report totals double-counted a file.'
|
||||||
|
$script:messages=@()
|
||||||
|
Write-SystemCleanupReport $c
|
||||||
|
$report=$script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($report.IndexOf('ENABLED -') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DuplicateDownloads') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DownloadedExecutables') -gt $report.IndexOf('DISABLED -')) 'Enabled and disabled report groups are unclear or misplaced.'
|
||||||
|
Assert-Cleanup ($report.IndexOf('Known savings:') -lt $report.IndexOf('ENABLED -') -and $report -match 'Additional DISABLED' -and $report -match '<0.01') 'Unique totals must appear first and small nonzero candidates must remain visible.'
|
||||||
|
$c=New-CleanupContext -ReportOnly $false
|
||||||
|
$script:disabledRan=$false
|
||||||
|
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { $script:disabledRan=$true; Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
|
||||||
|
Assert-Cleanup (-not $script:disabledRan -and (Test-Path -LiteralPath $potentialOriginal) -and (Test-Path -LiteralPath $potentialDuplicate) -and (Test-Path -LiteralPath $potentialRecent)) 'Apply mode ran a disabled category.'
|
||||||
|
|
||||||
|
$outside=New-CleanupFixture 'outside\preserved.tmp'
|
||||||
|
Assert-Cleanup (-not (Test-SystemCleanupPath $outside $root)) 'Containment check accepted an outside file.'
|
||||||
|
Assert-Cleanup (-not (Test-SystemCleanupPath 'C:\Windows' 'C:\')) 'Drive-root cleanup must be rejected.'
|
||||||
|
$junction=Join-Path $root 'linked'
|
||||||
|
$null=New-Item -ItemType Junction -Path $junction -Target (Split-Path -Parent $outside)
|
||||||
|
try {
|
||||||
|
Assert-Cleanup (-not (Test-SystemCleanupPath (Join-Path $junction 'preserved.tmp') $root)) 'Linked ancestor was accepted.'
|
||||||
|
$c=New-CleanupContext -ReportOnly $false
|
||||||
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
||||||
|
Assert-Cleanup (Test-Path -LiteralPath $outside) 'Cleanup followed junction outside the target.'
|
||||||
|
} finally { [IO.Directory]::Delete($junction, $false) }
|
||||||
|
$locked=New-CleanupFixture 'temps\locked.tmp'
|
||||||
|
$lock=[IO.File]::Open($locked, 'Open', 'ReadWrite', 'None')
|
||||||
|
try {
|
||||||
|
$c=New-CleanupContext -ReportOnly $false
|
||||||
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
||||||
|
Assert-Cleanup ((Test-Path -LiteralPath $locked) -and $c.Stats.SystemTemp.FailedFiles -eq 1) 'Locked files must be retained and counted.'
|
||||||
|
} finally { $lock.Dispose() }
|
||||||
|
|
||||||
|
# Same length is not the same content, and extensions must match.
|
||||||
|
$null=New-CleanupFixture 'downloads\a.txt' 'abc'
|
||||||
|
$same=New-CleanupFixture 'downloads\a (1).txt' 'abc'
|
||||||
|
$different=New-CleanupFixture 'downloads\a (2).txt' 'xyz'
|
||||||
|
$extension=New-CleanupFixture 'downloads\a (1).csv' 'abc'
|
||||||
|
$recent=New-CleanupFixture 'downloads\a (3).txt' 'abc' 0
|
||||||
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.DuplicateDownloads=$true
|
||||||
|
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c (Join-Path $testRoot 'downloads') $cutoff }
|
||||||
|
Assert-Cleanup (-not (Test-Path -LiteralPath $same) -and (Test-Path -LiteralPath $different) -and (Test-Path -LiteralPath $extension) -and (Test-Path -LiteralPath $recent)) 'Duplicate matching/retention failure.'
|
||||||
|
|
||||||
|
# Entire backup retained when a nested file is recent; old complete unit removed.
|
||||||
|
$backupOld=New-CleanupFixture 'backups\phone\old.dat'
|
||||||
|
$backupFresh=New-CleanupFixture 'backups\phone\nested\new.dat' 'new' 0
|
||||||
|
$bundle=Split-Path -Parent $backupOld
|
||||||
|
[IO.Directory]::SetLastWriteTimeUtc($bundle, [datetime]::UtcNow.AddDays(-60))
|
||||||
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
|
||||||
|
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
|
||||||
|
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Recent backup was partially cleaned.'
|
||||||
|
[IO.File]::SetLastWriteTimeUtc($backupFresh,[datetime]::UtcNow.AddDays(-60))
|
||||||
|
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $backupFresh),[datetime]::UtcNow.AddDays(-60))
|
||||||
|
$backupLock=[IO.File]::Open($backupFresh,'Open','ReadWrite','None')
|
||||||
|
try {
|
||||||
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
|
||||||
|
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
|
||||||
|
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Locked backup was partially cleaned.'
|
||||||
|
} finally { $backupLock.Dispose() }
|
||||||
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
|
||||||
|
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
|
||||||
|
Assert-Cleanup (-not (Test-Path -LiteralPath $bundle)) 'Old backup unit was not completely removed.'
|
||||||
|
|
||||||
|
# $I metadata controls retention, NOT the payload's old modification time.
|
||||||
|
$recycle=Join-Path $testRoot 'recycle'
|
||||||
|
foreach ($case in @(@{Id='old'; Days=60; Version=2},@{Id='recent'; Days=0; Version=1},@{Id='unknown'; Days=60; Version=99})) {
|
||||||
|
$meta=New-CleanupFixture ('recycle\S-1-5-21-fixture\$I'+$case.Id) 'placeholder'
|
||||||
|
$null=New-CleanupFixture ('recycle\S-1-5-21-fixture\$R'+$case.Id) 'data'
|
||||||
|
$originalPath=[Text.Encoding]::Unicode.GetBytes("C:\fixture.txt`0")
|
||||||
|
$length=if ($case.Version -eq 1) {544} else {28+$originalPath.Length}
|
||||||
|
$bytes=New-Object byte[] $length
|
||||||
|
[BitConverter]::GetBytes([long]$case.Version).CopyTo($bytes,0)
|
||||||
|
[BitConverter]::GetBytes([long]4).CopyTo($bytes,8)
|
||||||
|
[BitConverter]::GetBytes([datetime]::UtcNow.AddDays(-$case.Days).ToFileTimeUtc()).CopyTo($bytes,16)
|
||||||
|
if ($case.Version -eq 1) { $originalPath.CopyTo($bytes,24) }
|
||||||
|
else {
|
||||||
|
[BitConverter]::GetBytes([uint32]($originalPath.Length/2)).CopyTo($bytes,24)
|
||||||
|
$originalPath.CopyTo($bytes,28)
|
||||||
|
}
|
||||||
|
[IO.File]::WriteAllBytes($meta,$bytes)
|
||||||
|
}
|
||||||
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.RecycleBin=$true
|
||||||
|
Invoke-SystemCleanupCategory $c 'RecycleBin' { Clear-SystemCleanupRecycleBin $c $recycle $cutoff }
|
||||||
|
Assert-Cleanup (-not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Rold')) -and -not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Iold'))) 'Old recycled pair not removed.'
|
||||||
|
foreach ($id in @('recent','unknown')) {
|
||||||
|
Assert-Cleanup ((Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$I'+$id))) -and (Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$R'+$id)))) "Unsafe recycle deletion: $id"
|
||||||
|
}
|
||||||
|
$truncated=New-CleanupFixture 'truncated-recycle-metadata' 'data'
|
||||||
|
[IO.File]::WriteAllBytes($truncated, [byte[]]@(2,0,0,0,0,0,0,0))
|
||||||
|
Assert-CleanupThrows { Get-SystemCleanupRecycleDate $truncated } 'Truncated'
|
||||||
|
|
||||||
|
# Native failure is observable; preview never starts a process.
|
||||||
|
& {
|
||||||
|
$script:starts=0
|
||||||
|
function Start-Process { param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru)
|
||||||
|
$script:starts++; Assert-Cleanup ($Wait -and $PassThru -and $WindowStyle -eq 'Hidden') 'Native operations must wait, capture exit status, and hide the window.'
|
||||||
|
[pscustomobject]@{ExitCode=5}
|
||||||
|
}
|
||||||
|
$c=New-CleanupContext
|
||||||
|
Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off'
|
||||||
|
Assert-Cleanup ($script:starts -eq 0) 'Report mode launched a native process.'
|
||||||
|
$c.Options.ReportOnly=$false
|
||||||
|
Assert-CleanupThrows { Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off' } 'exit code 5'
|
||||||
|
}
|
||||||
|
# cleanmgr only writes selected handlers in an unused slot; finally restores after failure.
|
||||||
|
& {
|
||||||
|
$script:events=@(); $script:nativeFailure=$false
|
||||||
|
function Test-SystemCleanupAppRunning { return $false }
|
||||||
|
function Get-ChildItem {
|
||||||
|
param($LiteralPath)
|
||||||
|
foreach ($name in @('Thumbnail Cache','Previous Installations')) {
|
||||||
|
$key=[pscustomobject]@{PSChildName=$name; PSPath=('fixture:\'+$name)}
|
||||||
|
$key | Add-Member ScriptMethod GetValueNames { @('StateFlags1000') }
|
||||||
|
$key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function New-ItemProperty { param($LiteralPath,$Name,$Value,$PropertyType) $script:events += "write:$LiteralPath/$Name=$Value" }
|
||||||
|
function Remove-ItemProperty { param($LiteralPath,$Name) $script:events += "remove:$LiteralPath/$Name" }
|
||||||
|
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:events += "run:$FileName $Arguments"; if ($script:nativeFailure) { throw 'Synthetic native failure' } }
|
||||||
|
$c=New-CleanupContext; $c.Options.DiskCleanupItems=@('Thumbnail Cache'); $c.Options.DiskCleanupPreset='Custom'
|
||||||
|
Invoke-SystemCleanupDiskCleanup $c
|
||||||
|
Assert-Cleanup ($script:events.Count -eq 0) 'Report mode wrote Disk Cleanup settings.'
|
||||||
|
$c.Options.ReportOnly=$false
|
||||||
|
foreach ($script:nativeFailure in @($false,$true)) {
|
||||||
|
$script:events=@()
|
||||||
|
if ($script:nativeFailure) { Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $c } 'Synthetic native failure' }
|
||||||
|
else { Invoke-SystemCleanupDiskCleanup $c }
|
||||||
|
Assert-Cleanup ($script:events.Count -eq 3 -and $script:events[0] -eq 'write:fixture:\Thumbnail Cache/StateFlags1001=2' -and $script:events[1] -eq 'run:cleanmgr.exe /sagerun:1001' -and $script:events[2] -eq 'remove:fixture:\Thumbnail Cache/StateFlags1001') 'Disk Cleanup settings selection/restoration failed.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Snapshot deletion is exact-ID based and retains the newest system-volume snapshot.
|
||||||
|
& {
|
||||||
|
$script:commands=@()
|
||||||
|
function Get-CimInstance {
|
||||||
|
param($ClassName)
|
||||||
|
if ($ClassName -eq 'Win32_Volume') { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='volume1'} }
|
||||||
|
else {
|
||||||
|
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
|
||||||
|
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'}
|
||||||
|
[pscustomobject]@{VolumeName='volume2'; InstallDate=[datetime]'2026-09-01'; ID='{33333333-3333-3333-3333-333333333333}'}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:commands += "$FileName $Arguments" }
|
||||||
|
Invoke-SystemCleanupShadows (New-CleanupContext)
|
||||||
|
Assert-Cleanup ($script:commands.Count -eq 1 -and $script:commands[0] -match '/Shadow=\{11111111-' -and $script:commands[0] -notmatch '/Oldest') 'Incorrect VSS target selection.'
|
||||||
|
}
|
||||||
|
# Search always restores running state after failure, never changes startup settings.
|
||||||
|
& {
|
||||||
|
$savedProgramData=$env:ProgramData
|
||||||
|
$null=New-CleanupFixture 'search\Microsoft\Search\Data\Applications\Windows\Windows.edb'
|
||||||
|
try {
|
||||||
|
$env:ProgramData=Join-Path $testRoot 'search'
|
||||||
|
$script:serviceEvents=@()
|
||||||
|
function Get-Service {
|
||||||
|
param($Name)
|
||||||
|
$s=[pscustomobject]@{Status=$script:originalServiceStatus}
|
||||||
|
$s | Add-Member ScriptMethod WaitForStatus { param($Status,$Timeout) $script:serviceEvents += 'wait' }
|
||||||
|
return $s
|
||||||
|
}
|
||||||
|
function Stop-Service { param($Name) $script:serviceEvents += 'stop' }
|
||||||
|
function Start-Service { param($Name) $script:serviceEvents += 'start' }
|
||||||
|
function Set-Service { throw 'Startup configuration must be preserved.' }
|
||||||
|
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:serviceEvents += 'compact'; throw 'Synthetic compaction failure' }
|
||||||
|
foreach ($script:originalServiceStatus in @('Running','Stopped')) {
|
||||||
|
$script:serviceEvents=@()
|
||||||
|
$c=New-CleanupContext -ReportOnly $false
|
||||||
|
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $c } 'Synthetic compaction failure'
|
||||||
|
$expected=if ($script:originalServiceStatus -eq 'Running') { 'stop,wait,compact,start' } else { 'compact' }
|
||||||
|
Assert-Cleanup (($script:serviceEvents -join ',') -eq $expected) 'Search service restoration failed.'
|
||||||
|
}
|
||||||
|
$script:serviceEvents=@()
|
||||||
|
Invoke-SystemCleanupSearchCompaction (New-CleanupContext)
|
||||||
|
Assert-Cleanup ($script:serviceEvents.Count -eq 0) 'Preview changed Search service state.'
|
||||||
|
} finally { $env:ProgramData=$savedProgramData }
|
||||||
|
}
|
||||||
|
# Entire entry point with mixed enablement in preview. All mutation APIs fail
|
||||||
|
# the test if called. Every environment path and inventory points at inert fixtures.
|
||||||
|
& {
|
||||||
|
$savedEnvironment=@{SystemRoot=$env:SystemRoot; SystemDrive=$env:SystemDrive; ProgramData=$env:ProgramData}
|
||||||
|
$previewRoot=Join-Path $testRoot 'preview'
|
||||||
|
$null=New-CleanupFixture 'preview\Windows\Temp\old.tmp'
|
||||||
|
$null=New-CleanupFixture 'preview\Windows\Temp\CbsPersist_fixture.log'
|
||||||
|
$null=New-CleanupFixture 'preview\Users\Alice\AppData\Local\Temp\old.tmp'
|
||||||
|
$null=New-CleanupFixture 'preview\Users\Alice\Downloads\install.exe'
|
||||||
|
$null=New-CleanupFixture 'preview\hiberfil.sys'
|
||||||
|
foreach ($exe in @('powercfg.exe','schtasks.exe','esentutl.exe','vssadmin.exe','cleanmgr.exe')) { $null=New-CleanupFixture ('preview\Windows\System32\'+$exe) 'inert, never executed' }
|
||||||
|
try {
|
||||||
|
$env:SystemRoot=Join-Path $previewRoot 'Windows'; $env:SystemDrive=$previewRoot
|
||||||
|
$env:ProgramData=Join-Path $previewRoot 'ProgramData'
|
||||||
|
function Get-CimInstance {
|
||||||
|
param($ClassName)
|
||||||
|
switch ($ClassName) {
|
||||||
|
Win32_OperatingSystem { [pscustomobject]@{ProductType=1; Caption='Fixture Client'} }
|
||||||
|
Win32_UserProfile { [pscustomobject]@{Special=$false; LocalPath=(Join-Path $previewRoot 'Users\Alice')} }
|
||||||
|
Win32_Volume { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='\\?\Volume{11111111-1111-1111-1111-111111111111}\'} }
|
||||||
|
Win32_ShadowCopy {
|
||||||
|
[pscustomobject]@{VolumeName='\\?\Volume{11111111-1111-1111-1111-111111111111}\'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
|
||||||
|
[pscustomobject]@{VolumeName='\\?\Volume{11111111-1111-1111-1111-111111111111}\'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function Test-SystemCleanupAppRunning { return $false }
|
||||||
|
function Get-SystemCleanupOfficeStagingRoots { return (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment') }
|
||||||
|
function Get-Service { [pscustomobject]@{Status='Stopped'} }
|
||||||
|
function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' }
|
||||||
|
function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' }
|
||||||
|
function Remove-ItemProperty { throw 'PREVIEW MUTATION: registry removal' }
|
||||||
|
function Start-Service { throw 'PREVIEW MUTATION: start service' }
|
||||||
|
function Stop-Service { throw 'PREVIEW MUTATION: stop service' }
|
||||||
|
function Delete-DeliveryOptimizationCache { throw 'PREVIEW MUTATION: delivery cache' }
|
||||||
|
function Start-Process { throw 'PREVIEW MUTATION: native program' }
|
||||||
|
$o=Get-SystemCleanupOptions
|
||||||
|
$script:messages=@(); $script:details=@()
|
||||||
|
$result=@(Invoke-SystemCleanup $o)
|
||||||
|
Assert-Cleanup ($result.Count -eq 23 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))."
|
||||||
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DownloadedExecutables' -and -not $_.Enabled -and $_.CandidateFiles -eq 1 }).Count -eq 1) 'Default-disabled downloads were not assessed by the entry point.'
|
||||||
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'ComponentStore' -and -not $_.Enabled -and $null -eq $_.CandidateBytes -and $_.EstimateStatus -eq 'Not estimated' }).Count -eq 1) 'Unknown native savings must not be reported as zero.'
|
||||||
|
Assert-Cleanup (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'Temp\old.tmp')) 'Full preview removed a fixture.'
|
||||||
|
$compactOutput = ($script:messages | ForEach-Object { '[SystemCleanup] ' + $_ }) -join "`r`n"
|
||||||
|
$script:compactReportBytes = [Text.Encoding]::UTF8.GetByteCount($compactOutput)
|
||||||
|
Assert-Cleanup ($script:compactReportBytes -lt 4096) "23-category preview exceeded the 4 KiB regression budget ($script:compactReportBytes bytes)."
|
||||||
|
foreach ($row in $result) {
|
||||||
|
Assert-Cleanup ([regex]::Matches($compactOutput, ('(?m)^\[SystemCleanup\] ' + [regex]::Escape($row.Category) + '\s')).Count -eq 1) "Compact report lost or repeated category $($row.Category)."
|
||||||
|
}
|
||||||
|
Assert-Cleanup ($compactOutput -notmatch 'Assessing |selected items:|items not selected|CandidateFiles\s*:' -and $compactOutput -match 'Standard \(7 handlers\)') 'Default output must show the preset without progress chatter, handler inventories, or object dumps.'
|
||||||
|
Assert-Cleanup (($script:details -join "`n") -match 'items not selected.*Previous Installations') 'Full handler details must remain available in verbose output.'
|
||||||
|
Assert-Cleanup ($compactOutput -match 'DisableHibernation\s+-\s+<0.01\s+file size' -and $compactOutput -match 'ShadowCopies\s+-\s+0.00\s+VSS used' -and $compactOutput -notmatch '\bHibernation:|ShadowStorage:' -and $compactOutput -match 'ComponentStore: not analyzed;.*superseded updates.*substantial.*little/none') 'Full entry-point report must show usage in category rows and retain the component note even with cleanup disabled.'
|
||||||
|
function Test-SystemCleanupAppRunning { return $true }
|
||||||
|
function Get-Command { return $null }
|
||||||
|
$o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None'
|
||||||
|
$script:messages=@()
|
||||||
|
$result=@(Invoke-SystemCleanup $o)
|
||||||
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'RevitJournals' -and $_.Status -eq 'Skipped' }).Count -eq 1) 'An active application should skip cleanup, not fail the whole run.'
|
||||||
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DeliveryOptimization' -and -not $_.Enabled -and $_.Status -eq 'Unavailable' -and $null -eq $_.CandidateBytes }).Count -eq 1) 'A missing optional feature must be reported as unavailable, not zero savings or a failed report.'
|
||||||
|
$compactOutput=$script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($compactOutput -match 'BrowserCache.*Partial; incomplete.*chrome.*msedge' -and $compactOutput -match 'RevitJournals.*Skipped.*Revit is running' -and $compactOutput -match 'DeliveryOptimization.*Unavailable.*not installed') 'Compacting output must preserve partial, skipped and unavailable reasons.'
|
||||||
|
} finally {
|
||||||
|
$env:SystemRoot=$savedEnvironment.SystemRoot; $env:SystemDrive=$savedEnvironment.SystemDrive; $env:ProgramData=$savedEnvironment.ProgramData
|
||||||
|
}
|
||||||
|
}
|
||||||
|
& {
|
||||||
|
$c=New-CleanupContext
|
||||||
|
$script:messages=@(); $script:details=@()
|
||||||
|
Invoke-SystemCleanupCategory $c 'CrashDumps' { throw ("Synthetic failure`r`n" + ('long diagnostic ' * 300)) }
|
||||||
|
Write-SystemCleanupReport $c
|
||||||
|
$report=$script:messages -join "`n"
|
||||||
|
Assert-Cleanup ($c.Errors -eq 1 -and $report -match 'CrashDumps.*Failed; incomplete.*Synthetic failure.*see verbose' -and $report.Length -lt 1600) 'A long multiline error must retain its failure status without flooding the summary.'
|
||||||
|
Assert-Cleanup (($script:details -join "`n").Contains(('long diagnostic ' * 300))) 'Compacted errors must remain complete in verbose diagnostics.'
|
||||||
|
}
|
||||||
|
Write-Host "Compact 23-category preview: $script:compactReportBytes UTF-8 bytes."
|
||||||
|
Write-Host "PASS: $script:assertions offline cleanup assertions ($($PSVersionTable.PSVersion))."
|
||||||
|
} finally {
|
||||||
|
# Only this test's generated directory; links are removed non-recursively above.
|
||||||
|
$resolved=[IO.Path]::GetFullPath($testRoot)
|
||||||
|
$expectedParent=[IO.Path]::GetFullPath($env:TEMP).TrimEnd('\')+'\'
|
||||||
|
if (-not $resolved.StartsWith($expectedParent,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notmatch '^SystemCleanupTests-[0-9a-f]{32}$') { throw 'Unsafe fixture cleanup path.' }
|
||||||
|
if (Test-Path -LiteralPath $resolved) { Remove-Item -LiteralPath $resolved -Recurse -Force }
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
#Requires -Version 4.0
|
||||||
|
# Run with Windows PowerShell. All downloads, plan checks and installs are fixtures.
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$repo = Split-Path -Parent $PSScriptRoot
|
||||||
|
$fixtureDir = Join-Path ([IO.Path]::GetTempPath()) ('CloudBackupTest-' + [guid]::NewGuid())
|
||||||
|
$null = New-Item -ItemType Directory -Path $fixtureDir
|
||||||
|
|
||||||
|
function Read-TestAst($Path) {
|
||||||
|
$parseErrors = $null
|
||||||
|
$tree = [Management.Automation.Language.Parser]::ParseFile($Path, [ref]$null, [ref]$parseErrors)
|
||||||
|
if ($parseErrors) { throw ($parseErrors | Out-String) }
|
||||||
|
return $tree
|
||||||
|
}
|
||||||
|
function Find-TestFunction($Tree, $Name) {
|
||||||
|
$fn = $Tree.Find({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $Name}, $false)
|
||||||
|
if (!$fn) { throw "Missing $Name" }
|
||||||
|
return $fn
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$core = Read-TestAst (Join-Path $repo 'Update-EmberkomCloudBackup.ps1')
|
||||||
|
$shim = Read-TestAst (Join-Path $repo 'rmm/Update-EmberkomCloudBackup.ps1')
|
||||||
|
foreach ($entry in @($shim,$core)) {
|
||||||
|
if ($entry.ScriptRequirements.RequiredPSVersion -ne [version]'4.0') { throw "Expected #Requires -Version 4.0 in $($entry.Extent.File)" }
|
||||||
|
}
|
||||||
|
$windowFn = Find-TestFunction $core 'Test-CloudBackupUpdateWindow'
|
||||||
|
. ([scriptblock]::Create($windowFn.Extent.Text))
|
||||||
|
foreach ($case in @(
|
||||||
|
@('23:30-00:30','23:30',$true), @('23:30-00:30','00:29',$true),
|
||||||
|
@('23:30-00:30','00:30',$false), @('12:00-13:00','11:59',$false),
|
||||||
|
@('12:00-13:00','12:00',$true), @('12:00-13:00','13:00',$false), @('','02:00',$true)
|
||||||
|
)) {
|
||||||
|
if ((Test-CloudBackupUpdateWindow $case[0] ([datetime]::ParseExact($case[1],'HH:mm',$null))) -ne $case[2]) {
|
||||||
|
throw "Window boundary failed for $($case[0]) at $($case[1])"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Substitute only discovery of the installed product in the downloaded core.
|
||||||
|
$discovery = Find-TestFunction $core 'Get-CloudBackupInstallation'
|
||||||
|
$coreSource = $core.Extent.Text.Replace($discovery.Extent.Text, 'function Get-CloudBackupInstallation { Get-FixtureInstallation }')
|
||||||
|
$toolsAst = Read-TestAst (Join-Path $repo 'Tools.ps1')
|
||||||
|
$shimTools = (@('Run-Script','Get-EmberkomCloudBackupReleases','Get-EmberkomCloudBackupRelease','Save-EmberkomCloudBackupInstaller') |
|
||||||
|
ForEach-Object { (Find-TestFunction $toolsAst $_).Extent.Text }) -join [Environment]::NewLine
|
||||||
|
$fixtureBytes = [byte[]](1,2,3)
|
||||||
|
$sha = [Security.Cryptography.SHA256]::Create()
|
||||||
|
try { $hash = [BitConverter]::ToString($sha.ComputeHash($fixtureBytes)).Replace('-','') } finally { $sha.Dispose() }
|
||||||
|
$manifest = Get-Content -Raw -LiteralPath (Join-Path $repo 'resources/EmberkomCloudBackup.json') | ConvertFrom-Json
|
||||||
|
foreach ($kind in 'Windows','VM') {
|
||||||
|
if ($manifest.$kind.SHA256 -notmatch '^[a-f0-9]{64}$' -or $manifest.$kind.Url -notlike 'https://*') { throw "Bad $kind release" }
|
||||||
|
$manifest.$kind.SHA256 = $hash
|
||||||
|
$manifest.$kind.Version = '8.10.1.177'
|
||||||
|
}
|
||||||
|
function IsURLValid { param($URL) $true }
|
||||||
|
function Download-File {
|
||||||
|
param($URL)
|
||||||
|
if ($URL -notlike '*/Update-EmberkomCloudBackup.ps1') { throw "Unexpected script request" }
|
||||||
|
$path = Join-Path $fixtureDir 'downloaded.ps1'
|
||||||
|
[IO.File]::WriteAllText($path, $coreSource)
|
||||||
|
return $path
|
||||||
|
}
|
||||||
|
function New-Object {
|
||||||
|
param($TypeName,[object[]]$ArgumentList)
|
||||||
|
if ($TypeName -eq 'System.Threading.Mutex') {
|
||||||
|
return (Microsoft.PowerShell.Utility\New-Object -TypeName $TypeName -ArgumentList $ArgumentList)
|
||||||
|
}
|
||||||
|
if ($TypeName -ne 'Net.WebClient') { throw "Unexpected construction of $TypeName" }
|
||||||
|
$client = [pscustomobject]@{}
|
||||||
|
$client | Add-Member ScriptMethod DownloadString { param($url)
|
||||||
|
if ($url -like '*/Tools.ps1') { return $shimTools }
|
||||||
|
if ($url -like '*/Update-EmberkomCloudBackup.ps1') { return $coreSource }
|
||||||
|
if ($url -like '*/resources/EmberkomCloudBackup.json') {
|
||||||
|
$record.ManifestReads++
|
||||||
|
return ($manifest | ConvertTo-Json)
|
||||||
|
}
|
||||||
|
throw "Unexpected URL"
|
||||||
|
}
|
||||||
|
$client | Add-Member ScriptMethod Dispose {}
|
||||||
|
return $client
|
||||||
|
}
|
||||||
|
function Invoke-WebRequest {
|
||||||
|
param([switch]$UseBasicParsing,$Uri,$OutFile,$TimeoutSec,$ErrorAction)
|
||||||
|
$record.Downloads++
|
||||||
|
if ($Uri -cne $manifest.$kind.Url -or !$UseBasicParsing -or $TimeoutSec -ne 240) { throw 'Unexpected installer request' }
|
||||||
|
if (Test-Path -LiteralPath $OutFile) { throw 'Partial installer was not removed before retry' }
|
||||||
|
$record.Staged = $OutFile
|
||||||
|
[IO.File]::WriteAllBytes($OutFile, $fixtureBytes)
|
||||||
|
if ($scenario -eq 'corrupt') { [IO.File]::AppendAllText($OutFile,'x') }
|
||||||
|
if ($scenario -eq 'download failure') {
|
||||||
|
throw (Microsoft.PowerShell.Utility\New-Object Net.WebException -ArgumentList 'Certificate validation failed',([Net.WebExceptionStatus]::TrustFailure))
|
||||||
|
}
|
||||||
|
if ($scenario -eq 'persistent timeout' -or ($scenario -in @('timeout then success','plan during retry') -and $record.Downloads -eq 1)) {
|
||||||
|
throw (Microsoft.PowerShell.Utility\New-Object Net.WebException -ArgumentList 'The operation has timed out',([Net.WebExceptionStatus]::Timeout))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function Start-Sleep { param($Seconds) if ($Seconds -ne 3) { throw 'Unexpected retry delay' } }
|
||||||
|
function Get-FixtureInstallation {
|
||||||
|
if ($scenario -eq 'absent') { return }
|
||||||
|
$v = '8.9.1.177'
|
||||||
|
if ($scenario -in @('current','only VM newer','VM needs update','incomplete Windows')) { $v = '8.10.1.177' }
|
||||||
|
if ($record.Installs -and $scenario -ne 'unverified') { $v = $manifest.$kind.Version }
|
||||||
|
if ($scenario -eq 'newer') { $v = '8.11.0.1' }
|
||||||
|
if ($scenario -eq 'already updated' -and $record.Downloads) { $v = '8.10.1.177' }
|
||||||
|
[pscustomobject]@{ Version=[version]$v; Cli='Get-FixtureCli' }
|
||||||
|
}
|
||||||
|
function Get-FixtureCli($Command) {
|
||||||
|
if ($Command -ne 'ver') { throw 'Unexpected agent command' }
|
||||||
|
$record.CliCalls++
|
||||||
|
$global:LASTEXITCODE = 0
|
||||||
|
if ($kind -eq 'VM') { 'Backup Agent Edition: VMware' } else { 'Backup Agent Edition: DesktopIBB' }
|
||||||
|
'Service name: Fixture Service'
|
||||||
|
}
|
||||||
|
function Get-Date {
|
||||||
|
if ($scenario -eq 'window ended' -and $record.Downloads) { return [datetime]'2026-01-01T13:00' }
|
||||||
|
return [datetime]'2026-01-01T12:30'
|
||||||
|
}
|
||||||
|
function Get-CimInstance {
|
||||||
|
param($ClassName,$Filter,$Property,$ErrorAction)
|
||||||
|
$record.PlanChecks++
|
||||||
|
if ($ClassName -ne 'Win32_Process' -or $Filter -ne "Name = 'CBBackupPlan.exe'") { throw 'Unexpected worker query' }
|
||||||
|
if ($scenario -eq 'query failure') { throw 'Cannot enumerate processes' }
|
||||||
|
if ($scenario -eq 'busy' -or ($record.Downloads -and $scenario -in @('late plan','plan during retry'))) { [pscustomobject]@{ ProcessId=42 } }
|
||||||
|
}
|
||||||
|
function Start-Process {
|
||||||
|
param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru,$ErrorAction)
|
||||||
|
$record.Installs++
|
||||||
|
if ($FilePath -ne $record.Staged -or $ArgumentList -cne '/S' -or !$Wait -or !$PassThru) { throw 'Unexpected setup invocation' }
|
||||||
|
$code = switch ($scenario) { reboot {3010} failure {1603} default {0} }
|
||||||
|
[pscustomobject]@{ ExitCode=$code }
|
||||||
|
}
|
||||||
|
function Get-Service {
|
||||||
|
param($Name,$ErrorAction)
|
||||||
|
if ($Name -ne 'Fixture Service') { throw 'Unexpected service name' }
|
||||||
|
$service = [pscustomobject]@{}
|
||||||
|
$service | Add-Member ScriptMethod WaitForStatus { param($state,$timeout)
|
||||||
|
if ($state -ne 'Running' -or $scenario -eq 'service down') { throw 'Backup service unavailable' }
|
||||||
|
}
|
||||||
|
return $service
|
||||||
|
}
|
||||||
|
foreach ($case in @(
|
||||||
|
@('absent',0,0,0), @('current',0,0,0), @('newer',0,0,0),
|
||||||
|
@('only VM newer',0,0,0), @('VM needs update',0,1,1), @('incomplete Windows',1,0,0),
|
||||||
|
@('busy',0,0,0), @('late plan',0,1,0), @('query failure',1,0,0),
|
||||||
|
@('download failure',1,1,0), @('already updated',0,1,0), @('window ended',0,1,0),
|
||||||
|
@('timeout then success',0,2,1), @('plan during retry',0,2,0), @('persistent timeout',1,2,0),
|
||||||
|
@('bad window',1,0,0), @('corrupt',1,1,0), @('success',0,1,1),
|
||||||
|
@('VM',0,1,1), @('failure',1,1,1), @('unverified',1,1,1),
|
||||||
|
@('service down',1,1,1), @('reboot',3010,1,1)
|
||||||
|
)) {
|
||||||
|
$scenario,$expected,$expectedDownloads,$expectedInstalls = $case
|
||||||
|
$kind = if ($scenario -in @('VM','VM needs update')) { 'VM' } else { 'Windows' }
|
||||||
|
$manifest.VM.Version = if ($scenario -in @('only VM newer','VM needs update')) { '8.11.1.177' } else { '8.10.1.177' }
|
||||||
|
$manifest.Windows.SHA256 = if ($scenario -eq 'incomplete Windows') { '' } else { $hash }
|
||||||
|
$MSP360UpdateWindow = switch ($scenario) {
|
||||||
|
'bad window' { '25:00-26:00' }
|
||||||
|
'window ended' { '12:00-13:00' }
|
||||||
|
default { '' }
|
||||||
|
}
|
||||||
|
$record = @{ Downloads=0; Installs=0; Staged=$null; ManifestReads=0; CliCalls=0; PlanChecks=0 }
|
||||||
|
# PowerShell 4 writes Write-Host directly to the host. Capture it separately
|
||||||
|
# so log assertions work on 4.0 without mixing text into the core's return value.
|
||||||
|
$record.HostMessages = @()
|
||||||
|
$messages = & {
|
||||||
|
function Write-Host { param([string]$Object) $record.HostMessages += $Object }
|
||||||
|
& (Join-Path $repo 'rmm/Update-EmberkomCloudBackup.ps1') *>&1
|
||||||
|
}
|
||||||
|
$messages = @($messages) + $record.HostMessages
|
||||||
|
if ($LASTEXITCODE -ne $expected -or $record.Downloads -ne $expectedDownloads -or $record.Installs -ne $expectedInstalls) {
|
||||||
|
throw "$scenario failed. Exit=$LASTEXITCODE Downloads=$($record.Downloads) Installs=$($record.Installs). $messages"
|
||||||
|
}
|
||||||
|
if ($scenario -in @('current','newer','only VM newer')) {
|
||||||
|
$expectedCliCalls = if ($scenario -eq 'only VM newer') { 1 } else { 0 }
|
||||||
|
if ($record.ManifestReads -ne 1 -or $record.CliCalls -ne $expectedCliCalls -or $record.PlanChecks -ne 0 -or
|
||||||
|
($messages -join ' ') -notmatch 'No update needed') { throw "$scenario did not take the expected early exit" }
|
||||||
|
}
|
||||||
|
if ($record.Staged -and (Test-Path -LiteralPath $record.Staged)) { throw "$scenario left staged media" }
|
||||||
|
if ($scenario -eq 'persistent timeout') {
|
||||||
|
$output = $messages -join ' '
|
||||||
|
if ($output -notmatch 'attempt 2 of 2.*Timeout.*3 bytes saved' -or $output -match 'urlParams=') {
|
||||||
|
throw 'Persistent timeout must report the failed attempt and byte count without the signed URL.'
|
||||||
|
}
|
||||||
|
if (!$output.Contains($record.Staged) -or !$output.Contains($hash) -or
|
||||||
|
$output -notmatch "Z $([regex]::Escape($env:COMPUTERNAME)) - MSP360 installer download") {
|
||||||
|
throw 'Missing endpoint, UTC time, installer path or hash for endpoint security correlation.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-Host "PASS $scenario"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check the provisioner's existing edition mapping at the new release-file boundary.
|
||||||
|
& {
|
||||||
|
function Import-MSP360Module {}
|
||||||
|
function Get-MBSAgent { $false }
|
||||||
|
function Get-EmberkomCloudBackupRelease($Build) {
|
||||||
|
$record.Selected = $Build
|
||||||
|
$record.AgentEdition = $AgentEdition
|
||||||
|
throw 'Stopped at release lookup'
|
||||||
|
}
|
||||||
|
foreach ($pair in @(@('desktop','Windows','desktop'), @('server','Windows','baremetal'), @('vm','VM','vmedition'))) {
|
||||||
|
$Edition = $pair[0]
|
||||||
|
$record = @{}
|
||||||
|
try { & (Join-Path $repo 'Install-EmberkomCloudBackup.ps1') }
|
||||||
|
catch { if ($_.Exception.Message -ne 'Stopped at release lookup') { throw } }
|
||||||
|
if ($record.Selected -ne $pair[1] -or $record.AgentEdition -ne $pair[2]) { throw "Wrong provisioning package for $Edition" }
|
||||||
|
Write-Host "PASS existing $Edition installer release selection"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
$fixtureCore = Join-Path $fixtureDir 'downloaded.ps1'
|
||||||
|
if (Test-Path -LiteralPath $fixtureCore) { Remove-Item -LiteralPath $fixtureCore -Force }
|
||||||
|
Remove-Item -LiteralPath $fixtureDir -Force
|
||||||
|
}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
05:32:48 PM Information Created
|
||||||
|
Report: {
|
||||||
|
"ExecutionResult": "Failed",
|
||||||
|
"TroubleshooterName": "GH_OfficeUninstallALDA",
|
||||||
|
"Name": "Office Uninstall ALDA",
|
||||||
|
"ExecutionResultDetails": "There are no supported Office products installed.",
|
||||||
|
"DiagnosticName": "Utility-GetOfficeProducts"
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user