Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Calling PowerShell from CSharp
Search
tanaka_733
December 21, 2013
Technology
2k
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Calling PowerShell from CSharp
第1回PowerShell勉強会で話した資料です
tanaka_733
December 21, 2013
More Decks by tanaka_733
See All by tanaka_733
SRENEXT 2020 [B5] New RelicのSREに学ぶSREのためのNew Relic活用法
tanaka733
2
11k
Garbage Collection in .NET Framework
tanaka733
4
3k
New Features in Visual Studio 2013
tanaka733
0
1.1k
Starting Unity for Windows Store App
tanaka733
0
870
とあるインフラエンジニアのAzure活用
tanaka733
2
620
ぼくの考えた割と普通(c)なデプロイ戦略
tanaka733
1
11k
ASP.NET MVC4 Web APIをバックエンドにして作るストアとWindows Phoneプッシュ通知アプリ
tanaka733
0
1.9k
Yurufuwa_CSharp.pdf
tanaka733
0
5.1k
Windows ストアアプリで Push通知を使いこなそう
tanaka733
0
2k
Other Decks in Technology
See All in Technology
【CEDEC2026】『GRANBLUE FANTASY: Relink - Endless Ragnarok』のバトル制作事例 ~最高のキャラゲーを目指して~
cygames
PRO
0
280
トヨタ⽣産⽅式(TPS)⼊⾨
recruitengineers
PRO
3
760
研究開発部の紹介 / Sansan R&D Profile
sansan33
PRO
4
24k
【CEDEC2026】次世代デジタルカードゲームのサーバー設計と運用 〜『Shadowverse: Worlds Beyond』の舞台裏~
cygames
PRO
1
1.2k
2026-08-05 IBM Z開発最前線!IBM Bob Premium Package for Zって何がすごいの?
yutanonaka
0
110
【CEDEC2026】ゲームシナリオライターを支援するAIツール開発の実践 ― 設計とプロンプトの工夫 ―
cygames
PRO
1
820
その“隠したつもり”が命取り ── 自前と平文をやめて「正解」に委ねる
kuroneko13
0
120
TypeScript入門 2026
recruitengineers
PRO
3
570
同じWAFが、攻撃の“形”は弾く── 正当な“形”の不正は通す
kuroneko13
0
180
認知負荷をGemini で溶かす — GKE 基盤「Orbit」における AI エージェントの実践
sansantech
PRO
1
290
【AG-UI × A2UI × MCP Apps】Generative UIをやさしく解説する
nrinetcom
PRO
1
120
モダンフロントエンド 開発研修
recruitengineers
PRO
4
620
Featured
See All Featured
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.4k
Music & Morning Musume
bryan
47
7.3k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
640
The Limits of Empathy - UXLibs8
cassininazir
1
600
Heart Work Chapter 1 - Part 1
lfama
PRO
8
36k
Being A Developer After 40
akosma
91
590k
Digital Ethics as a Driver of Design Innovation
axbom
PRO
1
360
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
610
Optimising Largest Contentful Paint
csswizardry
37
3.9k
Done Done
chrislema
186
16k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
141
35k
Building an army of robots
kneath
306
46k
Transcript
None
仕事 個人 http://tech.tanaka733.net http://www.buildinsider.net/web/iis8
PowerShell そのものの内容は薄いです。たぶん。予定は未定 PowerShell をC# から実行したい! • C# というか .NET Framework
からですが、コードはC# のみです • 通常の外部プロセス実行だと落とし穴が • コマンドパイプラインも使いたい • リモートコンピューターにも実行したい 最後におまけが!? 資料と出てくるソースコードは今日中に公開します
None
https://speakerdeck.com/tanaka733/bokufalsekao-etage- topu-tong-c-nadepuroizhan-lue
None
None
None
static void Main(string[] args) { var psInfo = new ProcessStartInfo
{ FileName = "powershell.exe", CreateNoWindow = true, UseShellExecute = false, Arguments = "Get-ChildItem", RedirectStandardOutput = true }; var p = Process.Start(psInfo); Console.WriteLine(p.StandardOutput.ReadToEndAsync().Result); Console.ReadKey(); }
None
None
DEMO
using (var rs = RunspaceFactory.CreateRunspace()) { rs.Open(); using (var ps
= PowerShell.Create()) { ps.Runspace = rs; ps.AddCommand("Get-Service"); ps.Invoke() .Select(result => string.Format("{0} {1}", result.Properties["Status"].Value, result.Properties["Name"].Value)) .ToList() .ForEach(Console.WriteLine); } }
using (var rs = RunspaceFactory.CreateRunspace()) { rs.Open(); using (var ps
= PowerShell.Create()) { ps.Runspace = rs; ps.AddCommand("Get-Service"); ps.Invoke() .Select(result => string.Format("{0} {1}", result.Properties["Status"].Value, result.Properties["Name"].Value)) .ToList() .ForEach(Console.WriteLine); } }
//これでもプロパティ取得できます ps.Invoke() .Select(result => result.BaseObject) .Cast<dynamic>() .Select(result => string.Format("{0} {1}",
result.Status, result.ServiceName)) .ToList() .ForEach(Console.WriteLine);
None
None
DEMO
using (var ps = PowerShell.Create()) { ps.Runspace = rs; ps.AddCommand("Get-Process");
ps.AddArgument("chrome"); ps.AddCommand("Sort-Object"); ps.AddParameter("Descending"); ps.AddArgument("CPU"); var results = ps.Invoke(); results.Select(result => string.Format("{0} {1} {2}", result.Properties["Id"].Value, result.Properties["ProcessName"].Value, result.Members["CPU"].Value)) .ToList() .ForEach(Console.WriteLine); }
None
None
http://msdn.microsoft.com/ja- jp/library/system.management.automation.psmembertypes(v=vs.8 5).aspx
http://msdn.microsoft.com/ja- jp/library/system.management.automation.runspaces.runsp ace.defaultrunspace(v=vs.85).aspx using (var rs = RunspaceFactory.CreateRunspace()) { //
これが必要※1 Runspace.DefaultRunspace = rs; rs.Open(); using (var ps = PowerShell.Create()) { ps.Runspace = rs;
//これでもプロパティ取得できます results.Select(result => result.BaseObject) .Cast<Process>() .Select(result => string.Format("{0} {1} {2}",
result.Id, result.ProcessName, result.TotalProcessorTime.TotalSeconds)) .ToList() .ForEach(Console.WriteLine);
None
None
アプリ(powershell.exe, PowerShell ISE, あなたのアプリ)
None
DEMO
None
None
DEMO
var connectionInfo = new WSManConnectionInfo() { Scheme = "https", ComputerName
= "servername.cloudapp.net", Port = 7654, Credential = new PSCredential("username", "syoboipassword".Aggregate( new SecureString(), (s, c) => { s.AppendChar(c); return s; })), SkipCACheck = true }; using (var rs = RunspaceFactory.CreateRunspace(connectionInfo)) {//以下略
None
None
//connectionInfoは同じ using (var rsPool = RunspaceFactory.CreateRunspacePool(1, 2, connectionInfo)) { rsPool.Open();
var gpsCommand = PowerShell.Create().AddCommand("Get-Process"); gpsCommand.RunspacePool = rsPool; var gpsCommandAsyncResult = gpsCommand.BeginInvoke(); var getServiceCommand = PowerShell.Create().AddCommand("Get-Service"); getServiceCommand.RunspacePool = rsPool; var getServiceCommandAsyncResult = getServiceCommand.BeginInvoke(); var gpsCommandOutput = gpsCommand.EndInvoke(gpsCommandAsyncResult); //出力は省略 var getServiceCommandOutput = getServiceCommand.EndInvoke(getServiceCommandAsyncResult); //出力は省略 rsPool.Close(); }
DEMO
None
None
None
None
$source = @" using System; //中略 public class Program {
//[STAThread] <= 昔は必要だったらしいけど、v3かv4からいらなくなった (デフォルトSTA) public static void Run(string xaml) { var app = new Application(); var window = (Window)XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml))); app.Run(window); } } "@ Add-Type -ReferencedAssemblies $assemblies ` -TypeDefinition $source -Language Csharp [Program]::Run($xaml)
$assemblies = ( "System", "PresentationCore", "PresentationFramework", "System.Windows.Presentation", "System.Xaml", "WindowsBase", "System.Xml"
)
$xaml = @" <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title=“XamClaudiaPS1" Height="350" Width="525"> <Window.Resources>
<!– 中略 --> </Window.Resources> <Grid> <!– 中略 --> </Grid> </Window> "@ https://github.com/Grabacr07/XamClaudia
$signature = @" [DllImport("kernel32.dll", SetLastError = true)] public static extern
Boolean GetSystemPowerStatus(out SystemPowerStatus sps); public struct SystemPowerStatus { public Byte ACLineStatus; public Byte BatteryFlag; public Byte BatteryLifePercent; public Byte Reserved1; public Int32 BatteryLifeTime; public Int32 BatteryFullLifeTime; } "@ Add-Type -MemberDefinition $signature -Name PowerStatus -Namespace PowerStatus $systemPowerStatus = New-Object PowerStatus.PowerStatus+SystemPowerStatus [void][PowerStatus.PowerStatus]::GetSystemPowerStatus([ref]$systemPowerStatus) $systemPowerStatus
None
None
http://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx https://github.com/tanaka-takayoshi/PowerShellFromCsharp https://gist.github.com/tanaka-takayoshi/8066817 https://gist.github.com/tanaka-takayoshi/8066824
await
using
None