header image

Creating an object

Posted by: | March 11, 2009 | No Comment |

Jeffrey shows how to create custom objects – http://blogs.msdn.com/powershell/archive/2009/03/11/how-to-create-an-object-in-powershell.aspx

I recently saw a demo by Jonathan Noble where he showed another way

PS> $myobj = "" | Select Name, Price, Description
PS> $myobj.Name = "Test Object"
PS> $myobj.Price = 27.88
PS> $myobj.Description = "Some dodgy bit of stuff"

Now we want to see what we have created

PS> $myobj | fl

Name        : Test Object
Price       : 27.88
Description : Some dodgy bit of stuff

and finally the object itself

PS> $myobj | gm

   TypeName: Selected.System.String

Name        MemberType   Definition
—-        ———-   ———-
Equals      Method       System.Boolean Equals(Object obj)
GetHashCode Method       System.Int32 GetHashCode()
GetType     Method       System.Type GetType()
ToString    Method       System.String ToString()
Description NoteProperty System.String Description=Some dodgy bit of stuff
Name        NoteProperty System.String Name=Test Object
Price       NoteProperty System.Double Price=27.88

What we have done is created a string representing the results of the select.  We can then populate the objects which are NoteProperties. 

This has worked in the places I’ve tried it & I know a number of people who have used this approach successfully.  As with everything – be careful & test as completely as possible.


Technorati Tags: PowerShell,Object

under: PowerShell original