Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Execute individual PowerShell v2 commands using .NET Framework CLR 4
function Invoke-CLR4PowerShellCommand {
param (
if ($PSVersionTable.CLRVersion.Major -eq 4) {
Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList
$RunActivationConfigPath = $Env:TEMP | Join-Path -ChildPath ([Guid]::NewGuid())
New-Item -Path $RunActivationConfigPath -ItemType Container | Out-Null
<?xml version="1.0" encoding="utf-8" ?>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
"@ | Set-Content -Path $RunActivationConfigPath\powershell.exe.activation_config -Encoding UTF8
$EnvVarName = 'COMPLUS_ApplicationMigrationRuntimeActivationConfigPath'
$EnvVarOld = [Environment]::GetEnvironmentVariable($EnvVarName)
[Environment]::SetEnvironmentVariable($EnvVarName, $RunActivationConfigPath)
try {
& powershell.exe -inputformat text -command $ScriptBlock -args $ArgumentList
} finally {
[Environment]::SetEnvironmentVariable($EnvVarName, $EnvVarOld)
$RunActivationConfigPath | Remove-Item -Recurse
function Test-CLR4PowerShell {
$ScriptBlock = { $PSVersionTable.CLRVersion }
& $ScriptBlock
Invoke-CLR4PowerShellCommand -ScriptBlock $ScriptBlock
& $ScriptBlock
Invoke-CLR4PowerShellCommand -ScriptBlock { param ($name) "Hello $name" } -ArgumentList (Read-Host -Prompt 'Enter your name')
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment