简体   繁体   English

将参数传递到PowerShellScript的文件路径

[英]Passing the argument to the file path of PowerShellScript

Trying to pass the argument(s) or list of argument to PowerShell Script Path while executing it through C# function. 通过C#函数执行时,尝试将参数或参数列表传递给PowerShell脚本路径。

I am using a C# function to get the list of details from my script via a function that uses System.Management.Automation library to invoke powershell command. 我正在使用C#函数通过使用System.Management.Automation库调用powershell命令的函数从脚本中获取详细信息列表。 I am passing file path thus the script is working perfectly fine when it does not requires any argument, however when I need to pass them it is giving User-UnHandled Exeption. 我正在传递文件路径,因此该脚本在不需要任何参数的情况下可以正常运行,但是当我需要传递它们时,它将给出User-UnHandled Exeption。

Value in the scriptPath Variable: scriptPath变量中的值:

C:\Users\<username>\source\repos\MyProject\Shell\Get-SDC.ps1 'Test - Group'

My function: 我的功能:

private string PowerShellExecutorStr(string scriptPath)
    {
        string outString = "";
        var shell = PowerShell.Create();
        shell.Commands.AddCommand(scriptPath);
        var results = shell.Invoke();
        if (results.Count > 0)
        {
            var builder = new StringBuilder();
            foreach (var psObj in results)
            {
                builder.Append(psObj.BaseObject.ToString() + "\r\n");
            }
            outString = Server.HtmlEncode(builder.ToString());
        }
        shell.Dispose();
        return outString;
    }

Script: 脚本:

param($GroupName)
<Get-ADGroup Command to fetch Details of the Group using $GroupName as Parameter>

outString needs to fetch the output of the PowerShell Script when the arguments are passed to it. 将参数传递给outString时,需要获取PowerShell脚本的输出。

Use Add Parameter 使用添加参数

var shell = PowerShell.Create();
shell.Commands.AddCommand(scriptPath)
              .AddParameter("ParamName", "ParamValue");
var results = shell.Invoke();

The above is equivelent to to following PowerShell: 以上等同于以下PowerShell:

PS> scriptPath -ParamName ParamValue

Here's a breakdown in the documentation 这是文档中的细分

Another way that I found through Archer's link is to add argument 我通过Archer链接发现的另一种方法是添加参数

private string PowerShellExecutorStr(string script, string arg)
        {
            string outString = "";
            var shell = PowerShell.Create();
            shell.Commands.AddCommand(script);
            shell.Commands.AddArgument(arg);    // <----- Using this statement
            var results = shell.Invoke();
            ……rest of the code
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM