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
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
880
とあるインフラエンジニアの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
2.1k
Other Decks in Technology
See All in Technology
Azure App Service / Container Apps の組み込み認証
kuniteru
0
210
2026-09-10 【Snowflake World Tour Tokyo 2026】dbt Core と Snowflake で実現する多層的なデータガバナンス / Multi-Layered Data Governance Powered by dbt Core and Snowflake
civitaspo
0
220
WAF 運用改善の承認サイクル/SRE_BizReach_MIXI_1
visional_engineering_and_design
1
370
Where Is JetBrains AI Heading- — Central CLI, Air Alpha, and the Agentic Development Stack
x5gtrn
PRO
0
150
Webとヘルスデータ
yukukotani
1
200
Azure Cost Management の FOCUS コストデータを迷わず読むための“3つの軸”
tetsuyaooooo
0
160
GoCon2026 - Open Source, Open World
sanposhiho
2
410
enechainの内製セルフサービスプラットフォーム
hiyosi
0
140
Jetpack Compose で挑む新聞紙面UI ─ 複合ジェスチャー・ポリゴン記事領域・適応的ページ構成という3つの壁/droidkaigi2026
nikkei_engineer_recruiting
0
240
AIで開発は速くなったのに、なぜ現場は楽にならないのか 〜あなたの組織のボトルネックを突き止めるワークショップ〜
jacopen
1
280
Code4Lib JAPANカンファレンス2026 開会挨拶 / Code4Lib JAPAN Conference 2026: Opening Remarks
ykiyota
0
170
AI 駆動 Terraform 開発/SRE_BizReach_MIXI_2
visional_engineering_and_design
2
1.9k
Featured
See All Featured
Why Your Marketing Sucks and What You Can Do About It - Sophie Logan
marketingsoph
0
400
Testing 201, or: Great Expectations
jmmastey
46
8.3k
Building Flexible Design Systems
yeseniaperezcruz
330
41k
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
600
Building AI with AI
inesmontani
PRO
1
1.2k
Information Architects: The Missing Link in Design Systems
soysaucechin
1
1.1k
Faster Mobile Websites
deanohume
310
32k
Tell your own story through comics
letsgokoyo
1
1.1k
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
240
The Spectacular Lies of Maps
axbom
PRO
1
980
Odyssey Design
rkendrick25
PRO
2
800
Kristin Tynski - Automating Marketing Tasks With AI
techseoconnect
PRO
0
510
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