DCSIMG
Creating objects with a cast in PowerShell 3.0 - Shay Levy

Shay Levy

If you repeat it, PowerShell it!

News


btn_donate_LG

View Shay Levy's profile on LinkedIn Follow Shay Levy at Twitter Shay Levy's Facebook profile Subscribe to my FriendFeed


site statistics




Creating objects with a cast in PowerShell 3.0

Starting with PowerShell 3.0, we now have another cool way to create new objects. We can create them by calling the default constructor of the type and initializing its properties with a cast:

[System.Drawing.Point]@{X=1;Y=2}

We put the type in square brackets and assign it a hash table containing the properties we want to initialize. Looking at this example got me thinking, how can I know the properties I can set for a specific class/type? As a learning tool, I wrote the Get-HashType function. Give it a type name and it will tell you the properties you can set.


#requires -Version 3.0
function Get-TypeHash
{
   [CmdletBinding()]
   [OutputType('System.String')]
	
   Param(
      [Parameter(
         Mandatory=$true,
         Position=0,
         ValueFromPipeline=$true,
         ValueFromPipelineByPropertyName=$true)]
      [Alias('FullName')]
      [Type]$TypeName
   )

   process
   {
      try
      {  
         if($TypeName.IsClass -and !$TypeName.GetConstructor([Type]::EmptyTypes))
         {
            throw "Constructor not found. Cannot find an appropriate `
                        constructor for type '$TypeFullName'"
         }


         $TypeFullName = $TypeName.FullName
         $WriteableProperties = $TypeName.GetProperties() | where CanWrite

         if($WriteableProperties.Count -gt 0)
         {         
            $hash = "[$TypeFullName]@{"

            $WriteableProperties | ForEach-Object {
               $hash+="`n`t{0} = <{1}>" -f $_.Name,$_.PropertyType
            }
         
            $hash+"`n}" 
         }
         else
         {
            Write-Warning "No writable properties found for type '$TypeFullName'"
         }    
      }
      catch
      {
         Write-Error $_
      }
   }
}


PS> Add-Type –Assembly System.Drawing
PS> Get-TypeHash –TypeName System.Drawing.Point [System.Drawing.Point]@{ X = <System.Int32> Y = <System.Int32> }

The output includes the writeable properties of the type and their corresponding value type. Copy the output, assign the values and paste it back to the console. This will create the object:

PS> [System.Drawing.Point]@{
>> X = 1
>> Y = 1
>> }
>>
 IsEmpty   X   Y
 -------   -   -
   False   1   1

The function works for types that have a default constructor and for structure types. In the example above, System.Drawing.Point is a structure.

Comments

PowerShell Get-Script -Name Peter Kriegel | Management - PowerShell Get-Script -Name Peter Kriegel | Management said:

Pingback from  PowerShell Get-Script -Name Peter Kriegel  |  Management - PowerShell Get-Script -Name Peter Kriegel | Management

# May 28, 2012 5:04 PM

Chambliss said:

If some one wants to be updated with most up-to-date technologies

then he must be pay a quick visit this web page and be

up to date all the time.

# December 18, 2012 8:21 PM

Felton said:

Estoy seguro de que este párrafo ha tocado a todos los

visitantes de Internet, su párrafo muy, muy bueno en la creación de nueva página web.

# December 19, 2012 5:27 AM

Fisher said:

Thank you for your great post! It has long been really valuable.

I hope that you will proceed sharing your wisdom with us.

# March 3, 2013 8:25 PM

Blanco said:

The article posted was very informative and valuable.

You folks are performing a fantastic job. Keep going.

# March 17, 2013 8:41 AM

Ayres said:

Thank you for your wonderful post! It has long been very useful.

I hope which you will proceed sharing your wisdom with us.

# March 20, 2013 6:31 AM

Hay said:

The write-up posted was quite informative and helpful.

You individuals are performing a terrific job. Keep going.

# March 20, 2013 6:56 AM

Tompkins said:

Thank you for your great post! It has long been very valuable.

I hope that you will proceed sharing your wisdom with us.

# March 22, 2013 10:23 AM

Grier said:

The post posted was quite informative and beneficial.

You people are performing an excellent job. Keep going.

# March 22, 2013 11:20 AM

Spinks said:

Thank you for your fantastic post! It has long been extremely helpful.

I hope which you will proceed sharing your wisdom

with us.

# March 24, 2013 7:21 PM

Lassiter said:

A genuinely fascinating read, I might well not agree

entirely, but you do make some quite legitimate points.

# March 25, 2013 3:16 PM

Doyle said:

A genuinely fascinating read, I might well not agree entirely,

but you do make some quite legitimate points.

# March 31, 2013 3:30 PM

Sprague said:

Thank you for your amazing post! It has long been very helpful.

I hope that you will proceed sharing your wisdom with us.

# March 31, 2013 5:22 PM

Crist said:

I am really loving the theme/design of your internet internet

site. Do you ever run into any browser compatibility troubles?

A few of my blog readers have complained about my site

not working appropriately in Explorer but looks fantastic in Chrome.

Do you've any suggestions to assist fix this issue?

# April 20, 2013 8:53 PM

Richey said:

I have to convey my respect for your kindness for all those that need guidance on this 1 field.

Your special commitment to passing the answer up and down has been extremely functional and

has continually empowered a lot of people just like me to accomplish their dreams.

Your incredible insightful info entails a lot to me

and specially to my peers. Thanks a ton; from all of us.

# April 21, 2013 9:30 PM

Crittenden said:

I've to convey my respect for your kindness for all those that require guidance on this one field. Your particular commitment to passing the answer up and down has been incredibly functional and has continually empowered many people just like me to attain their dreams. Your amazing insightful data entails much to me and specifically to my peers. Thanks a ton; from all of us.

# April 21, 2013 11:39 PM

Keenan said:

I am truly loving the theme/design of your internet site.

Do you ever run into any browser compatibility difficulties?

A few of my blog readers have complained about my

site not working properly in Explorer but looks excellent in Chrome.

Do you might have any guidelines to assist fix this concern?

# May 2, 2013 4:24 PM

Kee said:

I like this weblog so much, saved to my bookmarks .

# May 2, 2013 5:22 PM

Event 2: My notes… | IT Pro PowerShell experience said:

Pingback from  Event 2: My notes&hellip; | IT Pro PowerShell experience

# May 9, 2013 4:57 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: