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
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
ACE-Step-1.5で見る 音楽生成AIのしくみと“破綻だけ直す”Retake機能の開発【zennfes spring 2026 登壇資料】
personabb
1
470
就職⽀援サービスにおけるキャリアアドバイザーのシフトスケジューリング
recruitengineers
PRO
1
150
プロダクト開発から業務改善コンサルまで。事業全体へ「染み出す」ことで広がるエンジニアの可能性
ham0215
0
130
Oracle AI Database@Azure:サービス概要のご紹介
oracle4engineer
PRO
6
2k
攻撃者視点で考えるDetection Engineering
cryptopeg
3
1.8k
AIのReact習熟度を測る
uhyo
2
570
Kubernetesにおける学習基盤とLLMOpsの概要
ry
1
310
Bedrock AgentCore RuntimeでAuth0 Changelog調査AIをアップグレードした話
t5u8a5a
1
150
日本 Fintech 未来予測レポート 2027〜2028年(オリジナル版)
8maki
0
2.2k
LayerX コーポレートエンジニアリング室におけるサプライチェーンセキュリティへの取り組み / Supply Chain Security at LayerX Corporate Engineering
yuyatakeyama
2
370
Bucharest Tech Week 2026 - Reinventing testing practices in the AI era
edeandrea
PRO
1
160
RSA暗号を手計算したくなること、ありますよね?? (20260615_orestudy6_rsa)
thousanda
0
430
Featured
See All Featured
Are puppies a ranking factor?
jonoalderson
1
3.5k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
25
2k
How to Get Subject Matter Experts Bought In and Actively Contributing to SEO & PR Initiatives.
livdayseo
0
140
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
2.9k
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
1
3.6k
How GitHub (no longer) Works
holman
316
150k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.8k
GraphQLの誤解/rethinking-graphql
sonatard
75
12k
A designer walks into a library…
pauljervisheath
211
24k
Docker and Python
trallard
47
3.9k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
2.9k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
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