58 lines
1.8 KiB
PowerShell
58 lines
1.8 KiB
PowerShell
[CmdletBinding()]
|
|
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$Command,
|
|
[string]$OutputDir,
|
|
[switch]$AllowNonZeroExit
|
|
)
|
|
|
|
Set-StrictMode -Version Latest
|
|
$ErrorActionPreference = "Stop"
|
|
|
|
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
|
$OutputDir = if ([string]::IsNullOrWhiteSpace($OutputDir)) {
|
|
Join-Path $repoRoot "artifacts\admin-command"
|
|
} else {
|
|
$OutputDir
|
|
}
|
|
$null = New-Item -ItemType Directory -Path $OutputDir -Force
|
|
|
|
$stdoutPath = Join-Path $OutputDir "stdout.txt"
|
|
$stderrPath = Join-Path $OutputDir "stderr.txt"
|
|
$metaPath = Join-Path $OutputDir "meta.txt"
|
|
$exitCodePath = Join-Path $OutputDir "exit-code.txt"
|
|
|
|
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
|
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
|
|
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
|
|
|
@(
|
|
"timestamp=$([DateTimeOffset]::Now.ToString('O'))"
|
|
"is_admin=$isAdmin"
|
|
) | Set-Content -LiteralPath $metaPath -Encoding UTF8
|
|
|
|
$psi = [System.Diagnostics.ProcessStartInfo]::new()
|
|
$psi.FileName = "cmd.exe"
|
|
$psi.Arguments = "/d /c $Command"
|
|
$psi.WorkingDirectory = (Get-Location).Path
|
|
$psi.UseShellExecute = $false
|
|
$psi.RedirectStandardOutput = $true
|
|
$psi.RedirectStandardError = $true
|
|
|
|
$process = [System.Diagnostics.Process]::Start($psi)
|
|
if ($null -eq $process) {
|
|
throw "Failed to start command."
|
|
}
|
|
|
|
$stdout = $process.StandardOutput.ReadToEnd()
|
|
$stderr = $process.StandardError.ReadToEnd()
|
|
$process.WaitForExit()
|
|
|
|
Set-Content -LiteralPath $stdoutPath -Value $stdout -Encoding UTF8
|
|
Set-Content -LiteralPath $stderrPath -Value $stderr -Encoding UTF8
|
|
Set-Content -LiteralPath $exitCodePath -Value "$($process.ExitCode)" -Encoding UTF8
|
|
|
|
if (-not $AllowNonZeroExit -and $process.ExitCode -ne 0) {
|
|
throw "Command failed with exit code $($process.ExitCode)."
|
|
}
|