30. December 2008
Andy Schneider
We can use C# quite easily with the Add-Type Cmdlet. With the -language parameter, you can also use VB .NET. However,if you are into functional programming and like F#, you can use that as well, although not quite as easily.
First, go and download the September 2008 CTP of F#. Once you have this installed, launch the 32 bit version of PowerShell. I'm using a 64 bit Vista machine and I had problems with the 64 bit version of Powershell with one line which I will get to in a bit. I think it has to do with the F# CodeDom Provider, not with PowerShell itself.
The F# CodeDom.dll was installed in C:\Program Files (x86)\FSharp-1.9.2.9\bin for me. Your mileage may vary. Anyway, cd into the bin directory of F# and you will find a file called FSharp.Compiler.CodeDom.dll. Once you are there, you can run the following lines to load up the F# Code Provider.
Add-Type -Path FSharp.Compiler.CodeDom.dll
$provider = New-Object Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider
$fsharpCode = @"
let sample = [1;2;3;4;5;6;7]
"@
$fsharpType = Add-Type -TypeDefinition $fSharpCode -CodeDomProvider $provider -PassThru |
where { $_.IsPublic }
$fsharpType::sample
When you call Sample on $fsharpType, it will return the array with numbers 1 through 7.
For some reason when I ran this on a 64 bit I get the following error when I try to add the type with typeDefinition $fsharpCode on line 6
Add-Type : The system cannot find the file specified
At line:6 char:23
+ $fsharpType = Add-Type <<<< -TypeDefinition $fSharpCode -CodeDomProvider $provider -PassThru | where { $_.IsPublic }
+ CategoryInfo : NotSpecified: (:) [Add-Type], Win32Exception
+ FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.AddTypeCommand
If you are into this sort of thing, have fun!