从C#中的Power Shell脚本接收输出,并使用它来进一步指导我的C#代码

我试图用C#制作Windows窗体应用程序以运行Power-Shell命令,该命令将对active Directory计算机对象进行更改。

我已经获得了使更改生效的代码部分,但是我需要一节来检查Current Description属性并将其返回以对其执行if语句。我试图弄清楚如何从我的第一个Power-Shell命令获取输出以转到字符串值,以便我可以继续使用C#,Power-Shell脚本是由同事创建的,并且希望尝试并改进它。

我尝试使用其他帮助Output Result from Powershell command to C# variable中的方法

我要么只获得计算机名称,要么获得计算机名称和System.Collections.ObjectModel.Collection``1[System.Management.Automation.PSObject]

private void ChangeDefault_Click(object sender,EventArgs e)
{
    oldistag = OldISTag.Text;
    newistag = NewISTag.Text;
    computeristags = ComputerIstag.Text.Split(new string[] { System.Environment.NewLine },StringSplitOptions.None);
    computeristagsout = new string[computeristags.Length];

    for (int i = 0; i < computeristags.Length; i++)
    {
        // PS script "Get-ADComputer -Identity " + "ISC110476" + " -Properties Description | Select-Object -ExpandProperty Description"
        // returns  a single line in powershell ISC108956
        var script = "Get-ADComputer -Identity " + computeristags[i] + " -Properties Description | Select-Object -ExpandProperty Description";

        PowerShell powerShell = PowerShell.Create().AddScript(script);           


        var current = powerShell.Invoke();

        computeristagsout[i] = computeristags[i] + currentdesc + current;
        System.IO.File.WriteAllText(@"C:\Scripts\output.txt",computeristagsout[i]);
    }

    for (int i = 0; i < computeristagsout.Length; i++)
    {
        output.Text += computeristagsout[i] + "\r\n";
    }
}

如果有任何内容,我希望得到的只是描述字段中的结果。

我已经收到System.Collections.ObjectModel.Collection``1[System.Management.Automation.PSObject]

ltye1113 回答:从C#中的Power Shell脚本接收输出,并使用它来进一步指导我的C#代码

尝试一下:

using System.Linq;
// ...
var script = "$(Get-ADComputer -Identity " + computeristags[i] + " -Properties Description | Select -ExpandProperty Description)";
PowerShell powerShell = PowerShell.Create().AddScript(script);           
var collection = powerShell.Invoke();
var current = collection.First();
computeristagsout[i] = string.Format("{0}{1}{2}",computeristags[i],currentdesc,current);

cmdlet Select-Object返回一个对象,这就是为什么要获取System.Management.Automation.PSObject::ToString的输出的原因。您需要使用Select来返回结合了-ExpandProperty的文本(仅一个自变量),然后您会得到一个string,您可以在其中使用日志。

本文链接:https://www.f2er.com/3116983.html

大家都在问