scripts/optimization.ps1
2026-02-21 15:48:04 +01:00

73 lines
No EOL
2.7 KiB
PowerShell

# Function to run process with true live streaming output
function Start-ProcessWithLiveStreaming {
param(
[string]$FilePath,
[string]$Arguments,
[string]$Name
)
$tempPath = $env:TEMP
$stdoutFile = "$tempPath\${Name}_stdout.txt"
$stderrFile = "$tempPath\${Name}_stderr.txt"
# Clean up old files
if (Test-Path $stdoutFile) { Remove-Item $stdoutFile -ErrorAction SilentlyContinue }
if (Test-Path $stderrFile) { Remove-Item $stderrFile -ErrorAction SilentlyContinue }
# Create file handles for immediate reading
$fileStream = [System.IO.File]::Create($stdoutFile)
Write-Host "Starting $Name..."
# Start the process
$process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -NoNewWindow -PassThru -RedirectStandardOutput $stdoutFile -RedirectStandardError $stderrFile -ErrorAction Stop
# Read output while process runs
$lastPosition = 0
while (-not $process.HasExited) {
Start-Sleep -Milliseconds 500
if (Test-Path $stdoutFile) {
$currentLength = (Get-Item $stdoutFile).Length
if ($currentLength -gt $lastPosition) {
$bytesToRead = $currentLength - $lastPosition
$stream = [System.IO.File]::OpenRead($stdoutFile)
$stream.Seek($lastPosition, [System.IO.SeekOrigin]::Begin) | Out-Null
$buffer = New-Object byte[] $bytesToRead
$stream.Read($buffer, 0, $bytesToRead) | Out-Null
$stream.Close()
$text = [System.Text.Encoding]::UTF8.GetString($buffer)
Write-Host $text -NoNewline
$lastPosition = $currentLength
}
}
}
# Wait for process to complete
$process.WaitForExit()
# Read any remaining output
if (Test-Path $stdoutFile) {
$content = Get-Content -Path $stdoutFile -Raw -ErrorAction SilentlyContinue
if ($content) { Write-Host $content }
}
if (Test-Path $stderrFile) {
$content = Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue
if ($content) { Write-Host $content }
}
# Get output for return
$outputText = ""
if (Test-Path $stdoutFile) { $outputText = Get-Content -Path $stdoutFile -Raw -ErrorAction SilentlyContinue }
if (Test-Path $stderrFile) { $outputText += Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue }
# Cleanup
Remove-Item $stdoutFile -ErrorAction SilentlyContinue
Remove-Item $stderrFile -ErrorAction SilentlyContinue
$fileStream.Close()
return @{
ExitCode = $process.ExitCode
Output = $outputText
}
}