I am trying to run the following simple ps1 file (which works fine if I call it from powershell) from Visual C#.
[windowsErrorReporting.ps1]
Get-WindowsErrorReporting
if($WER_ENABLED -eq "True")
{
Enable-WindowsErrorReporting
}
else
{
Disable-WindowsErrorReporting
}
Get-WindowsErrorReporting // *1
The following is the C# code I wrote, and here is the situation I got:
private string RunScript(string scriptFileName)
{
// Read text data from the script file.
string cmd;
var assm = Assembly.GetExecutingAssembly();
using (var stream = assm.GetManifestResourceStream("MyProject.Resources."+scriptFileName))
{
var reader = new StreamReader(stream);
cmd = reader.ReadToEnd();
}
// create powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// Create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmd);
pipeline.Commands.Add("Out-String");
foreach (string key in args.Keys)
{
runspace.SessionStateProxy.SetVariable("WER_ENABLED", "False");
}
Collection<PSObject> results;
StringBuilder stringBuilder = new StringBuilder();
// execute the script
results = pipeline.Invoke();
// convert the script result into a single string
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
// Close the runspace
runspace.Close();
// Return output
return stringBuilder.ToString();
}
I really appreciate if someone help me understand what is going on....
[SOLVED!] The reason I could not get the script working was that I run x86 version of the powershell from C#. That is why I get different results from the powershell window (x64) and the powershell runspace (x86). After I configured the visual C# compiler setting to build x64, everything worked fine.
What I learned from this problem is that some powershell commands, like Enable-WindowsErrorReporting, do not run on x86 version of powershell.
Check the result returned from Enable/Disable-WindowsErrorReporting
. If it returns False
it didn't work. I believe you have to be running as admin for the change to take effect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.