In a project developed using .Net 4, we needed to make some functionality available for scripting in PowerShell.
- The first task was to configure PowerShell to be able to load .Net 4 assemblies:
The $pshome variable is the directory where the powershell.exe and its configuration file powershell.exe.config reside (the .config does not seem to be required on Win7 as it was not on my system). On 32-bit systems, the path is C:\Windows\System32\WindowsPowerShell\v1.0, 64-bit systems have C:\Windows\SysWOW64\WindowsPowerShell\v1.0.
Create a file called powershell.exe.config in a temp directory, and paste this code (found on SO)
<?xml version="1.0"?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0.30319"/> <supportedRuntime version="v2.0.50727"/> </startup> </configuration>
Open a command prompt as administrator, and copy the file to PowerShell’s directory
copy .\powershell.exe.config c:\windows\system32\windowspowershell\v1.0\powershell.exe.config
Restart PowerShell, and you are able to load .Net 4 assemblies.
- Next, we need to set up the .Net environment so that it uses the assembly’s configuration file instead of PowerShell’s.
Since the executable that is loading the assembly is powershell.exe, it is thus looking for the powershell.exe.config. To use the correct config file, we need to set the current AppDomain’s APP_CONFIG_FILE property (found on SO):
$filename = "c:\path\to\MyAssembly.dll" [System.AppDomain]::CurrentDomain.SetData( "APP_CONFIG_FILE", $filename + ".config") $assembly = [System.Reflection.Assembly]::LoadFrom($filename)
Pingback: Resolving Assembly Bindings in Powershell « devioblog