PrintToVeraeTimeStamp/platform/windows/scripts/common.ps1

53 lines
2.7 KiB
PowerShell

# Shared helpers for the Verae installer scripts (dot-source me).
# The interactive (logged-in, non-elevated) user of THIS session — not the admin
# account that may have been used for UAC elevation. Owner of explorer.exe in our
# session; falls back to Win32_ComputerSystem.UserName (console user).
function Get-VeraeTargetUser {
$sess = (Get-Process -Id $PID).SessionId
$res = $null
foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sess })) {
$o = Invoke-CimMethod -InputObject $p -MethodName GetOwner -ErrorAction SilentlyContinue
$s = Invoke-CimMethod -InputObject $p -MethodName GetOwnerSid -ErrorAction SilentlyContinue
if ($o -and $o.User) { $res = [pscustomobject]@{ Domain = $o.Domain; User = $o.User; Sid = $s.Sid; Source = "explorer(session $sess)" }; break }
}
if (-not $res) {
$cu = (Get-CimInstance Win32_ComputerSystem).UserName
if ($cu) {
$d, $u = $cu -split '\\', 2
$sid = (New-Object Security.Principal.NTAccount($cu)).Translate([Security.Principal.SecurityIdentifier]).Value
$res = [pscustomobject]@{ Domain = $d; User = $u; Sid = $sid; Source = "console user" }
}
}
if (-not $res) {
$id = [Security.Principal.WindowsIdentity]::GetCurrent()
$d, $u = $id.Name -split '\\', 2
$res = [pscustomobject]@{ Domain = $d; User = $u; Sid = $id.User.Value; Source = "current process (fallback)" }
}
$prof = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$($res.Sid)" -ErrorAction SilentlyContinue).ProfileImagePath
if (-not $prof) { $prof = Join-Path (Split-Path $env:USERPROFILE -Parent) $res.User }
$res | Add-Member -NotePropertyName Profile -NotePropertyValue $prof
$res | Add-Member -NotePropertyName Account -NotePropertyValue "$($res.Domain)\$($res.User)"
return $res
}
function Get-MaskedToken([string]$t) {
if (-not $t) { return "" }
$t = $t.Trim()
if ($t.Length -le 12) { return "***" }
return ($t.Substring(0, 7) + "..." + $t.Substring($t.Length - 4))
}
# Write a flat INI (ASCII) readable by NSIS ReadINIStr.
function Write-VeraeIni([string]$Path, [string]$Section, [System.Collections.IDictionary]$Values) {
$lines = @("[$Section]")
foreach ($k in $Values.Keys) { $v = "$($Values[$k])" -replace "[\r\n]+", " "; $lines += "$k=$v" }
if (Test-Path $Path) {
# keep other sections
$old = Get-Content $Path -ErrorAction SilentlyContinue
$keep = @(); $skip = $false
foreach ($l in $old) { if ($l -match '^\[(.+)\]$') { $skip = ($Matches[1] -eq $Section) }; if (-not $skip) { $keep += $l } }
$lines = $keep + $lines
}
Set-Content -Path $Path -Value $lines -Encoding ASCII
}