我正在进行一个项目,将定制的c# .DLL集成到powershell中。但是,在将C#对象转换为PowerShell无法理解的表单时,我遇到了问题。我搜索过谷歌上百万次,尝试过一些不同的东西,但都没有成功。
当我使用对象数组调用SNC时,会发生以下错误:
调用带有"1“参数的"printObject”的“异常”:“无法将'System.Management.Automation.PSObject‘类型的对象强制转换为printObject类型
我正在张贴一些我的代码的小子集,希望你们能看到我做错了什么。
我正在使用的课程:
public class DC_Object
{
public string name = "undefined";
}
public class Cmdb_Host : DC_Object
{
//Lots of properties
}
public class Cmdb_Vlan : DC_Object
{
//Lots of properties
}函数,该函数打印对象:
public static void printObject(Object[] objects)
{
foreach (Object o in objects)
{
string name = ((DC_Object)o).name; //I'm assuimg things go wrong in here.fromJSON函数实际上是返回发送到printObject中的对象的函数,不确定它是否重要,但无论如何我都会发布它。
static public Object[] fromJSON(string input)
{
//Check the string to see to what object it should convert to
switch (input.Substring(0, 16))
{
//Reuest for a host (Host Table)
case "{\"u_cmdb_ci_host":
if (input[18] == '[') // We have an array
{
Container_Host c_host = JsonConvert.DeserializeObject<Container_Host>(input);
return c_host.u_cmdb_ci_host;
}
else // We have a single object
{
Container_Host_Single c_host = JsonConvert.DeserializeObject<Container_Host_Single>(input);
Container_Host h = new Container_Host();
h.u_cmdb_ci_host = new Cmdb_Host[1];
h.u_cmdb_ci_host[0] = c_host.u_cmdb_ci_host;
return h.u_cmdb_ci_host;
}
//Request for a VLAN (Network Table)
case "{\"cmdb_ci_ip_net":
Container_Vlan c_vlan = JsonConvert.DeserializeObject<Container_Vlan>(input);
return c_vlan.cmdb_ci_ip_network;
}
return null;
}Powershell模块/脚本:
#Loads in the custom DLL created for this specific project.
[Reflection.Assembly]::LoadFrom(“C:\Users\Joey\Documents\PSScripts\DataCollector\DataCollect.dll”)
# Creates a new Client object that handles all communication between the PowerShell module and the
# sncdb-worker at server side.
$client = new-object blablazzz.Sender;
[blablazzz.Config]::Configure("C:\Users\Joey\Documents\PSScripts\DataCollector\asp4all.ini")
$client.Connect();
# This functions returns a Host Machine (Virtual or Physical) in object notation to for easy post-processing
# in PowerShell.
Function SNC-GetHost($hostz = "blabla")
{
return $client.sendMessage([blablazzz.Parser]::getHost($hostz));
}
# This function returns VLAN information in object notation. This is a collection most of the time.
function SNC-GetVLAN($vlan = "TLS-TL2-CPH-TEST")
{
return $client.sendMessage([blablazzz.Parser]::getVlan($vlan));
}
Function printObject($hostz)
{
[blablazzz.Formatter]::printObject($hostz)
}PowerShell命令(dll已经加载):
PS C:\$variable = SNC-Get-VLAN
PS C:\printObject($variable)我必须指出,我的printDebug函数在SNC-getHost上使用时运行良好,但在SNC-getVlan上不起作用,still返回一个值数组,而SNC只返回一个值(虽然它仍然在数组中,但看起来不像PowerShell将其保存在数组中)。
发布于 2012-08-14 06:15:35
对于那些可能遇到同样问题的人来说。解决方案是将函数的返回值和参数更改为DC_Object,因为这是最顶层的封装对象。这解决了所有的铸造问题。
https://stackoverflow.com/questions/11650583
复制相似问题