PoshCode Archive  Artifact [342ed5971f]

Artifact 342ed5971f3486f625551eb0e5468a79a7a0f860a124717ad4f6c94132697a67:

  • File Import-CmdEnvironment.ps1 — part of check-in [62ef524aca] at 2018-06-10 13:02:55 on branch trunk — Invoke the specified command (with parameters) in cmd.exe, and import any environment variable changes back to PowerShell (user: Joel Bennett size: 2016)

# encoding: ascii
# api: powershell
# title: Import-CmdEnvironment
# description: Invoke the specified command (with parameters) in cmd.exe, and import any environment variable changes back to PowerShell
# version: 0.1
# type: script
# author: Joel Bennett
# license: CC0
# function: Import-CmdEnvironment
# x-poshcode-id: 1929
# x-archived: 2010-06-23T01:39:41
#
#
# .SYNOPSIS
# Import environment variables from cmd to PowerShell
# .DESCRIPTION
# Invoke the specified command (with parameters) in cmd.exe, and import any environment variable changes back to PowerShell
# .EXAMPLE
# Import-CmdEnvironment Import-CmdEnvironment ${Env:VS90COMNTOOLS}\vsvars32.bat x86
#
# Imports the x86 Visual Studio 2008 Command Tools environment
# .EXAMPLE
# Import-CmdEnvironment Import-CmdEnvironment ${Env:VS100COMNTOOLS}\vsvars32.bat x86_amd64
# 
# Imports the x64 Cross Tools Visual Studio 2010 Command environment

#function Import-CmdEnvironment {
[CmdletBinding()]
param(
   [Parameter(Position=0,Mandatory=$False,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
   [Alias("PSPath")]
   [string]$Command = "echo"
,
   [Parameter(Position=0,Mandatory=$False,ValueFromRemainingArguments=$true,ValueFromPipelineByPropertyName=$true)]
   [string[]]$Parameters
)
   ## If it's an actual file, then we should quote it:
	if(Test-Path $Command) { $Command = "`"$(Resolve-Path $Command)`"" }
   $setRE = new-Object System.Text.RegularExpressions.Regex '^(?<var>.*?)=(?<val>.*)$', "Compiled,ExplicitCapture,MultiLine"
   $OFS = " "
   [string]$Parameters = $Parameters
   $OFS = "`n"
	## Execute the command, with parameters.
   Write-Verbose "EXECUTING: cmd.exe /c `"$Command $Parameters > nul && set`""
	## For each line of output that matches, set the local environment variable
	foreach($match in  $setRE.Matches((cmd.exe /c "$Command $Parameters > nul && set")) | Select Groups) {
      Set-Content Env:\$($match.Groups["var"]) $match.Groups["val"] -Verbose
	}
#}