Last active
April 26, 2017 08:02
-
-
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
This file contains 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
<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