Created
December 8, 2013 03:13
-
-
Save threecourse/7852959 to your computer and use it in GitHub Desktop.
PowershellからC#コードをコンパイル・実行するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# --------------------------------------------------------------------- | |
# PowershellからC#コードをコンパイル・実行するサンプル | |
# | |
# (参考) | |
# http://codezine.jp/article/detail/5007 | |
# | |
# (注意点) | |
# .NET Frameworkの制約上、Add-Typeによる型の追加を再実行するには、Powershellのセッションを切る必要がある。 | |
# そのため、Powershellのプロセスを立ち上げ、その中でコンパイル・実行するようにしている。 | |
# --------------------------------------------------------------------- | |
# 引数の取得 | |
# Python風に、トップレベルであれば$moduleに"__main__"が入るようにしている。 | |
# 他のPowershellプロセスを立ち上げるときには、$moduleに"called"を入れるようにする。 | |
param([string]$module) | |
if($module -eq ""){ $module = "__main__"} | |
# コンパイル・実行を行う関数の定義 | |
function ComplieAndRun(){ | |
# CSharpコードのソース | |
$source=@" | |
public class SampleClass{ | |
public static string SayHello(string Name) | |
{ | |
return "Hello " + Name; | |
} | |
} | |
"@ | |
# CSharpコードのコンパイル | |
Add-Type -Language CSharpVersion3 -TypeDefinition $Source | |
# CSharpコードの実行 | |
[SampleClass]::SayHello("World") | |
} | |
# トップレベルでない場合のみ、コンパイル・実行を行う。 | |
if($module -ne "__main__"){ | |
ComplieAndRun | |
[Console]::ReadKey() | Out-Null # 実行後入力を待つ | |
} | |
# トップレベルの場合は、別のPowershellプロセスを立ち上げ、自身のスクリプトを呼び出す。 | |
if($module -eq "__main__"){ | |
$path = '"' + $Script:MyInvocation.MyCommand.Path + '"' | |
start-process powershell.exe -ArgumentList @("-File", $path, "called") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment