Skip to main content
 首页 » 编程设计

c#之在服务器上执行 powershell .ps1 文件并查看结果 C# asp.net

2024年02月20日10xxx_UU

我正在尝试使用 C# asp.net 网页在我的服务器上执行 .ps1 PowerShell 文件。 该脚本采用一个参数,我已经通过使用服务器上的命令提示符验证了它是否有效。运行后,我需要在网页上显示结果。

目前,我正在使用:

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。 谁能告诉我我做错了什么? 谢谢

请您参考如下方法:

有点过时;然而,对于那些寻找类似解决方案的人,我不会创建一个 cmd 并将 powershell 传递给它,而是利用 System.Management.Automation命名空间并在没有 cmd 中间人的情况下创建 PowerShell 控制台对象服务器端。您可以将命令或 .ps1 文件传递​​给 AddScript() 函数(均带有参数)以供其执行。比必须调用 powershell.exe 的单独 shell 干净得多。

确保应用程序池的适当身份以及主体具有执行 PowerShell 命令和/或脚本所需的适当级别的权限。此外,请确保您已通过 Set-ExecutionPolicy 将执行策略配置为适当的级别(无限制/或远程签名,除非您正在签名),以防您仍要执行执行 .ps1 文件服务器端的方式。

下面是一些起始代码,它执行由 TextBox 网络表单提交的命令,就好像它是一个使用这些对象的 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 .