159 lines
13 KiB
PowerShell
159 lines
13 KiB
PowerShell
#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 }
|