如何在C#单元方法中获取Powershell cmdlet的结果



我有下面的PowerShell cmnd,它在PowerShell中运行良好,我还可以从C#中的单元测试中调用和执行它,如下所述。但我的问题是在PowerShell窗口中,我写$rec.Categories.Count,然后得到结果。我如何在我在C#中调用的PowerShell脚本中写这篇文章,并在其中获取值进行测试?

在PowerShell窗口中:

$inv = Get-Inventory -Project 'TestDemo'
$inv.Categories.Count
4

与我在C#中的脚本相同,我通过下面的方法调用它,它成功运行,但我不知道如何获得";4〃;在我的结果变量中。

[Fact]
public void VerifyGetInventoriesOfaProject()
{
string path = Path.Combine( Root, @"TestDataGetInventory.ps1" );
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript( path );
var results = pipeline.Invoke();
runspace.Close();
// Assert.Equal( 5, results );
}

如果你只搜索c# get output from powershell,第一个结果是一篇关于这个问题的stackoverflow帖子,有一个非常清晰简单的答案。。。

通过代码调用时获取Powershell命令的输出

最新更新