forked from KurtDeGreeff/PlayPowershell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompile-Csharp.ps1
68 lines (63 loc) · 1.98 KB
/
Compile-Csharp.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
##################################################################
# Compiler
##################################################################
function Compile-Csharp ([string] $code, $FrameworkVersion="v4.0.30319")
{
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$framework = [System.IO.Path]::Combine($env:windir, "Microsoft.NET\Framework\$FrameWorkVersion")
$references = New-Object System.Collections.ArrayList
$references.AddRange( @("${framework}\System.dll","${framework}\System.Core.dll"))
$parameters = New-Object System.CodeDom.Compiler.CompilerParameters
$parameters.GenerateInMemory = $true
$parameters.GenerateExecutable = $false
$parameters.ReferencedAssemblies.AddRange($references)
$result = $provider.CompileAssemblyFromSource($parameters, $code)
if ($result.Errors.Count)
{
$codeLines = $code.Split("`n");
foreach ($ce in $result.Errors)
{
write-host "Error: $($codeLines[$($ce.Line - 1)])"
$ce | out-default
}
Throw "Compilation of C# code failed"
}
}
##################################################################
# C# Code
##################################################################
$code = @'
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace CompileTest
{
public class Sound
{
[DllImport("User32.dll", SetLastError = true)]
static extern Boolean MessageBeep(UInt32 beepType);
public static void Beep(BeepTypes type)
{
if (!MessageBeep((UInt32)type))
{
Int32 err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
}
}
}
public enum BeepTypes
{
Simple = -1,
Ok = 0x00000000,
IconHand = 0x00000010,
IconQuestion = 0x00000020,
IconExclamation = 0x00000030,
IconAsterisk = 0x00000040
}
}
'@
##################################################################
# Compile the code and access the .NET object within PowerShell
##################################################################
Compile-Csharp $code
[CompileTest.Sound]::Beep([CompileTest.BeepTypes]::IconAsterisk)