Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.9 kB
1
Indexable
Never
Function Run-ProgramwithStdout {
    param($Command)
    $detail = [System.Collections.ArrayList]@()

    [string]$TextReturn = ''

    $StdOutputFile = "$($ENV:TEMP)\$($pid)-stdout.log"
    $StdErrorFile = "$($ENV:TEMP)\$($pid)-stderr.log"
    
    $Detail += New-Object PSObject -Property @{
        "Attribute"= "Command line"
        "Value" = "$Command"
        "Result" = "Success"
    }

    $ts = Measure-Command {
        $processInfo = New-Object System.Diagnostics.ProcessStartInfo
        $processInfo.FileName = "powershell"
        $processInfo.Arguments = "-NoProfile -ExecutionPolicy Bypass -Command $Command"
        $processInfo.RedirectStandardOutput = $true
        $processInfo.RedirectStandardError = $true
        $processInfo.UseShellExecute = $false
        $processInfo.CreateNoWindow = $true

        $process = New-Object System.Diagnostics.Process
        $process.StartInfo = $processInfo
        $process.Start() | Out-Null
        $process.WaitForExit()

        $stdOutput = $process.StandardOutput.ReadToEnd()
        $stdError = $process.StandardError.ReadToEnd()

        $Detail += New-Object PSObject -Property @{
            "Attribute"= "Return code"
            "Value" = "$($process.ExitCode)"
            "Result" = "Success"
        }

        # Standard output
        $detail += New-Object PSObject -Property @{
            'Attribute' = "StdOut"
            'Value' = $stdOutput
            'Result' = "Success"
        }

        # Standard Error
        $detail += New-Object PSObject -Property @{
            'Attribute' = "StdErr"
            'Value' = $stdError
            'Result' = "Success"
        }
    }

    $ht = @{
        'Text' = $detail
        'ExecutionTime' = [math]::Round($ts.TotalSeconds, 0)
        'ExitCode' = $process.ExitCode
    }
    return $ht
}
Leave a Comment