Skip to content

Instantly share code, notes, and snippets.

@brud
Created July 18, 2023 11:08
Show Gist options
  • Save brud/3f493c53bc58b0cefa0d913b8b580d90 to your computer and use it in GitHub Desktop.
Save brud/3f493c53bc58b0cefa0d913b8b580d90 to your computer and use it in GitHub Desktop.
Cmd caller with error
open System
open System.Diagnostics
open System.Threading.Tasks
type CommandResult = {
ExitCode: int;
StandardOutput: string;
StandardError: string
}
let processStartInfo executable args =
let startInfo = ProcessStartInfo (executable, args)
startInfo.RedirectStandardOutput <- true
startInfo.RedirectStandardError <- true
startInfo.UseShellExecute <- false
startInfo.CreateNoWindow <- true
startInfo
let executeCommand executable args =
async {
use p = new Process ()
p.StartInfo <- processStartInfo executable args
p.Start() |> ignore
let outTask = Task.WhenAll [| p.StandardOutput.ReadToEndAsync (); p.StandardError.ReadToEndAsync () |]
do! p.WaitForExitAsync() |> Async.AwaitTask
let! out = outTask |> Async.AwaitTask
return {
ExitCode = p.ExitCode;
StandardOutput = out.[0];
StandardError = out.[1]
}
}
let executeShellCommand command =
executeCommand "cmd" command
// Invocation sample
let r = executeShellCommand "msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi" |> Async.RunSynchronously
if r.ExitCode = 0 then
printfn $"{r.StandardOutput}"
else
eprintfn $"{r.StandardError}"
Environment.Exit(r.ExitCode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment