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
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
tanaka_733
December 21, 2013
Technology
1.9k
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
2.9k
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
AIっぽい文章を採点して人間らしく直すアプリを作ってみた
yama3133
2
190
FinOps × AIエージェントで実現する コストインシデントの自動調査
oasis1994liveforever
0
140
機械学習を「社会実装」するということ 2026年夏版 / Social Implementation of Machine Learning June 2026 Version
moepy_stats
5
2.4k
AmazonRoute 53ではじめてのドメイン取得!HTTPS化までの道のりを整理してみた
usanchuu
3
140
失敗を資産に変えるClaude Code
shinyasaita
0
660
人材育成分科会.pdf
_awache
4
250
エンジニアリング戦略の作り方 / Crafting Engineering Strategy
iwashi86
21
6.9k
気づかぬうちにセキュリティ負債を生むAPIキー運用
sgwrmctk
0
130
Kubernetesにおける学習基盤とLLMOpsの概要
ry
1
310
AAIFに入ってみた ~内から見えるコミュニティ動向~
sato4
0
230
【セミナー資料】Claude Code をセキュアに使うための考え方と設定の勘どころ / Claude Code Webinar 20260616
masahirokawahara
2
340
エラーバジェットのアラートのタイミングを考える.pdf
kairim0
0
150
Featured
See All Featured
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
333
22k
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.3k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
2.9k
Gemini Prompt Engineering: Practical Techniques for Tangible AI Outcomes
mfonobong
2
430
What the history of the web can teach us about the future of AI
inesmontani
PRO
1
610
Code Review Best Practice
trishagee
74
20k
Abbi's Birthday
coloredviolet
2
8.1k
4 Signs Your Business is Dying
shpigford
187
22k
We Are The Robots
honzajavorek
0
250
Joys of Absence: A Defence of Solitary Play
codingconduct
1
390
Why Your Marketing Sucks and What You Can Do About It - Sophie Logan
marketingsoph
0
170
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
480
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