I am updating a PowerShell script that manages some .NET assemblies. The script was written for assemblies built against .NET 2 (the same version of the framework that PowerShell runs with), but now needs to work with .NET 4 assemblies as well as .NET 2 assemblies.
Since .NET 4 supports running applications built against older versions of the framework, it seems like the simplest solution is to launch PowerShell with the .NET 4 runtime when I need to run it against .NET 4 assemblies.
How can I run PowerShell with the .NET 4 runtime?
Here is the contents of the configuration file I used to support both .NET 2.0 and .NET 4 assemblies:
Also, here’s a simplified version of the PowerShell 1.0 compatible code I used to execute our scripts from the passed in command line arguments:
In addition to the basic error handling shown above, we also inject a
trap
statement into the script to display additional diagnostic information (similar to Jeffrey Snover's Resolve-Error function).Just as another option, the latest PoshConsole release includes binaries targeted to .NET 4 RC (which work fine against the RTM release) without any configuration.
Please be VERY careful with using the registry key approach. These are machine-wide keys and forcibily migrate ALL applications to .NET 4.0.
Many products do not work if forcibily migrated and this is a testing aid and not a production quality mechanism. Visual Studio 2008 and 2010, MSBuild, turbotax, and a host of websites, SharePoint and so on should not be automigrated.
If you need to use PowerShell with 4.0, this should be done on a per-application basis with a configuration file, you should check with the PowerShell team on the precise recommendation. This is likely to break some existing PowerShell commands.
The best solution I have found is in the blog post Using Newer Version(s) of .NET with PowerShell. This allows powershell.exe to run with .NET 4 assemblies.
Simply modify (or create)
$pshome\powershell.exe.config
so that it contains the following:Additional, quick setup notes:
Locations and files are somewhat platform dependent; however will give you an inline gist of how to make the solution work for you.
cd $pshome
in the Powershell window (doesn't work from DOS prompt).C:\Windows\System32\WindowsPowerShell\v1.0\
powershell.exe.config
if yourPowerShell.exe
is being executed (create the config file if need be).PowerShellISE.Exe
is running then you need to create its companion config file asPowerShellISE.Exe.config