【问题标题】:Not able to pass Object over pipeline in C# to run powershell commands无法在 C# 中通过管道传递对象以运行 powershell 命令
【发布时间】:2015-12-18 23:23:52
【问题描述】:

我想使用 C# 运行以下 PS cmd

Get-SCRunAsAccount -VMMServer VmmserverName -Name proName | Remove-SCRunAsAccount

我尝试了以下程序,但配置文件没有被删除。当我在 Powershell 中运行上述 cmd 时,它可以工作,这意味着 cmd 没有问题。但不确定为什么 RunAsAccount 的对象没有通过 C# 中的管道。

我也尝试过在 c# 中使用管道运行 Get-process | Sort-Object VM 它有效。

帮助我在这里缺少什么

        Pipeline pipeline = Runspace.CreatePipeline();            
        Collection<PSObject> results = null;
        string output = null;

        Command command = new Command("Get-SCRunAsAccount");            
        command.Parameters.Add("VMMServer", "VmmserverName");
        command.Parameters.Add("Name", "proName");

        Command command1 = new Command("Remove-SCRunAsAccount");

        pipeline.Commands.Add(command);
        pipeline.Commands.Add(command1);
        pipeline.Commands.Add("Out-String");          
        results = pipeline.Invoke(); 

【问题讨论】:

    标签: c# powershell command pipeline


    【解决方案1】:

    您需要先导入SCVMM cmdlet,然后才能使用它们:

    pipeline.Commands.Add("Import-Module").AddParameter("Name","VirtualMachineManager");
    

    【讨论】:

    • 我忘了提到 VMM 模块已经导入到运行空间中。如果我在它下方运行,则正确显示 RunasAccount。命令 command = new Command("Get-SCRunAsAccount"); command.Parameters.Add("VMMServer", "VmmserverName"); command.Parameters.Add("Name", "proName");管道。命令。添加(命令); pipeline.Commands.Add("Out-String");结果 = pipeline.Invoke();
    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多