-
PowerShell 2.0: One Cmdlet at a Time #107 Add-Type
Posted on June 30th, 2010 3 commentsContinuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Add-Type cmdlet.
What can I do with it?
Imbed code from modern programming languages into your PowerShell session or scripts. The list of valid languages are: C#, C# 3.0, VisualBasic and JScript – C# is the default. Use the Language parameter to specify one if it is not C#.
Example:
Within a PowerShell session use some C# code to create a TakeAway class and create a static method Minus. Use the Add-Type cmdlet to add the class to the session and then call the TakeAway class and Minus static method.
$csharp = @" public class TakeAway { public static int Minus(int a, int b) { return (a - b); } } "@ Add-Type -TypeDefinition $csharp [TakeAway]::Minus(10,7)
You will see that we get the expected answer of 3:
How could I have done this in PowerShell 1.0?
PowerShell 1.0 did not support adding C# or other code into PowerShell scripts, you could however have created your own cmdlet which I’m sure would have been very straightforward for most sysadmins
2 responses to “PowerShell 2.0: One Cmdlet at a Time #107 Add-Type”

-
Another great post in the series !
This is indeed a great new cmdlet in PS v2. I used it in my http://www.lucd.info/2010/04/09/lun-report-datastores-rdms-and-node-visibility/ post.
Only drawback, there is no Remove-Type.
Once you defined a new type you can’t get rid of it, except when you stop/start the session.
1 Trackbacks / Pingbacks
-
[...] a good powershell Cmdlet explanation: now we are at 107 on Jonathan Medd’s Powershell BLOG: http://www.jonathanmedd.net/2010/06/powershell-2-0-one-cmdlet-at-a-time-107-add-type.html [...]
Leave a reply
-









LucD August 1st, 2010 at 15:42