0

I want to set a timeout on powershell scripts I have running in c#.

My code to run my scripts is

  private void RunPowerShell(string scriptText)
        {
            string tempFile = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "PinScript.ps1");
            var file = new StreamWriter(tempFile);
            file.AutoFlush = true;
            file.WriteLine(scriptText);
            file.Dispose();

            string output, errors = string.Empty;
            //this is basically a helper method that runs an exe via the command prompt in c#
            //I want to keep this as is and either add an argument to powershell.exe or alter the 
            //.psi scripts themselves
            _cmd.Run(@"powershell.exe",
                            @"-NoProfile -ExecutionPolicy Bypass " + @"& '" + tempFile + "'",
                            out output,
                            out errors);

            Console.WriteLine("Powershell Output: " + output);
            Console.WriteLine("Powershell Errors: " + errors);
            File.Delete(tempFile);
        }

I see there is code that works to time out a script here but I cannot understand how to ingrate that concept into what I have above.

  • You are running Synchronously while link was running Asynchronously. So the timeout is not needed in Synchronous mode unless you want to shutdown the powershell after a certain time limit. Then you could use a c# timer and close the _cmd after a period of time. – jdweng Feb 05 '20 at 17:42
  • You can read the article referred to in that SO post in the Wayback Machine here: https://web.archive.org/web/20170830063823/https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ – Matt Gregory Feb 05 '20 at 17:44
  • @jdweng If the powershell script hangs I simply want to shut it down after 2 min of hanging and give back a message – user12847070 Feb 05 '20 at 17:47
  • You use the Kill() to stop the _cmd process in a timer. – jdweng Feb 05 '20 at 18:06

0 Answers0