首页 > 解决方案 > Powershell ASP.net 返回某些字段

问题描述

我从各种来源混淆了以下查询,但无法使其工作,因此它只返回输出框中的选定字段。我需要用户通过网络输入路径,因此无法使用 addscript 命令。如果在 zip 过滤器之后删除 3 个命令,则脚本将返回 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.Management.Automation.Runspaces;
using System.Text;

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

    }


    protected void ExecuteInputClick(object sender, EventArgs e)
    {
        // First of all, let's clean the TextBox from any previous output
        Result.Text = string.Empty;

        // Create the InitialSessionState Object
        InitialSessionState iss = InitialSessionState.CreateDefault2();

        //In our specific case we don't need to import any module, but I'm adding these two lines below
        //to show where we would import a Module from Path.
        //iss.ImportPSModulesFromPath("C:\\inetpub\\LocalScriptsAndModules\\MyModuleFolder1");
        //iss.ImportPSModulesFromPath("C:\\inetpub\\LocalScriptsAndModules\\MyOtherModule2");


        // Initialize PowerShell Engine
        var shell = PowerShell.Create(iss);

        // Add the command to the Powershell Object, then add the parameter from the text box with ID Input
        //The first one is the command we want to run with the input, so Get-ChildItem is all we need
        shell.Commands.AddCommand("Get-ChildItem").AddParameter("Path", Input.Text)
                                                  .AddParameter("Filter", "*.zip");
        shell.AddCommand("select-object");
        var props = new string[] { "name", "LastWriteTime" };
        shell.AddParameter("property", props);


        // Execute the script 
        try
        {
            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 < >
                Result.Text = Server.HtmlEncode(builder.ToString());
            }
        }
        catch (ActionPreferenceStopException Error) { Result.Text = Error.Message; }
        catch (RuntimeException Error) { Result.Text = Error.Message; };
    }
}
}

标签: c#asp.netpowershell

解决方案


推荐阅读