Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Paule96/warnings powershell #13122

Merged
merged 17 commits into from
Oct 16, 2020
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 54 additions & 32 deletions Tasks/PowerShellV2/powershell.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}

Expand All @@ -34,7 +36,8 @@ try {
}

$input_arguments = Get-VstsInput -Name 'arguments'
} else {
}
paule96 marked this conversation as resolved.
Show resolved Hide resolved
else {
$input_script = Get-VstsInput -Name 'script'
}

Expand All @@ -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")
}

Expand All @@ -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,
Expand All @@ -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
}

Expand All @@ -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) {
Expand All @@ -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)
Expand All @@ -154,6 +175,7 @@ try {
if ($failed) {
Write-VstsSetResult -Result 'Failed' -Message "Error detected" -DoNotThrow
}
} finally {
}
finally {
Trace-VstsLeavingInvocation $MyInvocation
}
27 changes: 21 additions & 6 deletions Tasks/PowerShellV2/powershell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 {
Expand All @@ -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)) {`);
Expand Down Expand Up @@ -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));
Expand Down
15 changes: 12 additions & 3 deletions Tasks/PowerShellV2/task.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
"author": "Microsoft Corporation",
"version": {
"Major": 2,
"Minor": 170,
"Patch": 1
"Minor": 177,
paule96 marked this conversation as resolved.
Show resolved Hide resolved
"Patch": 0
},
"releaseNotes": "Script task consistency. Added support for macOS and Linux.",
"minimumAgentVersion": "2.115.0",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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."
}
}
}
4 changes: 2 additions & 2 deletions Tasks/PowerShellV2/task.loc.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down