PowerShell / vscode-powershell

Provides PowerShell language and debugging support for Visual Studio Code

Home Page:https://marketplace.visualstudio.com/items/ms-vscode.PowerShell

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Show warning when writing to the output stream in a function with a return value.

NickSt opened this issue · comments

Prerequisites

  • I have written a descriptive issue title.
  • I have searched all issues to ensure it has not already been reported.

Summary

In a powershell function with a return value, any time the standard output stream is written to, it appends the those results to the output by transforming the output into an array. For Example

 function demonstration {
    echo "Starting demonstration"
    $returnHashMap = @{}
    Write-Output "building hashmap"
    $returnHashMap["key1"] = "value1"
    $returnHashMap["key2"] = "value2"
    Write-Output "hashmap built"

    return $returnHashMap
}
$x = demonstration
echo $x | ConvertTo-Json

This produces the following output :

[
  "Starting demonstration",
  "building hashmap",
  "hashmap built",
  {
    "key2": "value2",
    "key1": "value1"
  }
]

note the actual return value is a submember of an array.
if you wanted to access the hashmap at this point you have to first access its index in the array so for instance:
echo $x[3]['key1']

This behavior is almost always undesirable. I'd request that the extension provide a warning when doing this.

Proposed Design

I'd propose that the extension underline in yellow (warning) any time echo or write-output is used in a function that has a return command. If logging is desired write-information or (debug, verbose etc) can be used instead without the same effects.

Thank you for your submission!

This would be more appropriate as a PSScriptAnalyzer warning rule, there isn't much we can do within the vscode-powershell repo directly on this. I suggest you reopen the issue there, and if a rule is created (or you create your own and bring it in), the intellisense will take effect within the extension, as the extension just uses PSScriptAnalyzer to do this analysis anyways.

https://github.com/PowerShell/PSScriptAnalyzer