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

1 c# asp.net powershell scripting command-line

我正在尝试使用 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我包含调用 powershell 的行,它甚至不会显示初始的“请稍候……”。它最终会超时,即使我增加了 ScriptManager 上的 AsyncPostBackTimeout。谁能告诉我我做错了什么?谢谢

Jef*_*eff 5

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

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

下面是一些执行由 TextBox Web 表单提交的命令的启动代码,就好像它是使用这些对象的 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());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一篇写给您的文章,其中介绍了如何使用 Visual Studio 从头到尾创建页面并完成此操作,http://grokgarble.com/blog/?p= 142 。