Created
March 23, 2011 02:51
-
-
Save jstangroome/882528 to your computer and use it in GitHub Desktop.
Execute individual PowerShell v2 commands using .NET Framework CLR 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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