Skip to content

Instantly share code, notes, and snippets.

@jstangroome
Created March 23, 2011 02:51
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstangroome/882528 to your computer and use it in GitHub Desktop.
Save jstangroome/882528 to your computer and use it in GitHub Desktop.
Execute individual PowerShell v2 commands using .NET Framework CLR 4
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment