public
Last active

Execute individual PowerShell v2 commands using .NET Framework CLR 4

  • Download Gist
CLR4PowerShell.psm1
PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
function Invoke-CLR4PowerShellCommand {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ScriptBlock]
$ScriptBlock,
[Parameter(ValueFromRemainingArguments=$true)]
[Alias('Args')]
[object[]]
$ArgumentList
)
if ($PSVersionTable.CLRVersion.Major -eq 4) {
Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList
return
}
 
$RunActivationConfigPath = $Env:TEMP | Join-Path -ChildPath ([Guid]::NewGuid())
New-Item -Path $RunActivationConfigPath -ItemType Container | Out-Null
@"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
</configuration>
"@ | 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
 
#Test-CLR4PowerShell

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.