首先,我们定义一个函数 Compiler-FSharp,有两个参数,一个是 F# 源代码,当然是必须的;另一个是必须的引用,这是可选的。
然后,调用这个函数。
Function Compiler-FSharp
([string]
$fSharpCode,[Array]$References)
{
#
判断 Powershell 的版本
$is32=
$PSHOME.Contains("SysWOW64")
$isAMD64= ($env:PROCESSOR_ARCHITECTURE).Contains("AMD64")
#
增加 Path 等
if ($isAMD64)
{
$env:Path=$env:Path+";C:\ProgramFiles
(x86)\Microsoft SDKs\F#\4.0\Framework\v4.0"
Add-Type-Path"C:\ProgramFiles (x86)\ReferenceAssemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"
if($is32)
{
$ra= "C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll"
}
else
{
$ra= "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll"
}
}
else
{
if($is32)
{
$env:Path=
$env:Path+
";C:\ProgramFiles (x86)\Microsoft SDKs\F#\4.0\Framework\v4.0"
Add-Type-Path"C:\ProgramFiles (x86)\ReferenceAssemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"
}
else
{
$env:Path=
$env:Path+
";C:\ProgramFiles\Microsoft SDKs\F#\4.0\Framework\v4.0"
Add-Type-Path"C:\ProgramFiles\ReferenceAssemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"
}
$ra="C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll"
}
if ($references.Count
-ge 1)
{
$ra.AddRange($References)
$references
| % {
Add-Type -Path
$_ -ErrorAction
SilentlyContinue}
}
#
加载 FSharp.Compiler.CodeDom.dll
Add-Type-Path
C:\FSharpPowerPack-4.0.0.0\bin\FSharp.Compiler.CodeDom.dll
$provider=New-ObjectMicrosoft.FSharp.Compiler.CodeDom.FSharpCodeProvider
$fSharpCode=Get-Content"C:\Users\tmx\Desktop\loop.fs"|
Out-String
$fSharpType=Add-Type
-TypeDefinition$fSharpCode-CodeDomProvider$provider-ReferencedAssemblies$ra-ErrorActionIgnore-PassThru|where
{ $_.IsPublic }
$fSharpType
<#
-CompilerParameters
$cp = New-ObjectSystem.CodeDom.Compiler.CompilerParameters
$cp.CompilerOptions= "--platform:x86"
#>
}
调用 Compiler-FSharp。
Compiler-FSharp $fSharpCode
后面就可以调用在 F# 源代码中定义的函数了,比如:
[Test]::HelloWorld
[Test]::Loop(10)
[Test]::factorial(10)
=========================
附:F# 源代码。
$fSharpCode [email protected]"
module Test
let HelloWorld =
"Hello World!!!!"
printfn "%s" HelloWorld
let rec Loop n =
seq [
if n <= 0 then
()
else
yield n;
yield! Loop (n-1)
] |> Seq.sort
printfn "%A" (Loop 5)
let rec factorial x =
if x = 0 then 1
else x * (factorial (x - 1))
"@
如果,源代码是保存在文件中的,也可以这样:
$fSharpCode= Get-Content"C:\Scripts\TestCompilerFSharp.fs"
|Out-String
初步解决《powershell 的版本所引起的加载 FSharp 编译器问题》