Creating objects with a cast in PowerShell 3.0

April 19, 2012

18 comments

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.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

18 comments

  1. ChamblissDecember 18, 2012 ב 20:21

    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.

    Reply
  2. FeltonDecember 19, 2012 ב 05:27

    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.

    Reply
  3. FisherMarch 3, 2013 ב 20:25

    Thank you for your great post! It has long been really valuable.
    I hope that you will proceed sharing your wisdom with us.

    Reply
  4. BlancoMarch 17, 2013 ב 08:41

    The article posted was very informative and valuable.
    You folks are performing a fantastic job. Keep going.

    Reply
  5. AyresMarch 20, 2013 ב 06:31

    Thank you for your wonderful post! It has long been very useful.
    I hope which you will proceed sharing your wisdom with us.

    Reply
  6. HayMarch 20, 2013 ב 06:56

    The write-up posted was quite informative and helpful.
    You individuals are performing a terrific job. Keep going.

    Reply
  7. TompkinsMarch 22, 2013 ב 10:23

    Thank you for your great post! It has long been very valuable.
    I hope that you will proceed sharing your wisdom with us.

    Reply
  8. GrierMarch 22, 2013 ב 11:20

    The post posted was quite informative and beneficial.
    You people are performing an excellent job. Keep going.

    Reply
  9. SpinksMarch 24, 2013 ב 19:21

    Thank you for your fantastic post! It has long been extremely helpful.
    I hope which you will proceed sharing your wisdom
    with us.

    Reply
  10. LassiterMarch 25, 2013 ב 15:16

    A genuinely fascinating read, I might well not agree
    entirely, but you do make some quite legitimate points.

    Reply
  11. DoyleMarch 31, 2013 ב 15:30

    A genuinely fascinating read, I might well not agree entirely,
    but you do make some quite legitimate points.

    Reply
  12. SpragueMarch 31, 2013 ב 17:22

    Thank you for your amazing post! It has long been very helpful.
    I hope that you will proceed sharing your wisdom with us.

    Reply
  13. CristApril 20, 2013 ב 20:53

    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?

    Reply
  14. RicheyApril 21, 2013 ב 21:30

    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.

    Reply
  15. CrittendenApril 21, 2013 ב 23:39

    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.

    Reply
  16. KeenanMay 2, 2013 ב 16:24

    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?

    Reply
  17. KeeMay 2, 2013 ב 17:22

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

    Reply
  18. MccloskeyJune 30, 2013 ב 20:57

    I blog frequently and I truly thank you for your content.
    This great article has truly peaked my interest.

    I’m going to book mark your blog and keep checking for new details about once a week. I opted in for your Feed too.

    Reply