Normally you shouldn't rely on exit codes from PowerShell script, but to answer your question, with your current implementation you can query $LASTEXITCODE automatic variable before disposing your PowerShell instance, however, for this to work you will need to pass-in the script path as .AddScript(...) argument, instead of reading the script content via File.ReadAllText(...). Preferably you should use an absolute path but relative might work
You should also handle the Write-Host output in your code, that output you can find it in ps.Streams.Information, it will not be output from .Invoke().
Alternatively, you could subscribe to DataAdding event:
ps.AddScript(@".\buildScript.ps1");
ps.Streams.Information.DataAdding += (s, e) =>
{
InformationRecord info = (InformationRecord)e.ItemAdded;
Console.WriteLine(info.MessageData);
};
In summary you can do:
int exitCode = 0;
using (PowerShell ps = PowerShell.Create())
{
ps.AddScript(@".\buildScript.ps1");
var psResults = ps.Invoke();
foreach (PSObject psObj in psResults)
{
var result = psObj.ToString();
}
// if not using the event driven approach
if (ps.Streams is { Information.Count: > 0 })
{
foreach (InformationRecord information in ps.Streams.Information)
{
// handle information output here...
}
}
if (ps.HadErrors)
{
ps.Commands.Clear();
exitCode = ps
.AddScript("$LASTEXITCODE")
.Invoke<int>()
.FirstOrDefault();
}
}
// Do something with exitCode