teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追記

2016/08/31 14:06

投稿

Zuishin
Zuishin

スコア28675

answer CHANGED
@@ -1,2 +1,58 @@
1
1
  [PowerShellスクリプトをExeに変換する](http://mtgpowershell.blogspot.jp/2013/03/powershellexe.html)のはどうですか?
2
- または [CSharpCodeProvider クラス](https://msdn.microsoft.com/ja-jp/library/microsoft.csharp.csharpcodeprovider(v=vs.110).aspx)を使えば PowerShell などから C# をコンパイルできます。
2
+ または [CSharpCodeProvider クラス](https://msdn.microsoft.com/ja-jp/library/microsoft.csharp.csharpcodeprovider(v=vs.110).aspx)を使えば PowerShell などから C# をコンパイルできます。
3
+ ###追記
4
+ CSharpCodeProvider と WinAPI を使った例です。
5
+ 下記 Compile-Cs.ps1 と untitled.cs を保存し、PowerShell から `Compile-Cs untitled.cs` としてコンパイルしてください。untitled.exe ができますので、それを実行すると Hello World と表示されるはずです。
6
+ **Compile-Cs.ps1**
7
+ ```
8
+ [CmdletBinding(SupportsShouldProcess = $True)]
9
+ Param (
10
+ [Parameter(
11
+ Mandatory = $True,
12
+ Position = 0
13
+ )]
14
+ [string[]]$Path = @(),
15
+
16
+ [Parameter(
17
+ Mandatory = $False,
18
+ Position = 1
19
+ )]
20
+ [string]$ExeName = "untitled.exe",
21
+
22
+ [Parameter(
23
+ Mandatory = $False
24
+ )]
25
+ [string[]]$Reference = @()
26
+ )
27
+ $compiler = New-Object Microsoft.CSharp.CSharpCodeProvider
28
+ $compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
29
+ if ($Reference.Length -gt 0) {
30
+ $compilerParameters.ReferencedAssemblies.AddRange($Reference)
31
+ }
32
+ $compilerParameters.GenerateInMemory = $False
33
+ $compilerParameters.GenerateExecutable = $True
34
+ $compilerParameters.OutputAssembly = $ExeName
35
+ $results = $compiler.CompileAssemblyFromFile($compilerParameters, $Path)
36
+ if ($results.NativeCompilerReturnValue -ne 0) {
37
+ $results.Output | Write-Host
38
+ exit 1
39
+ } else {
40
+ $results
41
+ }
42
+ ```
43
+ **untitled.cs**
44
+ ```C#
45
+ using System;
46
+ using System.Runtime.InteropServices;
47
+
48
+ static class Program
49
+ {
50
+ [DllImport("msvcrt.dll")]
51
+ static extern int puts(string s);
52
+
53
+ static void Main()
54
+ {
55
+ puts("Hello World!");
56
+ }
57
+ }
58
+ ```