简体   繁体   English

在 C# PSObject PSPropertyInfo 不返回值时 PS 命令行确实返回值

[英]In C# PSObject PSPropertyInfo does not return value when PS command-line does return value

In C# I am trying to get the IPAddresses of my computer using the following command (the command works fine in PowerShell and, indeed, shows IP addresses):在 C# 中,我尝试使用以下命令获取计算机的 IP 地址(该命令在 PowerShell 中运行良好,并且确实显示了 IP 地址):

In PowerShell:在 PowerShell 中:

Get-CimInstance Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" -ComputerName $env:ComputerName | Select -Property IPAddress

PowerShell Output: PowerShell Output:

{1.2.3.4}
{5.6.7.8}

When I turn around and attempt to get the value (stored in results) from the PowerShell command in C# like this:当我转身尝试从 C# 中的 PowerShell 命令获取值(存储在结果中)时,如下所示:

foreach (PSObject obj in results) {

    foreach (PSPropertyInfo objProperties in obj.Properties) {

        string pName = objProperties.Name.ToString(); // returns "IPAddress"

        **string pValue = objProperties.Value.ToString(); // returns "System.String[]" and not an actual IP address**

    }

}

pValue has a value of "System.String[]" and not the actual IP address value. pValue的值为“System.String[]”,而不是实际的 IP 地址值。 But objProperties.Name successfully returns the key-name "IPAddress".但 objProperties.Name 成功返回键名“IPAddress”。

How can I get the actual IP Address instead of "System.String[]"?如何获取实际的 IP 地址而不是“System.String []”?

The fix in this scenario, as noted in the comments to the question, is:如对问题的评论中所述,这种情况下的解决方法是:

((string[])objProperties.Value).First()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM