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:
- Suppose I turned off Windows Error Reporting from the C# runspace.
- When I turn it off from C#, the second Get-WindowsErrorReporting (the line I marked as *1 above) shows that the setting was properly changed.
- However, when I type Get-WIndowsErrorReporting on another powershell window, the value is still not changed.
- I also tried the other way around : Change the state from the powershell window, and check the state from the C# code... This time, I get "disabled" from the powershell window, and "enabled" from the C# runspace.
- From what I saw, I guess there is no "Link" between the powershell "sessions"(sorry I don't know how they call it...) of the powershell window and C# runspace...
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....