繁体   English   中英

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

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

在 C# 中,我尝试使用以下命令获取计算机的 IP 地址(该命令在 PowerShell 中运行良好,并且确实显示了 IP 地址):

在 PowerShell 中:

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

PowerShell Output:

{1.2.3.4}
{5.6.7.8}

当我转身尝试从 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的值为“System.String[]”,而不是实际的 IP 地址值。 但 objProperties.Name 成功返回键名“IPAddress”。

如何获取实际的 IP 地址而不是“System.String []”?

如对问题的评论中所述,这种情况下的解决方法是:

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

暂无
暂无

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

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