C# 和 Powershell 3.0 对象

标签 c# powershell iscsi

我不知道如何用摘要来介绍这个问题,所以我会直接解释一下。

我目前正在 C# 应用程序中实现一些依赖于执行各种 powershell 命令的功能。准确地说,我正在尝试从 Windows Server 2012 iSCSI 目标功能中检索服务器目标列表。

PS 命令是 Get-IscsiServerTarget,作为示例,它返回以下输出:

Id                          : Server0.contoso.local:SQLTarget 
TargetName                  : SQLTarget 
TargetIqn                   : iqn.1991-05.com.microsoft:server0-sqltarget-target
Description                 : 
Enable                      : True 
Status                      : Idle 
LastLogin                   : 12/31/1600 4:00:00 PM 
EnableChap                  : False 
EnableReverseChap           : False 
ComputerName                : Server0.contoso.local 
MaxReceiveDataSegmentLength : 65536 
FirstBurstLength            : 65536 
MaxBurstLength              : 262144 
ReceiveBufferCount          : 10 
EnforceIdleTimeoutDetection : True 
InitiatorIds                : {IPAddress:10.1.1.3} 
LunMappings                 : {TargetName:SQLTarget;WTD:2;LUN:0} 
Version                     : 3.3.16543 
ServerInfo                  : Server0.contoso.local

The PSObject collection that returns after invoking the command on the pipeline is a collection of Microsoft.Iscsi.Target.Commands.IscsiServerTarget objects, which is all well and good as I can access all the properties that are primitive types. My problem is that LunMappings is of type Microsoft.Iscsi.Target.Commands.LunMapping and I can't find a way to access the properties of this particular object.

Calling ToString() on the property results in a string equaling "Microsoft.Iscsi.Target.Commands.LunMapping[]" - which is obviously not what I want.

In my mind what I want to do is

psobject[index].Properties["LunMappings"].Properties["Lun"]

((Microsoft.Iscsi.Target.Commands.LunMapping[])psobject[index].Properties["LunMappings"]).Lun

我已经尝试了最后一个,在引用了必要的程序集之后,但我收到了编译错误。

如果有任何指导、指导或建设性意见,我将不胜感激。

编辑 在项目中放置对 Microsoft.Iscsi.Target.Commands.dll 的引用以允许转换 PSObject ((Microsoft.Iscsi.Target.Commands.LunMapping[])psobject[index].Properties["LunMappings"]).Lun 导致编译错误 - 错误 4 The type or namespace name 'Iscsi' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?).

编辑

现在已经解决了这个问题。第一次编辑提到的错误4问题,我尝试投的时候,是因为项目针对的是3.5的框架,引用的程序集需要4.0的。现在我可以成功转换对象了。

最佳答案

LunMappings 属性是 LunMapping 对象的数组,因此您首先需要转换为该数组类型。完成后,您需要访问数组的一些索引,此时您可以访问 .Lun 属性

var arr = (Microsoft.Iscsi.Target.Commands.LunMapping[])psobject[index].Properties["LunMappings"];
arr[0].Lun;

关于C# 和 Powershell 3.0 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17436453/

相关文章:

linux - iscsiadm : Login I/O error, 接收 PDU 失败

windows - 如何在 Windows 中以编程方式挂载原始 iSCSI 卷并准备使用?

c# - 在 Saucelabs 中使用 selenium c# 进行浏览器扩展测试

c# - 创建表查询

java - Powershell环境设置

sql-server - 导入模块 : The specified module 'SqlServer' was not loaded because no valid module file was found in any module directory

Powershell 检查 OU 是否存在

c# - C# 中的内联/速记类型

c# - 如何从非控制台应用程序项目写入控制台

c# - iSCSI 驱动器的 DriveInfo