-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
powershell.ps1
257 lines (228 loc) · 9.91 KB
/
powershell.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
[CmdletBinding()]
param()
Import-Module $PSScriptRoot\ps_modules\Sanitizer
. $PSScriptRoot\helpers.ps1
function Get-ActionPreference {
param (
[Parameter(Mandatory)]
[string]
$VstsInputName,
[Parameter()]
[string]
$DefaultAction = 'Default',
[Parameter()]
[string[]]
$ValidActions = @( 'Default', 'Stop', 'Continue', 'SilentlyContinue' )
)
$result = Get-VstsInput -Name $VstsInputName -Default $DefaultAction
if (-not $ValidActions -contains $result) {
Write-Error (Get-VstsLocString -Key 'PS_InvalidActionPreference' -ArgumentList @( $VstsInputName, $result, ($ValidActions -join ', ') ))
}
return $result
}
Trace-VstsEnteringInvocation $MyInvocation
try {
Import-VstsLocStrings "$PSScriptRoot\task.json"
# Get inputs.
$input_errorActionPreference = Get-ActionPreference -VstsInputName 'errorActionPreference' -DefaultAction 'Stop'
$input_warningPreference = Get-ActionPreference -VstsInputName 'warningPreference' -DefaultAction 'Default'
$input_informationPreference = Get-ActionPreference -VstsInputName 'informationPreference' -DefaultAction 'Default'
$input_verbosePreference = Get-ActionPreference -VstsInputName 'verbosePreference' -DefaultAction 'Default'
$input_debugPreference = Get-ActionPreference -VstsInputName 'debugPreference' -DefaultAction 'Default'
$input_progressPreference = Get-ActionPreference -VstsInputName 'progressPreference' -DefaultAction 'SilentlyContinue'
$input_showWarnings = Get-VstsInput -Name 'showWarnings' -AsBool
$input_failOnStderr = Get-VstsInput -Name 'failOnStderr' -AsBool
$input_ignoreLASTEXITCODE = Get-VstsInput -Name 'ignoreLASTEXITCODE' -AsBool
$input_pwsh = Get-VstsInput -Name 'pwsh' -AsBool
$input_workingDirectory = Get-VstsInput -Name 'workingDirectory' -Require
Assert-VstsPath -LiteralPath $input_workingDirectory -PathType 'Container'
$input_targetType = Get-VstsInput -Name 'targetType'
if ("$input_targetType".ToUpperInvariant() -eq "FILEPATH") {
$input_filePath = Get-VstsInput -Name 'filePath' -Require
try {
Assert-VstsPath -LiteralPath $input_filePath -PathType Leaf
}
catch {
Write-Error (Get-VstsLocString -Key 'PS_InvalidFilePath' -ArgumentList $input_filePath)
}
if (!$input_filePath.ToUpperInvariant().EndsWith('.PS1')) {
Write-Error (Get-VstsLocString -Key 'PS_InvalidFilePath' -ArgumentList $input_filePath)
}
$input_arguments = Get-VstsInput -Name 'arguments'
}
elseif ("$input_targetType".ToUpperInvariant() -eq "INLINE") {
$input_script = Get-VstsInput -Name 'script'
}
else {
Write-Error (Get-VstsLocString -Key 'PS_InvalidTargetType' -ArgumentList $input_targetType)
}
$input_runScriptInSeparateScope = Get-VstsInput -Name 'runScriptInSeparateScope' -AsBool
# Generate the script contents.
Write-Host (Get-VstsLocString -Key 'GeneratingScript')
$contents = @()
if ($input_errorActionPreference -ne 'Default') {
$contents += "`$ErrorActionPreference = '$input_errorActionPreference'"
}
if ($input_warningPreference -ne 'Default') {
$contents += "`$WarningPreference = '$input_warningPreference'"
}
if ($input_informationPreference -ne 'Default') {
$contents += "`$InformationPreference = '$input_informationPreference'"
}
if ($input_verbosePreference -ne 'Default') {
$contents += "`$VerbosePreference = '$input_verbosePreference'"
}
if ($input_debugPreference -ne 'Default') {
$contents += "`$DebugPreference = '$input_debugPreference'"
}
if ($input_progressPreference -ne 'Default') {
$contents += "`$ProgressPreference = '$input_progressPreference'"
}
# Change default error view to normal view. We need this for error handling since we pipe stdout and stderr to the same stream
# and we rely on PowerShell piping back NormalView error records (required because PowerShell Core changed the default to ConciseView)
$contents += "`$ErrorView = 'NormalView'"
if ("$input_targetType".ToUpperInvariant() -eq 'FILEPATH') {
try {
$null = Protect-ScriptArguments -InputArgs $input_arguments -TaskName "PowerShellV2"
}
catch {
$message = $_.Exception.Message
if ($message -eq (Get-VstsLocString -Key 'ScriptArgsSanitized')) {
throw $message;
}
$telemetry = @{
'UnexpectedError' = $message
'ErrorStackTrace' = $_.Exception.StackTrace
}
Publish-Telemetry $telemetry
}
$contents += ". '$("$input_filePath".Replace("'", "''"))' $input_arguments".Trim()
Write-Host (Get-VstsLocString -Key 'PS_FormattedCommand' -ArgumentList ($contents[-1]))
}
else {
$contents += "$input_script".Replace("`r`n", "`n").Replace("`n", "`r`n")
}
if (!$input_ignoreLASTEXITCODE) {
$contents += 'if (!(Test-Path -LiteralPath variable:\LASTEXITCODE)) {'
$contents += ' Write-Host ''##vso[task.debug]$LASTEXITCODE is not set.'''
$contents += '} else {'
$contents += ' Write-Host (''##vso[task.debug]$LASTEXITCODE: {0}'' -f $LASTEXITCODE)'
$contents += ' exit $LASTEXITCODE'
$contents += '}'
}
$joinedContents = [System.String]::Join(
([System.Environment]::NewLine),
$contents);
if ($input_showWarnings) {
$joinedContents = '
$warnings = New-Object System.Collections.ObjectModel.ObservableCollection[System.Management.Automation.WarningRecord];
Register-ObjectEvent -InputObject $warnings -EventName CollectionChanged -Action {
if($Event.SourceEventArgs.Action -like "Add"){
$Event.SourceEventArgs.NewItems | ForEach-Object {
Write-Host "##vso[task.logissue type=warning;]$_";
}
}
};
Invoke-Command {' + $joinedContents + '} -WarningVariable +warnings';
}
# Write the script to disk.
Assert-VstsAgent -Minimum '2.115.0'
$tempDirectory = Get-VstsTaskVariable -Name 'agent.tempDirectory' -Require
Assert-VstsPath -LiteralPath $tempDirectory -PathType 'Container'
$filePath = [System.IO.Path]::Combine($tempDirectory, "$([System.Guid]::NewGuid()).ps1")
$null = [System.IO.File]::WriteAllText(
$filePath,
$joinedContents,
([System.Text.Encoding]::UTF8))
# Prepare the external command values.
#
# Note, use "-Command" instead of "-File". On PowerShell v4 and V3 when using "-File", terminating
# errors do not cause a non-zero exit code.
if ($input_pwsh) {
$powershellPath = Get-Command -Name pwsh.exe -CommandType Application | Select-Object -First 1 -ExpandProperty Path
}
else {
$powershellPath = Get-Command -Name powershell.exe -CommandType Application | Select-Object -First 1 -ExpandProperty Path
}
$executionOperator;
if ($input_runScriptInSeparateScope) {
$executionOperator = '&';
}
else {
$executionOperator = '.';
}
Assert-VstsPath -LiteralPath $powershellPath -PathType 'Leaf'
$arguments = "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command `"$executionOperator '$($filePath.Replace("'", "''"))'`""
$splat = @{
'FileName' = $powershellPath
'Arguments' = $arguments
'WorkingDirectory' = $input_workingDirectory
}
# Switch to "Continue".
$global:ErrorActionPreference = 'Continue'
$failed = $false
# Run the script.
Write-Host '========================== Starting Command Output ==========================='
if (!$input_failOnStderr) {
Invoke-VstsTool @splat
}
else {
$inError = $false
$errorLines = New-Object System.Text.StringBuilder
Invoke-VstsTool @splat 2>&1 |
ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) {
# Buffer the error lines.
$failed = $true
$inError = $true
$null = $errorLines.AppendLine("$($_.Exception.Message)")
# Write to verbose to mitigate if the process hangs.
Write-Verbose "STDERR: $($_.Exception.Message)"
}
else {
# Flush the error buffer.
if ($inError) {
$inError = $false
$message = $errorLines.ToString().Trim()
$null = $errorLines.Clear()
if ($message) {
Write-VstsTaskError -Message $message -IssueSource $IssueSources.CustomerScript
}
}
Write-Host "$_"
}
}
# Flush the error buffer one last time.
if ($inError) {
$inError = $false
$message = $errorLines.ToString().Trim()
$null = $errorLines.Clear()
if ($message) {
Write-VstsTaskError -Message $message -IssueSource $IssueSources.CustomerScript
}
}
}
# Fail on $LASTEXITCODE
if (!(Test-Path -LiteralPath 'variable:\LASTEXITCODE')) {
$failed = $true
Write-Verbose "Unable to determine exit code"
Write-VstsTaskError -Message (Get-VstsLocString -Key 'PS_UnableToDetermineExitCode')
}
else {
if ($LASTEXITCODE -ne 0) {
$failed = $true
Write-VstsTaskError -Message (Get-VstsLocString -Key 'PS_ExitCode' -ArgumentList $LASTEXITCODE)
}
}
# Fail if any errors.
if ($failed) {
Write-VstsSetResult -Result 'Failed' -Message "Error detected" -DoNotThrow
}
}
catch {
Write-VstsTaskError -Message $_.Exception.Message
Write-VstsSetResult -Result 'Failed' -Message "Error detected" -DoNotThrow
}
finally {
Trace-VstsLeavingInvocation $MyInvocation
}