xlogI125’s blog

パソコン作業を効率化したい

C#からPowerShellコマンドを使う(PowerShell.AddScriptメソッド)

メモ

C#を使用可能でSystem.Management.Automation.dllを参照して良い場合にPowerShell.AddScriptメソッドを使う。

使い捨てスクリプト

# PowerShell 5.1, Windows 11 (2023年12月頃)

Set-StrictMode -Version Latest

$ps = [System.Management.Automation.PowerShell]::Create()
$null = $ps.AddScript('$gci = Get-ChildItem')
$null = $ps.AddScript('$gci | Out-GridView -Title "AddScript"')
$null = $ps.AddScript('$gci')
$ps.Invoke() | Out-GridView -Title "Invoke"
$ps.Dispose()
# PowerShell 5.1, Windows 11 (2023年12月頃)

Set-StrictMode -Version Latest

Add-Type -Language CSharp -TypeDefinition @'
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;

namespace ConsoleApp1 {
  public class Program {
    public static void Main(string[] args) {
      Collection<PSObject> psObjs;
      using (PowerShell ps = PowerShell.Create()) {
        ps.AddScript(@"Get-ChildITem | Format-Table | Out-String -Width 80");
        psObjs = ps.Invoke();
        foreach (PSObject psObj in psObjs) {
          Console.WriteLine("{0}", psObj);
        }

        ps.AddScript(@"$gci = Get-ChildITem ""c:\""");
        ps.AddScript(@"$gci | Out-GridView");
        ps.AddScript(@"$str = $gci | Format-Table | Out-String -Width 80");
        ps.AddScript(@"$str");
        psObjs = ps.Invoke();
        foreach (PSObject psObj in psObjs) {
          Console.WriteLine("{0}", psObj);
        }
      }
    }
  }
}
'@

[ConsoleApp1.Program]::Main($args)

過去記事

dy100ms.hatenadiary.jp