blog: Creating Custom Objects with “Select-Object”
Once you grab a hold of the "Object" concept in Powershell it brings a whole new light to scripting. The power that is at your finger tips is basically limitless, but to harness this power you not only need to know how to use objects but also create them as well.
Here is my way of creating objects.
Effectively what happens is you set your $myobj to a empty string and pipe to select-object. While this may seem odd, its actually quite useful because what select-object returns is a PSCustomObject with the properties that you specify. This allows you to create you object with defined properties that you can fill out later in one line.
The "proper" way to create a custom object is to do this.
If you pipe Get-ChildItem to Get-member you get tons of methods and properties for both System.IO.FileInfo and System.IO.DirectoryInfo
Here is my way of creating objects.
IMO this is the simplest way to create custom objects.
$myobj = ""| select-Object Server,Result
Effectively what happens is you set your $myobj to a empty string and pipe to select-object. While this may seem odd, its actually quite useful because what select-object returns is a PSCustomObject with the properties that you specify. This allows you to create you object with defined properties that you can fill out later in one line.
The "proper" way to create a custom object is to do this.
While this isn't that much more work... I think its harder to read (and more typing) so I go with this shortcut
$myobj = new-object System.Object $myobj | add-member -membertype noteproperty -name Server -value $sname $myobj | add-member -membertype noteproperty -name Result -value $sResult
I will give you one warning about select-object (not related, but while I'm on this subject.) select-object does Change the object type and therefore you lose methods and properties you may expect to be there. I have seen numerous post on the news groups that have this exact problem.
$myobj = "" | select-Object Server,Result $myobj.Server = $sname $myobj.Result = $sResult
If you pipe Get-ChildItem to Get-member you get tons of methods and properties for both System.IO.FileInfo and System.IO.DirectoryInfo
Now pipe it to select-object and do a Get-Member
PS> get-childitem | gm
Just be careful to remember this. I actually avoid using select-object to filter objects simply because of this. Instead... I just use the properties.
PS> (get-childitem | select-object Fullname,length) | gm TypeName: System.Management.Automation.PSCustomObject 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() FullName NoteProperty System.String FullName=C:WindowsSystem32409 length NoteProperty length=null
tshell :: Jun.04.2009 :: Active Directory, All :: No Comments »

