Skip to content

Instantly share code, notes, and snippets.

@breezhang
Last active April 14, 2023 19:14
Show Gist options
  • Save breezhang/4523040 to your computer and use it in GitHub Desktop.
Save breezhang/4523040 to your computer and use it in GitHub Desktop.
Embedding PowerShell in your C# Application author :Douglas Finke
function Invoke-Template {
param(
[string]$Path,
[Scriptblock]$ScriptBlock
)
function Get-Template {
param($TemplateFileName)
$content = [IO.File]::ReadAllText(
(Join-Path $Path $TemplateFileName) )
Invoke-Expression "@`"`r`n$content`r`n`"@"
}
& $ScriptBlock
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace breezhang.Copy.Douglas Finke.to.github.com
{
public static class PsExtensions
{
public static List<PSObject> ExecutePs(
this string script, bool writeToConsole = true)
{
var powerShell = PowerShell
.Create()
.AddScript(script);
if (writeToConsole)
{
powerShell.AddCommand("Out-String");
powerShell
.Invoke<PSObject>()
.ToList()
.WritePs();
}
// Lets the caller act on the returned collection
// of PowerShell objects
return powerShell
.Invoke<PSObject>()
.ToList();
}
public static void WritePs(this List<PSObject> psResults)
{
psResults.ForEach(Console.WriteLine);
}
}
}
var script = "Get-Process | Where {$_.Handles -gt 400}";
// Let the extension method
// print out the results
script.ExecutePs();
// In PowerShell v3, PSObject
// implements IDynamicObject
foreach (dynamic item in
script.ExecutePs(writeToConsole: false))
{
Console.WriteLine(item.ProcessName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment