Last active
April 14, 2023 19:14
-
-
Save breezhang/4523040 to your computer and use it in GitHub Desktop.
Embedding PowerShell in your C# Application author :Douglas Finke
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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