获取PowerShell响应

huangapple go评论68阅读模式
英文:

C# obtaining Powershell responses

问题

使用PowerShell,我可以使用以下代码:

$myMB = Get-Mailbox -Identity "test@test.com"

然后,我可以通过以下方式获取任何属性:

Write-Host $myMB.Name
Write-Host $myMB.Alias

在C#中,使用PowerShell发送命令并收集结果时(仅显示捕获结果的部分),它只捕获邮箱的名称。我假设它只返回一个字符串到结果集合,而不是邮箱对象。

如何捕获其余的属性呢?

谢谢!

英文:

Using PowerShell I can use

$myMB = Get-Mailbox -Identity "test@test.com"

then I can get any property by using $myMB.PropertyName, i.e.

Write-Host $myMB.Name
Write-Host $myMB.Alias

In C#, using PowerShell, when I send a PowerShell command and then collect the results (just showing the section that captures results below), it just captures the Name of the Mailbox. I'm assuming its just returning a string to the results collection, not the MB Object.

Collection<PSObject> results = ps.Invoke();
foreach (PSObject result in results)
{
 Debug.Writeline("Result: " + result.ToString());
}

How do I capture the rest of the properties?

Thanks!

答案1

得分: 2

正如您所发现的那样,PowerShell将所有内容都包装在PSObject包装类型中。

属性(无论是通过PowerShell的自身类型系统层动态添加的,还是只是包装的.NET实例的一部分)都通过Properties字典公开:

foreach (PSObject result in results)
{
    Debug.Writeline("邮箱属于邮箱数据库:" + result.Properties["Database"].ToString());
}
英文:

As you've found, PowerShell wraps everything in the PSObject wrapper type.

Properties (whether dynamically added through PowerShell's own type system layer, or simply part of a wrapped .NET instance) are exposed via the Properties dictionary:

foreach (PSObject result in results)
{
    Debug.Writeline("Mailbox belongs to mailbox database: " + result.Properties["Database"].ToString());
}

huangapple
  • 本文由 发表于 2023年7月28日 02:18:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定