Reputation: 1148
I'm running powershell scripts from c# by way of Runspace
and Pipeline
.
I need to support Powershell 2
My script uses [System.Net.WebRequest]
From the PS CLI on this machine, [System.Net.WebRequest]
works fine.
However, running a script from c# results in
Unable to find type [System.Net.WebRequest]: make sure that the assembly containing this type is loaded.
I've tried using Add-Type
to load System.Net
and confirmed it is loaded with [appdomain]::CurrentDomain.GetAssemblies()
But the error persists
No issues if the computer has PS 3.0
Edit: Full relevant code
InitialSessionState initial = InitialSessionState.CreateDefault();
runspace = RunspaceFactory.CreateRunspace(initial);
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline()) {
pipeline.Commands.AddScript(scriptText);
<invoke, read output etc>
}
Upvotes: 2
Views: 505
Reputation: 1148
I created a test app and found this to not be an issue.
The issue only occurs in my main app.
After a few hours of narrowing down the differences, I found that I could recreate the issue in my test app by loading and and using a shared module of mine.
I narrowed it down to a shared GetMyVersion
routine in my shared DLL module.
Assembly assembly = Assembly.GetExecutingAssembly();
return FileVersionInfo.GetVersionInfo(assembly.Location);
The solution was to execute this code early within the exe. I was able to leave the regular usage of the shared DLL routine in the rest of the app.
Another solution that may be more reliable and also help in other circumstances is to directly access the assembly
$sysManagement = [System.Reflection.Assembly]::LoadWithPartialName("System.Net");
$netType = $sysManagement.GetType("System.Net.WebRequest",$true);
$netType::Create("http://etc.com")
Upvotes: 1