Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Created October 24, 2021 23:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinGrote/cbb0d9285c023574ec85495d0ffc64e1 to your computer and use it in GitHub Desktop.
Save JustinGrote/cbb0d9285c023574ec85495d0ffc64e1 to your computer and use it in GitHub Desktop.
A version of Add-Type for F# in PowerShell
namespace AddFSharpType
module AddFSharpType =
open System.IO
open FSharp.Compiler.CodeAnalysis
open System
/// This is basically the compiler so we name it that way
let compiler = FSharpChecker.Create()
let AddFromFile (sourceFile : string) =
let destination = "ThisIsIgnoredForDynamicAssemblyCompliation.dll"
let initializeOpts = Some(stderr, stdout)
let errors, exitCode, assembly =
compiler.CompileToDynamicAssembly([|
"fsc.dll"
"--noframework"
"-a"; sourceFile
"-o"; destination
"-I"; "C:/Users/JGrote/Projects/FSharp/out"
"-I"; "C:/Program Files/dotnet/sdk/6.0.100-rc.2.21505.57/Microsoft/Microsoft.NET.Build.Extensions/net461/lib"
|], initializeOpts)
|> Async.RunSynchronously
// TODO: Better error handling
if exitCode > 0 then raise (InvalidOperationException(errors.[0].ToString()))
assembly.Value
let AddType (typeDefinition : string) =
let tempName = Path.GetTempFileName()
let tempFile = Path.ChangeExtension(tempName, ".fsx")
File.WriteAllText(tempFile, typeDefinition)
AddFromFile(tempFile)
/// The PowerShell Cmdlet to implement the above
open System.Management.Automation
[<Cmdlet("Add", "FSharpType")>]
type AddFSharpTypeCommand () =
inherit PSCmdlet ()
[<Parameter>]
member val TypeDefinition : string = "" with get, set
override this.EndProcessing() =
let assembly = AddFSharpType.AddType(this.TypeDefinition)
this.WriteObject(assembly)
base.EndProcessing()
@JustinGrote
Copy link
Author

{943CACF8-276F-4821-AAF8-1309FE83178C}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment