Skip to content

Instantly share code, notes, and snippets.

@roundand
Last active April 26, 2017 08:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roundand/9911140 to your computer and use it in GitHub Desktop.
Save roundand/9911140 to your computer and use it in GitHub Desktop.
LinqPad demo of how to call PowerShell from C#, passing in parameters and receiving a hashtable response
<Query Kind="Statements">
<GACReference>System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</GACReference>
<Namespace>System.Management.Automation</Namespace>
</Query>
// create a powershell session
PowerShell ps = PowerShell.Create();
// add a script to emit a PowerShell hashtable which includes a parameter value
ps.AddScript("param($target); Write-Output @{hello = $target}");
ps.AddParameter("target", "World");
// call the script
System.Collections.ObjectModel.Collection<PSObject> results = ps.Invoke();
// take the first emitted result as a dynamic and dump it
dynamic result = results[0];
((string)result.hello).Dump("Should be 'World'");
// tidy up after
ps.Dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment