You have to run your SL app with elevated permissions out-of-browser, but this will allow you to query Powershell. You’ll have to parse the output yourself.
namespace TestPowershellScripting
{
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices.Automation;
///
/// Requires that OOB and elevated permissions are active.
///
public class PowerShellSL
{
///
///
private const string PowerShellExecutable = "powershell.exe";
///
/// executing context. When set to false, PowerShell runs faster, but does not have
/// access to user-level environment variables.
///
public bool UseProfile { get; set; }
///
/// In the PowerShell script, use WriteHost to write output to standard output.
/// The script is written to standard input and run using the WScript library.
///
/// The PowerShell script to run, expressed as a string.
///
/// A FileNotFoundException is thrown if Powershell cannot be run.
/// An InvalidOperationException is thrown if the automation factory is unavailable.
public string Run(string script) {
// Check to see if stuff is available
if (!AutomationFactory.IsAvailable)
throw new InvalidOperationException("AutomationFactory is unavailable. Program must be run as out-of-browser with elevated permissions.");
var shell = AutomationFactory.CreateObject("WScript.Shell");
string cmd = PowerShellExecutable + " -NonInteractive " + (UseProfile ? "" : "-NoProfile") + " -WindowStyle Hidden -Command -";
string output = "";
dynamic result = null;
try {
result = shell.Exec(cmd);
result.StdIn.Write(script);
result.StdIn.Close();
while (!result.StdOut.AtEndOfStream) {
output += result.StdOut.ReadLine() + "\r\n";
}
} catch (FileNotFoundException fnfex) {
throw new FileNotFoundException("PowerShell is not installed on the local computer.", fnfex);
}
return output;
}
///
/// When results are available, the delegate 'results' is called with the program output.
/// In the PowerShell script, use WriteHost to write output to standard output.
/// The script is written to standard input and run using the WScript library.
///
/// The PowerShell script to run, expressed as a string.
/// The delegate method to call when results have been returned.
/// A FileNotFoundException is thrown if Powershell cannot be run.
/// An InvalidOperationException is thrown if the automation factory is unavailable.
public void RunAsync(string script, Action results) {
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(
(sender, e) => {
e.Result = this.Run((string)e.Argument);
}
);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(sender, e) => {
if (results != null)
results((string)e.Result);
}
);
bw.RunWorkerAsync(script);
}
}
}