PowerShell and the dynamic keyword in C# 4.0

March 7, 2009

in IronPython,IronRuby,JSON,PSMDTAG:FAQ C# 4.0,PowerShell

The dynamic keyword in C# 4.0 simplifies the interaction with PowerShell variables. C#’s var keyword casts the GetVariable as an object and needs additional code to cajole the object array into a shape that could be worked with.

The embedded PowerShell below creates 4 variables.

  • $a – An array of ints piped through a where and foreach
  • $b – A hash table
  • $c – A simple array
  • $d – A string

Printing the string variable results in printing each character.

Next up, using PowerShell’s Add-Member to add a NoteProperty, ScriptProperty and ScriptMethod to a PowerShell object and doing late-bound access in C#. I’ve experimented a bit but no success.

image

image

Results

image

Some References

Using the dynamic keyword is being experimented with other dynamic languages and other ways.

{ 1 comment… read it below or add one }

Frederic Torres 12.30.11 at 10:45 pm

I think I solved what you were trying to do with C#, PowerShell and the keyword dynamic.
See my post
Running PowerShell from C# with a hint of dynamic.

But I was wandering if may be there was an easier solution like with IronPython.

Leave a Comment

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

Contrat Creative Commons

© 2007-2012, Doug Finke