diff --git a/Tasks/PowerShellV2/powershell.ps1 b/Tasks/PowerShellV2/powershell.ps1 index 3c15ebabbf21..3393eecf83bc 100644 --- a/Tasks/PowerShellV2/powershell.ps1 +++ b/Tasks/PowerShellV2/powershell.ps1 @@ -15,6 +15,7 @@ try { Write-Error (Get-VstsLocString -Key 'PS_InvalidErrorActionPreference' -ArgumentList $input_errorActionPreference) } } + $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 @@ -25,7 +26,8 @@ try { $input_filePath = Get-VstsInput -Name 'filePath' -Require try { Assert-VstsPath -LiteralPath $input_filePath -PathType Leaf - } catch { + } + catch { Write-Error (Get-VstsLocString -Key 'PS_InvalidFilePath' -ArgumentList $input_filePath) } @@ -34,7 +36,8 @@ try { } $input_arguments = Get-VstsInput -Name 'arguments' - } else { + } + else { $input_script = Get-VstsInput -Name 'script' } @@ -48,7 +51,8 @@ try { if ("$input_targetType".ToUpperInvariant() -eq 'FILEPATH') { $contents += ". '$("$input_filePath".Replace("'", "''"))' $input_arguments".Trim() Write-Host (Get-VstsLocString -Key 'PS_FormattedCommand' -ArgumentList ($contents[-1])) - } else { + } + else { $contents += "$input_script".Replace("`r`n", "`n").Replace("`n", "`r`n") } @@ -61,14 +65,27 @@ try { $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") - $joinedContents = [System.String]::Join( - ([System.Environment]::NewLine), - $contents) $null = [System.IO.File]::WriteAllText( $filePath, $joinedContents, @@ -80,14 +97,15 @@ try { # 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 { + } + else { $powershellPath = Get-Command -Name powershell.exe -CommandType Application | Select-Object -First 1 -ExpandProperty Path } Assert-VstsPath -LiteralPath $powershellPath -PathType 'Leaf' $arguments = "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command `". '$($filePath.Replace("'", "''"))'`"" $splat = @{ - 'FileName' = $powershellPath - 'Arguments' = $arguments + 'FileName' = $powershellPath + 'Arguments' = $arguments 'WorkingDirectory' = $input_workingDirectory } @@ -99,33 +117,35 @@ try { Write-Host '========================== Starting Command Output ===========================' if (!$input_failOnStderr) { Invoke-VstsTool @splat - } else { + } + 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 - } - } + ForEach-Object { + if ($_ -is [System.Management.Automation.ErrorRecord]) { + # Buffer the error lines. + $failed = $true + $inError = $true + $null = $errorLines.AppendLine("$($_.Exception.Message)") - Write-Host "$_" + # 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 + } } + + Write-Host "$_" } + } # Flush the error buffer one last time. if ($inError) { @@ -143,7 +163,8 @@ try { $failed = $true Write-Verbose "Unable to determine exit code" Write-VstsTaskError -Message (Get-VstsLocString -Key 'PS_UnableToDetermineExitCode') - } else { + } + else { if ($LASTEXITCODE -ne 0) { $failed = $true Write-VstsTaskError -Message (Get-VstsLocString -Key 'PS_ExitCode' -ArgumentList $LASTEXITCODE) @@ -154,6 +175,7 @@ try { if ($failed) { Write-VstsSetResult -Result 'Failed' -Message "Error detected" -DoNotThrow } -} finally { +} +finally { Trace-VstsLeavingInvocation $MyInvocation } diff --git a/Tasks/PowerShellV2/powershell.ts b/Tasks/PowerShellV2/powershell.ts index ad8dd97843f7..e4b85ef5dcf3 100644 --- a/Tasks/PowerShellV2/powershell.ts +++ b/Tasks/PowerShellV2/powershell.ts @@ -19,6 +19,7 @@ async function run() { default: throw new Error(tl.loc('JS_InvalidErrorActionPreference', input_errorActionPreference)); } + let input_showWarnings = tl.getBoolInput('showWarnings', false); let input_failOnStderr = tl.getBoolInput('failOnStderr', false); let input_ignoreLASTEXITCODE = tl.getBoolInput('ignoreLASTEXITCODE', false); let input_workingDirectory = tl.getPathInput('workingDirectory', /*required*/ true, /*check*/ true); @@ -34,7 +35,7 @@ async function run() { input_arguments = tl.getInput('arguments') || ''; } - else if(input_targetType.toUpperCase() == 'INLINE') { + else if (input_targetType.toUpperCase() == 'INLINE') { input_script = tl.getInput('script', false) || ''; } else { @@ -45,13 +46,28 @@ async function run() { console.log(tl.loc('GeneratingScript')); let contents: string[] = []; contents.push(`$ErrorActionPreference = '${input_errorActionPreference}'`); + let script = ''; if (input_targetType.toUpperCase() == 'FILEPATH') { - contents.push(`. '${input_filePath.replace(/'/g, "''")}' ${input_arguments}`.trim()); - console.log(tl.loc('JS_FormattedCommand', contents[contents.length - 1])); + script = `. '${input_filePath.replace(/'/g, "''")}' ${input_arguments}`.trim(); + } else { + script = `${input_script}`; } - else { - contents.push(input_script); + if (input_showWarnings) { + script = ` + $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 {${script}} -WarningVariable +warnings; + `; } + contents.push(script); + // log with detail to avoid a warning output. + tl.logDetail(uuidV4(), tl.loc('JS_FormattedCommand', script), null, 'command', 'command', 0); if (!input_ignoreLASTEXITCODE) { contents.push(`if (!(Test-Path -LiteralPath variable:\LASTEXITCODE)) {`); @@ -116,7 +132,6 @@ async function run() { // Run bash. let exitCode: number = await powershell.exec(options); - // Fail on exit code. if (exitCode !== 0) { tl.setResult(tl.TaskResult.Failed, tl.loc('JS_ExitCode', exitCode)); diff --git a/Tasks/PowerShellV2/task.json b/Tasks/PowerShellV2/task.json index 15251508df26..2084c00d1718 100644 --- a/Tasks/PowerShellV2/task.json +++ b/Tasks/PowerShellV2/task.json @@ -17,8 +17,8 @@ "author": "Microsoft Corporation", "version": { "Major": 2, - "Minor": 170, - "Patch": 1 + "Minor": 177, + "Patch": 0 }, "releaseNotes": "Script task consistency. Added support for macOS and Linux.", "minimumAgentVersion": "2.115.0", @@ -97,6 +97,15 @@ "helpMarkDown": "If this is true, this task will fail if any errors are written to the error pipeline, or if any data is written to the Standard Error stream. Otherwise the task will rely on the exit code to determine failure.", "groupName": "advanced" }, + { + "name": "showWarnings", + "type": "boolean", + "label": "Show warnings as Azure DevOps warnings", + "required": false, + "defaultValue": "false", + "helpMarkDown": "If this is true, and your script writes a warnings - they are shown as warnings also in pipeline logs", + "groupName": "advanced" + }, { "name": "ignoreLASTEXITCODE", "type": "boolean", @@ -151,4 +160,4 @@ "PS_InvalidFilePath": "Invalid file path '{0}'. A path to a .ps1 file is required.", "PS_UnableToDetermineExitCode": "Unexpected exception. Unable to determine the exit code from powershell." } -} \ No newline at end of file +} diff --git a/Tasks/PowerShellV2/task.loc.json b/Tasks/PowerShellV2/task.loc.json index 7a4f1c8481a5..896b461791e5 100644 --- a/Tasks/PowerShellV2/task.loc.json +++ b/Tasks/PowerShellV2/task.loc.json @@ -17,8 +17,8 @@ "author": "Microsoft Corporation", "version": { "Major": 2, - "Minor": 170, - "Patch": 1 + "Minor": 177, + "Patch": 0 }, "releaseNotes": "ms-resource:loc.releaseNotes", "minimumAgentVersion": "2.115.0",