I was following along with a book about WMI and Powershell, and it explains how to create a custom class in Powershell. It involves writing some C# code, and the add-type command. When I try to create multiple entries in the object with the += command, I get the following error:
Method invocation failed because [pawobject] doesn't contain a method named 'op_Addition'.
At line:23 char:14
+ $MyObjects += <<<< $MyObject
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
The code I am using to create the class is this:
$source = @"
public class pawobject
{
public string Description { get; set; }
public string Name { get; set; }
public int Number { get; set;}
}
"@
And to add it to PowerShell I use the following:
Add-Type $source -Language CSharpVersion3
The code to create a value is this:
$MyObject = New-Object -TypeName pawobject -Property @{
Name = "MyObject5";
Number = 200;
Description = "Take3"
}
This creates a single $MyObject. From here is where my problems come. I tried to create the object with multiple entries like this:
$MyObjects += $MyObject
But I get the above error. I have tried
$MyObjects = $MyObjects + $MyObject
I looked around online, and tried adding the following code the the public class:
public static string Add(string a, string b) {
return (a + b);
}
But that seems to only work with numbers. I am not familiar at all with C#, so I’m not even sure where to start looking to fix this error. I can see this being very useful, as I am always creating new objects in my environment. Being able to define our own types would be a tremendous advantage, especially being able to control what type of data can get put into each property. Thank you in advance, have a great day!
Edit: Let me explain what I want the results to do.
I want to be able to declare something like this this:
$MyObject = New-Object -TypeName pawobject -Property @{
Name = "MyObject";
Number = 100;
Description = "Take1"
}
When I take the output of $MyObject I end up with this:
Description Name Number
----------- ---- ------
Take1 MyObject 100
I would like to then be able to declare this:
$MyObjects += $MyObjects
And end up with $MyObjects having this:
Description Name Number
----------- ---- ------
Take1 MyObject 100
Take2 MyObject5 200
Basically adding (not sure of the technical term for adding two sets of objects) the $MyObject to $MyObjects
It’s interpretting it as adding two objects together
I think in c# you would need to implement the operate like this:
I’m not sure that this is actually what you want to do though. It seems like you want to create an array of objects.
I’ve tested this out and it does create an array of objects.
You need to make sure the operator knows what it’s adding together. There’s no declaration of variable type so to create the array I’m using the return type of adding 2 together.
Hope this helps