Monday, October 26, 2009

Executing PowerShell code from within your own program

In V2 this got a lot easier. Here’s my PSExecute function. The idea is that you send in a text value and a script. The script references the value as $_. All output from the script is returned as the result of PSExecute. Exceptions (e.g. syntax errors), errors etc. are returned as well. Depending on the usage, this may not be what you need, but you can change it yourself.

I’m planning to use this in combination with ILM. Having the ability to use a piece of PowerShell script in an advanced flow rule or in the MVExtension seems very useful.

A script could be $_.toupper() etc.

private String PSExecute(String Script, String InputValue)
{
// Create PS outside the function if called multiple times for performance reasons
PowerShell PS = PowerShell.Create();

// The script could probably be parsed once to speed things up if the same script is used repeatably
PS.AddScript("'" + InputValue + "' | foreach {" + Script + "}");
String s = "";
try
{
foreach (PSObject result in PS.Invoke())
{
s += result.ToString();
} // End foreach.
}
catch (Exception e)
{
s += "EXCEPTION: " + e.Message; // ToString();
// just continue
}
foreach (DebugRecord result in PS.Streams.Debug)
{
s += "DEBUG: " + result.ToString();
}
foreach (VerboseRecord result in PS.Streams.Verbose)
{
s += "VERBOSE: " + result.ToString();
}
foreach (WarningRecord result in PS.Streams.Warning)
{
s += "WARNING: " + result.ToString();
}
foreach (ErrorRecord result in PS.Streams.Error)
{
s += "ERROR: " + result.ToString();
}

return s;
}





If you want to try it from PowerShell first, here’s the statements -




$script='$input | fforeach {$_.toupper()}'
$script='$_.toupper()'
$ps=[System.Management.Automation.powershell]::create()
$ps.AddScript('''' + $Inputvalue + ''' | foreach {' + $script + '}')
$ps.invoke()
$ps.Streams





Have fun!

No comments: