我正在开发一个将定制的 c# .DLL 集成到 powershell 中的项目。但是,我在将 C# 对象转换为 PowerShell 可以理解的形式时遇到问题。我已经在谷歌上搜索了一百万次并尝试了一些不同的东西,但没有一个是成功的。
当我使用对象数组调用 SNC-getVlan 时,会发生以下错误:
“使用“1”参数调用“printObject”的异常:“无法将'System.Management.Automation.PSObject'类型的对象转换为'Objects.blablazz.DC_Object'”
我正在发布我的代码的一些小子集,希望你们能看到我做错了什么。
我正在使用的课程:
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 上不起作用,SNC-Get-Vlan 返回一个值数组,而 SNC-getHost 只返回一个值(它仍在虽然是一个数组,但它看起来不像 PowerShell 将它保存在一个数组中)。