-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Invoke-Environment.ps1
90 lines (73 loc) · 2.3 KB
/
Invoke-Environment.ps1
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<#
.Synopsis
Invokes a command and imports its environment variables.
Author: Roman Kuzmin (inspired by Lee Holmes's Invoke-CmdScript.ps1)
.Description
It invokes the specified command or batch file with arguments and imports
its result environment variables to the current PowerShell session.
Command output is discarded by default, use the switch Output to enable it.
You may check for $LASTEXITCODE unless the switch Force is specified.
.Parameter Command
Specifies the entire command including the batch file and parameters.
This string is passed in `cmd /c` as it is. Mind quotes for paths and
arguments with spaces and special characters. Do not use redirection.
.Parameter File
Specifies the batch file path.
.Parameter Arguments
With File, specifies its arguments. Arguments with spaces are quoted.
In the batch file, you may unquote them as %~1, %~2, etc.
Other special characters are not treated.
.Parameter Output
Tells to collect and return the command output.
.Parameter Force
Tells to import variables even if the command exit code is not 0.
.Inputs
None. Use the script parameters.
.Outputs
With Output, the command output.
.Example
>
# Invoke vsvars32 and import variables even if exit code is not 0
Invoke-Environment '"%VS100COMNTOOLS%\vsvars32.bat"' -Force
# Invoke vsvars32 as file and get its output
Invoke-Environment -File $env:VS100COMNTOOLS\vsvars32.bat -Output
.Link
https://github.com/nightroman/PowerShelf
#>
[CmdletBinding(DefaultParameterSetName='Command')]
param(
[Parameter(Mandatory=1, Position=0, ParameterSetName='Command')]
[string]$Command
,
[Parameter(Mandatory=1, ParameterSetName='File')]
[string]$File
,
[Parameter(ParameterSetName='File')]
[string[]]$Arguments
,
[switch]$Output
,
[switch]$Force
)
$stream = if ($Output) {($temp = [IO.Path]::GetTempFileName())} else {'nul'}
$operator = if ($Force) {'&'} else {'&&'}
if ($File) {
$Command = "`"$File`""
if ($Arguments) {
foreach($_ in $Arguments) {
if ($_.Contains(' ')) {
$_ = "`"$_`""
}
$Command += " $_"
}
}
}
foreach($_ in cmd.exe /c " $Command > `"$stream`" 2>&1 $operator SET") {
if ($_ -match '^([^=]+)=(.*)') {
[System.Environment]::SetEnvironmentVariable($matches[1], $matches[2])
}
}
if ($Output) {
Get-Content -LiteralPath $temp
Remove-Item -LiteralPath $temp
}