【问题标题】:How to call power shell script file by passing attributes in c#如何通过在c#中传递属性来调用powershell脚本文件
【发布时间】:2019-02-22 09:21:34
【问题描述】:

如何通过在c#中传递属性来调用power shell脚本文件。 我正在使用下面的代码通过传递输入来调用 ps1 文件,但在调用附近出现错误。 错误信息:

System.Management.Automation.CommandNotFoundException: '术语 'Get-Childitem C:\samplemm.ps1' 未被识别为 cmdlet、函数、脚本文件或可运行的程序。检查 名称的拼写,或者如果包含路径,请验证路径 是正确的,然后再试一次。'

namespace SCOMWebAPI.Services
{
    public class MaintennceModeService
    {
        private static IEnumerable<PSObject> results;

        internal static string post(MaintenanceMode value)
        {
            // create Powershell runspace

            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            Pipeline pipeline = runspace.CreatePipeline();

            //Here's how you add a new script with arguments
            Command myCommand = new Command("Get-Childitem C:\\samplemm.ps1");
            CommandParameter testParam = new CommandParameter("mgmtserver", "NodeName");
            myCommand.Parameters.Add(testParam);

            pipeline.Commands.Add(myCommand);

            // Execute PowerShell script
            results = pipeline.Invoke();
            runspace.Close();
            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
              stringBuilder.AppendLine(obj.ToString());
            }

            return stringBuilder.ToString();
        }
    }
}

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    当您在 powershell 中键入命令 Get-ChildItem C:\\samplemm.ps1 时,实际上是将文本 C:\\samplemm.ps1 绑定到默认参数 Path

    您的代码的问题是您将第一个参数作为命令名称的一部分包含在内。只需将其分开即可。

    代替

    Command myCommand = new Command("Get-Childitem C:\\samplemm.ps1");
    

    分离出参数:

    Command myCommand = new Command("Get-Childitem");
    CommandParameter pathParameter = new CommandParameter("Path", "C:\\samplemm.ps1");
    myCommand.Parameters.Add(pathParameter);
    

    【讨论】:

    • 实际上我需要将输入变量传递给powershell脚本并捕获powershell脚本的返回并转换为json格式。
    • @Jack - 您的问题中未提及此信息。您的问题仅涉及错误。根据这个答案似乎是合适的。您必须添加有关您想要什么样的 json 以及您想要完成什么的问题的详细信息?。
    • @Jack - 与其在您的问题中添加详细信息,不如发布一个新的、不同的问题。
    • 谢谢大家,我可以用您提供的解决方案修复
    猜你喜欢
    • 2010-12-24
    • 1970-01-01
    • 2010-11-27
    • 2014-11-08
    • 2011-01-23
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多