Search code examples
c#powershellasp.net-coreexit

How can I keep an Asp.Net web app running despite a powershell call to [System.Environment]::Exit(1)


I am currently building an Asp.Net Core web app in C#. The web app needs to call a pre-existing powershell script which I cannot edit or modify. I call the script as so:

using (var pwsh = PowerShell.Create())
{
    string script = $"Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process; cd \"{directory}\"; .\\script.ps1";
    var results = pwsh.AddScript(script).Invoke();
}

This works without any apparent problems for the most part. There is an issue though when the script throws an error. Within the script there is a global catch which looks like this:

catch
{
    [System.Environment]::Exit(1)
}

When this catch block is entered the call to Environment.Exit brings down the entire website - this is not the behaviour I would like. I was wondering if there was anyway around this (again without altering the script).


Solution

  • As Keith Nicholas says, we could try to start a process to run the powershell script.

    About how to run powershell script, I suggest you could try to refer to below example codes:

            if (System.IO.File.Exists("your powshell script path"))
            {
                 string strCmdText = "your powshell script path";
                var process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.FileName = @"C:\windows\system32\windowspowershell\v1.0\powershell.exe";
                process.StartInfo.Arguments = "\"&'" + strCmdText + "'\"";
    
                process.Start();
                string s = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
    
            }