Skip to content

Strict Write-Output #15781

Closed
Closed

Description

@iRon7

Summary of the new feature / enhancement

Write-Output description excerpt:

In PowerShell, it is generally not necessary to use the cmdlet in instances where the output is displayed by default.

This is a very nice feature but at the other hand could cause quite some confusion for a novice PowerShell scripter or with complex (recursive) functions as it implies that unwanted objects (including $null) could be accidently dropped into the pipeline by an included command (function, method or cmdlet) without notice.
Besides, if it known that a custom function leaks objects into the pipeline, it might still be a hassle to actually track them down.

See StackOverflow issues along with:

Proposed technical implementation details (optional)

Despite the reasons to avoid the use of the Write-Output cmdlet, it would be nice to have a Set-StrictMode version that enforces the use of Write-Output or Return. Meaning, if anything is placed on the pipeline that doesn't come from Write-Output or Return, a "strict" error should be raised pushing for a fix either way:

  • If it was the intention to add something to the pipeline, use the Write-Output cmdlet.
  • if it was not the intention to add anything to the pipeline, waste the results by using the [Void] initiator or assigning it
    (e.g. $Null = ...)

Caveats

  • I have no clue how difficult it is to determine whether a function or method always returns nothing or for a cmdlet (like Export-Csv) always returns a System.Management.Automation.Internal.AutomationNull.
  • I suspect that that external commands should always be voided ([void](NotePad)) or assigned ($Null = NotePad)
  • As Set-StrictMode is also applied to the child scopes, I presume that custom child functions can just be checked for the existence of Write-Host or return statement to determine whether something is returned.

Actually, at second thought, the above caveats ar probably not relevant as the strict check (whether Write-Output or Return is used when something is added to the pipeline) should take place at runtime.

  • Set-StrictMode can be set from within a function but could also be set (temporary for trouble shooting) at the prompt level (or even at a global scope with Set-PSDebug -Strict command). The indiscriminate implication of this request would be that every expression (including a simple expression-mode calculation as 2 * 3 or .\MyTestFunction.ps1 invocation) would require a Write-Output (as: 2 * 3 |Write-Output or .\MyTestFunction.ps1 |Write-Output) unless exceptions are made at the top/shell-level.

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Jul 15, 2021
  2. added
    WG-Engine
    WG-Language
    on Jul 15, 2021
  3. mklement0 commented on Nov 1, 2021

    @mklement0
    Contributor

    The pitfall of accidental output is real, but I wonder if it is better addressed with a debugging feature rather than a new strict mode, which would in essence take away a fundamental PowerShell feature (implicit output). Also, as a fundamental problem, the lack of lexical scoping makes any strict mode liable to break unrelated code.

    Therefore, I wonder if enhancing, say, Set-PSDebug is a better way forward, allowing users to locate all lines in their script that produce output in a given call.

    # HYPOTHETICAL example.
    # As an aside: -Trace is currently [int]-typed  - switching to an *enum* with descriptive symbolic value names
    # would make sense.
    # 3 == hypothetical new output-tracing flag
    PS> Set-PSDebug -Trace 3; ./script.ps1
    
    DEBUG:    8+  >>>> $arrayList.Add($foo)
    0

    That is, the above indicates that the statement on line 8 produced output.


    As a stopgap you can use the following technique to print the locations and source code of output-producing statements:

    PS> ./script.ps1 | % { 
      Write-Verbose -vb "Output from $(($entry=(Get-PsCallStack)[1]).Location): $($entry.Position.Text)"; $_ 
    }
    
    VERBOSE: Output from script.ps1: line 8: $arrayList.Add($foo)
    0
  4. iRon7 commented on Nov 7, 2021

    @iRon7
    Author

    Michael Klement (@mklement0), thanks for the comments, I indeed also like the Set-PSDebug idea.

    a new strict mode, which would in essence take away a fundamental PowerShell feature (implicit output). Also, as a fundamental problem, the lack of lexical scoping makes any strict mode liable to break unrelated code.

    I agree, the idea is quite controversy. Yet avoiding accidental pitfalls is exactly why someone would prefer strict programming (modes). Besides it is an optional choice. By default, PowerShell is still a loosely programming language.

  5. mklement0 commented on Nov 9, 2021

    @mklement0
    Contributor

    Re Set-PSDebug: Glad to hear it, iRon7.

    Re introducing new strict modes in general: I am wary:

    • The lack of lexical scoping of strict modes makes their use treacherous.
    • Even if lexical scoping were to be introduced, the dynamic scoping of the existing strict modes would have to be retained for backward compatibility, which would invite confusion and subtle bugs.
    • Generally, strict modes make it harder to reason about a given piece of code.

    As for the specific new mode proposed:

    • While such a mode would undoubtedly help, to me the philosophical question is whether carving out a "non-PowerShell niche" inside of PowerShell that subscribes to a different output philosophy is worth doing.

    Therefore, my personal preference would be to help prevent this pitfall via debugging and linting features (PSSA, also as an opt-in).

  6. mklement0 commented on Dec 7, 2021

    @mklement0
    Contributor

    iRon7, I assume you meant to post this comment here instead:

    Michael Klement (@mklement0),

    Even if lexical scoping were to be introduced, the dynamic scoping of the existing strict modes would have to be >> retained for backward compatibility, which would invite confusion and subtle bugs.

    A different way to implement lexical scoping is by excluding using SuppressMessageAttribute class in the cmdlet binding similar to the approach of PSScriptAnalyzer.

    That would certainly fix the scoping issue (it could even be a property of the existing CmdletBinding attribute) and make code easier to reason about.

    However, requiring the use of an attribute - undoubtedly an advanced technique - could prove too high of a hurdle for the intended target audience, novice scripters. (For those comfortable with implicit output who are merely looking to troubleshoot code, a Set-PSDebug solution should suffice.)

  7. removed
    Needs-Triage
    on Jan 20, 2022
  8. daxian-dbw commented on Jan 21, 2022

    @daxian-dbw
    Member

    The Engine WG reviewed this issue today. We don't think introducing a new strict mode is the right way to help prevent this issue because that could easily break other scripts. If a script uses strict mode, then most likely it's using Set-StrictMode latest, which means new strict mode like the proposed one will be applied to it, and thus potentially break the script.

    We believe PowerShell Script Analyzer should be the right tool to help, by emitting warnings for expressions that generate output directly to pipeline. Feel free to open an issue in that repo.

  9. added
    Resolution-Declined
    on Jan 21, 2022
  10. ghost closed this as completedon Jan 22, 2022
  11. iRon7 commented on Jan 24, 2022

    @iRon7
    Author

    Sorry, I was on holidays and couldn't immediately respond.

    If a script uses strict mode, then most likely it's using Set-StrictMode latest, which means new strict mode like the proposed one will be applied to it, and thus potentially break the script.

    This argument is more related to the implementation of Set-StrictMode and how the scope is linked to a version rather than a lexical scoping using a different parameter or cmdlet annotations (using the System.Diagnostics.CodeAnalysis Namespace?) instead. See also: #16388 -Mode parameter for Set-StrictMode.

    We believe PowerShell Script Analyzer should be the right tool to help, by emitting warnings for expressions that generate output directly to pipeline. Feel free to open an issue in that repo.

    Afaik, PowerShell Script Analyzer is not able to catch runtime errors/situation knowing that a (custom) function/cmdlet could potentially return an object but effectively never does during runtime...
    Anyways, I am happy to give it a try if you think otherwise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Issue-EnhancementResolution-DeclinedWG-EngineWG-Language

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions