August 26, 2015

PowerShell - Create Custom Objects

PowerShell allows you to return structured results from a command so that users can easily sort, group, and filter them. You can create Custom Objects with required properties or methods. Lets explore how to create the objects.

There are different methods you can create Custom Objects.

1. Add-Member cmdlet, a cmdlet that allows us to add properties to an object. In this case we’re adding a NoteProperty, giving our property the name Name and a value that represents the Name property.

$object = New-Object System.Object

$object | Add-Member –MemberType NoteProperty –Name Id –Value 1
$object | Add-Member –MemberType NoteProperty –Name Code –Value "I001"
$object | Add-Member –MemberType NoteProperty –Name Name –Value "Laptop"

Write-Output $object

2. You can assign a hash table to the object to quickly create the objects properties. This can be very useful if you have a list of name/value pairs.

$props = @{
Id = 1
Code = 'I001'
Name = 'Laptop'
}
$object = new-object psobject -Property $props

Write-Output $object

3. Or a shorter alternative like this:

$object = [PSCustomObject]@{
Id = 1
Code = 'I001'
Name = 'Laptop'
}

Write-Output $object

4. New-Module with the AsCustomObject parameter creates a custom object.

$object = New-Module -AsCustomObject -ScriptBlock {
[int]$Id=1 
[string]$Code='I001'
[string]$Name='Laptop'
Export-ModuleMember -Variable *
}

Write-Output $object

5. You can using Add-Type to compile C# or other .NET languages, and in this way you can make a real class definition.

Add-Type @"
    using System;
    public class myClass{

        public int Id=0;
        public string Code="";
        public string Name="";

    }
"@

$object = New-Object myClass
$object.Id = 1
$object.Code = "I001"
$object.Name = "Laptop"

Write-Output $object

6. This method is a quick way of gathering data to be manipulated.

$object = "" | select Id, Code, Name
$object.Id = 1
$object.Code = "I001"
$object.Name = "Laptop"

Write-Output $object

References:
https://technet.microsoft.com/en-us/library/ff730946.aspx
http://social.technet.microsoft.com/wiki/contents/articles/7804.powershell-creating-custom-objects.aspx

No comments:

Post a Comment