Powershell script executed but hangs when called from IIS ASP.NET site

Viewed 55

This is my code:

In Default.aspx.cs

//Default.aspx.cs is used to create a docx file on server 
//and push to the browser for downloading  
protected void btnSubmit_Click(object sender, EventArgs e)
{
  try
  {
    string strOutFile = string.Empty;
    switch (ExportType.SelectedItem.Value)
    {
      case "TestReport":
        //_strBaseDirectory was defined in web.config and refer to the site wwwroot folder
        strOutFile = _strBaseDirectory + @"Download\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".docx";
        RunPowershell(
          _strBaseDirectory + @"Powershell\ExportTestResult.ps1 " + "' -Outfile " + strOutFile);
        break;
      default:
        break;
    }
    Download("~/DownLoad/" + new FileInfo(strOutFile).Name);
  }
  catch (Exception ex)
  {
    //log   
  }  
}

private void Download(string strFilePath)
{
  if (new FileInfo(Server.MapPath(strFilePath)).Exists)
  {
    Response.ContentType = "application/octet-stream";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + new FileInfo(strFilePath).Name);
    Response.TransmitFile(Server.MapPath(strFilePath));
    Response.End();
  }
} 

private int RunPowershell(string strArguments)
{
  try
  {
    var p = Process.Start(
      "powershell.exe",
      @strArguments
    );
    p.WaitForExit();
    return p.ExitCode;
  }
  catch (Exception ex)
  {
    throw (ex);
  }
}

Powershell\ExportTestResult.ps1 :

#For debugging, all the suspected cmdlets and COM reference operations have been removed one-by-one. 
#The latest and entire content(identical to my local one), I copy here

param ($Outfile)
cls

cp "d:\wwwroot\site\download\template.docx" $outfile
exit

What I have tried:

  1. When the asp/ps1 published to IIS and trigger from browser,
    1. ExportTestResult.ps1 has been started with a new process id ;
    2. The file (refer to $outfile in ExportTestResult.ps1) has been created;
    3. powershell process keep running without exit.
    4. When I killed the powershell process in windows ProcessManager, the browser show the downloading progress immediately
  2. When the asp project/ps1 ran in VS directly, ExportTestResult.ps1 and p.WaitForExit() exited directly.

Environment:

  • IIS: 10
  • PowerShell: 5.1

So, how to let the powershell process exit correctly in IIS just like debugging in VS? Is there something wrong with my IIS config?

If I missed something, please let me know.

0 Answers
Related