Untitled

 avatar
unknown
plain_text
a year ago
1.9 kB
5
Indexable
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
}
Editor is loading...
Leave a Comment