2012-10-26 6 views
1

C# asp.net 웹 페이지를 사용하여 내 서버에서 .ps1 PowerShell 파일을 실행하려고합니다. 스크립트는 매개 변수 하나를 사용하며 서버에서 명령 프롬프트를 사용하여 작동하는지 확인했습니다. 실행 후 결과를 웹 페이지에 표시해야합니다.서버에서 powershell .ps1 파일 실행 및 결과보기 C# asp.net

현재 내가 사용하고 있습니다 :

protected void btnClickCmdLine(object sender, EventArgs e) 
{ 
    lblResults.Text = "Please wait..."; 
    try 
    { 
     string tempGETCMD = null; 
     Process CMDprocess = new Process(); 
     System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo(); 
     StartInfo.FileName = "cmd"; //starts cmd window 
     StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
     StartInfo.CreateNoWindow = true; 
     StartInfo.RedirectStandardInput = true; 
     StartInfo.RedirectStandardOutput = true; 
     StartInfo.UseShellExecute = false; //required to redirect 
     CMDprocess.StartInfo = StartInfo; 
     CMDprocess.Start(); 
     lblResults.Text = "Starting...."; 
     System.IO.StreamReader SR = CMDprocess.StandardOutput; 
     System.IO.StreamWriter SW = CMDprocess.StandardInput; 
     SW.WriteLine("@echo on"); 

     SW.WriteLine("cd C:\\Tools\\PowerShell\\"); 

     SW.WriteLine("powershell .\\poweron.ps1 **parameter**"); 

     SW.WriteLine("exit"); //exits command prompt window 
     tempGETCMD = SR.ReadToEnd(); //returns results of the command window 
     lblResults.Text = tempGETCMD; 
     SW.Close(); 
     SR.Close(); 
    } 
    catch (Exception ex) 
    { 
     lblErrorMEssage.Text = ex.ToString(); 
     showError(); 
    } 
} 

그러나, 심지어는 초기 표시되지 않습니다 "기다려주십시오 ..."나는 PowerShell을 호출하는 줄을 포함합니다. ScriptManager에서 AsyncPostBackTimeout을 늘려도 결국 결국 시간 초과됩니다. 누구나 내가 뭘 잘못하고 있다고 말할 수 있습니까? 감사합니다

+0

poweron.ps1이란 무엇입니까? 어떤 소스 코드? . http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts – Kiquenet

답변

0

나는 보안상의 이유로이 페이지를 직접 aspx에서 실행할 수 없다고 생각합니다. 저를 위해 아주 잘 Capturing Powershell output in C# after Pipeline.Invoke throws

1 일 :

  1. 원격 실행 영역을 만듭니다 : http://social.msdn.microsoft.com/Forums/hu/sharepointgeneralprevious/thread/88b11fe3-c218-49a3-ac4b-d1a04939980c http://msdn.microsoft.com/en-us/library/windows/desktop/ee706560%28v=vs.85%29.aspx

  2. PSHost 출력을 실행하고 포착하기 위해서이다.

참고 : 이벤트가 완료되지 않았기 때문에 레이블이 업데이트되지 않습니다. PowerShell을 기다리는 동안 레이블을 표시하려면 ajax를 사용해야 할 수도 있습니다.

0

시도했을 때 SR.ReadToEnd()을 완료하기 전에 표준 입력을 플러시하거나 닫아야합니다. 이것을 시도하십시오 :

lblResults.Text = "Please wait..."; 
    try 
    { 
     string tempGETCMD = null; 
     Process CMDprocess = new Process(); 
     System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo(); 
     StartInfo.FileName = "cmd"; //starts cmd window 
     StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
     StartInfo.CreateNoWindow = true; 
     StartInfo.RedirectStandardInput = true; 
     StartInfo.RedirectStandardOutput = true; 
     StartInfo.UseShellExecute = false; //required to redirect 
     CMDprocess.StartInfo = StartInfo; 
     CMDprocess.Start(); 
     lblResults.Text = "Starting...."; 
     using (System.IO.StreamReader SR = CMDprocess.StandardOutput) 
     { 
      using (System.IO.StreamWriter SW = CMDprocess.StandardInput) 
      { 
       SW.WriteLine("@echo on"); 
       SW.WriteLine("cd C:\\Tools\\PowerShell\\"); 
       SW.WriteLine("powershell .\\poweron.ps1 **parameter**"); 
       SW.WriteLine("exit"); //exits command prompt window 
      } 
      tempGETCMD = SR.ReadToEnd(); //returns results of the command window 
     } 
     lblResults.Text = tempGETCMD; 
    } 
    catch (Exception ex) 
    { 
     lblErrorMessage.Text = ex.ToString(); 
     showError(); 
    } 
} 
4

약간 날짜가 남았습니다. 그러나 비슷한 해결책을 찾으려는 사람들에게는 cmd를 작성하고 powershell을 전달하지 않고 System.Management.Automation 네임 스페이스를 활용하고 cmd를 사용하지 않고 PowerShell 콘솔 객체 서버 측을 만들 수 있습니다. 실행을 위해 명령 또는 .ps1 파일을 AddScript() 함수에 전달할 수 있습니다. PowerShell.exe를 호출해야하는 별도의 셸보다 훨씬 깔끔합니다.

응용 프로그램 풀의 적절한 ID와 해당 보안 주체가 PowerShell 명령 및/또는 스크립트를 수행하는 데 필요한 적절한 수준의 권한을 갖고 있는지 확인하십시오. 또한 실행 정책을 계속 실행하려는 경우 Set-ExecutionPolicy을 통해 구성된 실행 정책을 적절한 수준 (서명하지 않은 한 제한되지 않거나 원격 서명)으로 설정해야합니다. ps1 파일 서버 측. 여기

는 이러한 개체를 사용하여 AA PowerShell 콘솔 인 것처럼 텍스트 상자 웹 양식에 의해 제출 명령을 실행하는 일부 스타터 코드의 - 접근 설명한다 : 여기

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Management.Automation; 
using System.Text; 

namespace PowerShellExecution 
{ 
    public partial class Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     protected void ExecuteCode_Click(object sender, EventArgs e) 
     { 
      // Clean the Result TextBox 
      ResultBox.Text = string.Empty; 

      // Initialize PowerShell engine 
      var shell = PowerShell.Create(); 

      // Add the script to the PowerShell object 
      shell.Commands.AddScript(Input.Text); 

      // Execute the script 
      var results = shell.Invoke(); 

      // display results, with BaseObject converted to string 
      // Note : use |out-string for console-like output 
      if (results.Count > 0) 
      { 
       // We use a string builder ton create our result text 
       var builder = new StringBuilder(); 

       foreach (var psObject in results) 
       { 
        // Convert the Base Object to a string and append it to the string builder. 
        // Add \r\n for line breaks 
        builder.Append(psObject.BaseObject.ToString() + "\r\n"); 
       } 

       // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < > 
       ResultBox.Text = Server.HtmlEncode(builder.ToString()); 
      } 
     } 
    } 
} 

을 쓰기는 당신을 위해이다 그건 그 커버 Visual Studio로 처음부터 끝까지 페이지를 작성하고 완료하는 방법, http://grokgarble.com/blog/?p=142.

관련 문제