Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make PowerShell think an object is not enumerable

Tags:

powershell

I've been working on some PowerShell functions to manage objects implemented in an assembly we have created. One of the classes I have been working with implements IEnumerable. Unfortunatly, this causes PowerShell to unroll the object at every opportunity. (I can't change the fact that the class implements IEnumerable.)

I've worked around the problem by creating a PSObject and copying the properties of our custom object to the PSObject, then returning that instead of the custom object. But I'd really rather return our custom object.

Is there some way, presumably using my types.ps1xml file, to hide the GetEnumerator() method of this class from PowerShell (or otherwise tell PowerShell to never unroll it).

like image 397
OldFart Avatar asked Oct 14 '10 15:10

OldFart


People also ask

What is @() in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

What is PSCustomObject PowerShell?

PSCustomObject is a great tool to add into your PowerShell tool belt. Let's start with the basics and work our way into the more advanced features. The idea behind using a PSCustomObject is to have a simple way to create structured data. Take a look at the first example and you'll have a better idea of what that means.

How do you clear an array in PowerShell?

array . Clear() Sets all item values to the default value of the array's item type.

How do you initialize an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.


1 Answers

Wrapping in a PSObject is probably the best way.

You could also explicitly wrap it in another collection—PowerShell only unwraps one level.

Also when writing a cmdlet in C#/VB/... when you call WriteObject use the overload that takes a second parameter: if false then PowerShell will not enumerate the object passed as the first parameter.

like image 103
Richard Avatar answered Oct 16 '22 05:10

Richard