获取PowerShell响应

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

C# obtaining Powershell responses

问题

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

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

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

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

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

如何捕获其余的属性呢?

谢谢!

英文:

Using PowerShell I can use

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

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

  1. Write-Host $myMB.Name
  2. 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.

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

How do I capture the rest of the properties?

Thanks!

答案1

得分: 2

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

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

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

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:

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

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:

确定