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
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×AWS CDK×AWS FISで"振り返れる"ミニGameDayをつくろう
yoshimi0227
1
160
なぜ私たちのSREプラクティスはなかなか機能しないのか 〜システムより先に組織を見る〜 / Why our SRE practices aren't really working
vtryo
3
3.8k
地域 SRE コミュニティ最前線 / SRE NEXT 2026 Discussion Night Track C
muziyoshiz
0
220
人を動かすのは時間ではなく、納得感 〜新任EMが入社3ヶ月、組織を2回変えた話〜
kakehashi
PRO
3
240
SRE Next 2026 何でも屋からの脱却
bto
0
760
Compose 新機能総まとめ / What's New in Jetpack Compose
yanzm
0
270
AIレビューはどこまで任せられるのか?自動化と人が背負うレビューの境界
sansantech
PRO
3
880
関数型の考えを TypeScript に持ち込んで、テストしやすい純粋関数を増やす / Pure at the Core, Effects at the Edge: Bringing Functional Thinking into TypeScript
kaminashi
1
120
SRE Lounge Hiroshimaへの招待
grimoh
0
670
CDKで書くECSのベストプラクティス、 改めて考え直す2026 #cdkconf2026
makies
1
490
“それは自分の仕事じゃない"を越えて行け
yuukiyo
1
370
キャリアの中で本を作る / Making a Book During Your Career
ak1210
0
140
Featured
See All Featured
Product Roadmaps are Hard
iamctodd
55
12k
From Legacy to Launchpad: Building Startup-Ready Communities
dugsong
0
260
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
State of Search Keynote: SEO is Dead Long Live SEO
ryanjones
0
220
Test your architecture with Archunit
thirion
1
2.3k
The Spectacular Lies of Maps
axbom
PRO
1
860
Designing for humans not robots
tammielis
254
26k
30 Presentation Tips
portentint
PRO
1
350
Thoughts on Productivity
jonyablonski
76
5.2k
Designing Experiences People Love
moore
143
24k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.8k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.5k
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