Skip to content

CLI: script blocks as external program arguments break the command #10842

Closed

Description

Note that this applies to calling external programs, including PowerShell's CLI, from within PowerShell

Passing a single script block containing the entire command to the PowerShell executable is a convenient way to pass a command from within PowerShell (a) without having to worry about quoting and (b) actually getting deserialized objects back (not just text).

PS> pwsh -noprofile { 'hi' }  #  -Command implied.

hi   # OK

Behind the scenes, the script block is Base64-encoded and the command line is transformed to using the -EncodedCommand parameter with the encoded script block (along with parameters -inputFormat xml and -outputFormat xml)

However, this transformation is mistakenly also applied if you attempt to pass a script block as an individual argument to a -File command:

Update: More generally, the inappropriate argument transformation is applied when invoking any external program, and a script block is used as any of its arguments; e.g., /bin/echo { 'hi' }

Steps to reproduce

Describe "Pass a script block as an argument with -File" {
  BeforeAll {
    Push-Location testdrive:\
    # Test script that simply echoes its arguments.
    '$args' > test.ps1
  }
  It "Passes the script block as a string." {
    # The script block should be stringified and therefore be passed
    # as ' hi '
    pwsh -noprofile -file ./test.ps1 { 'hi' } | Should -Be ' hi '
  }
  AfterAll {
    Pop-Location
  }
}

Expected behavior

The test should pass.

Actual behavior

The test fails:

Expected ' hi ', but got 
@('-encodedCommand', 'IAAnAGgAaQAnACAA', '-inputFormat', 'xml', '-outputFormat', 'xml').

Note how the script-block argument - meant to be an argument to the script passed to -File - was inappropriately translated into the -encodedCommand ... arguments and passed to the target script.

Environment data

PowerShell Core 7.0.0-preview.4

Activity

  1. added
    Issue-Question
    on Oct 19, 2019
  2. changed the title [-]CLI: script block as individual arguments break the command[/-] [+]CLI: script blocks as -File arguments break the command[/+] on Oct 19, 2019
  3. added
    WG-Engine
    Issue-Bug
    and removed
    Issue-Question
    on Oct 19, 2019
  4. BrucePay commented on Oct 21, 2019

    @BrucePay
    Collaborator
      • It's practically impossible to pass a scriptblock as an argument unless it's encoded because embedding the raw text will result in all sorts of parse errors.
      • Passing a scriptblock to -File makes no sense as the parameter requires a file name.
      • The calling PowerShell process doesn't try to infer anything about the parameter processing of the child process. This comes from the "minishell" era where there would be a bunch of powershell hosts exposing parameters with a variety of parameters that take scriptblocks.
  5. mklement0 commented on Oct 21, 2019

    @mklement0
    ContributorAuthor

    Thanks, Bruce Payette (@BrucePay) - how does any of this (especially 2.) relate to this bug report, which is about an obvious mis-application of the base64-encoding-behind-the-scenes technique?

    To recap from the OP:

    However, this transformation is mistakenly also applied if you attempt to pass a script block as an individual argument to a -File command:

    Once we agree that this is a bug (which seems pretty obvious to me), we can talk about what the correct behavior should be in this - exotic - scenario:

    Given:

    PS> /bin/echo @{ foo = 1 }
    System.Collections.Hashtable
    

    i.e., simple .ToString() stringification is normally applied, so the same should apply to script blocks:

    PS> /bin/echo { 'foo = 1' }
     'foo = 1'
    

    That is, the literal contents of the script block should be passed - that this may break due to PowerShell's broken quoting for external programs is a separate issue.

    Just to demonstrate that the current behavior doesn't make sense (actually a simpler repro than in the OP):

    PS> /bin/echo { 'foo = 1' }
    -encodedCommand IAAnAGYAbwBvACAAPQAgADEAJwAgAA== -inputFormat xml -outputFormat text
    

    Oops.

  6. BrucePay commented on Oct 22, 2019

    @BrucePay
    Collaborator

    stringification is normally applied, so the same should apply to script blocks:

    That is explicitly not true for scriptblocks. The current behaviour is entirely by design. Whenever a scriptblock is passed, it is always passed encoded so the following can work:

    PS[1] (69) > $data = powershell {
    >> foreach ($i in 1..10)
    >> {
    >>     $i * 2
    >> }
    >> }                                                                                                                                                  PS[1] (70) > "$data"                                                                                                                                  2 4 6 8 10 12 14 16 18 20
  7. mklement0 commented on Oct 22, 2019

    @mklement0
    ContributorAuthor

    Bruce Payette (@BrucePay):

    it is always passed encoded so the following can work:

    That makes perfect sense when calling the PowerShell CLI - and there only if the encoded command makes up everything to execute.

    It makes no sense when calling other external programs - and that is the bug.
    To recap (on macOS and Linux):

    PS> /bin/echo { 'foo = 1' }
    -encodedCommand IAAnAGYAbwBvACAAPQAgADEAJwAgAA== -inputFormat xml -outputFormat text
    

    Passing these arguments to the /bin/echo Unix utility is self-evidently pointless.

  8. BrucePay commented on Oct 24, 2019

    @BrucePay
    Collaborator

    Since PowerShell is hostable, there is no way to know all of the executables that could take script block so we do it for everything. Conversely, there is no reason to try to pass scriptblocks to anything but a powershell host so why does it matter?

    Passing these arguments to the /bin/echo Unix utility is self-evidently pointless.

    Even if it wasn't encoded it would be pointless so why would you do it?

  9. mklement0 commented on Oct 25, 2019

    @mklement0
    ContributorAuthor

    Bruce Payette (@BrucePay):

    Let's start with an external program that we know to host PowerShell:

    # Create a test .ps1 file that simply echoes its arguments ,
    # invoke it with -File and pass it a script block.
    PS> '"$args"' > temp:/test.ps1; pwsh -noprofile -file (Convert-Path temp:/test.ps1) { 'hi' }
    
    -encodedCommand IAAnAGgAaQAnACAA -inputFormat xml -outputFormat text

    It clearly doesn't make sense to expect arbitrary script file test.ps1 to know how to to interpret these arguments, which are solely meaningful to PowerShell's own CLI.

    Even if we - unwarrantedly - assume that all external programs host PowerShell, there is no no reason to assume that they speak this particular flavor of CLI syntax - that is not a requirement for programs hosting PowerShell.

    In short: Translating script blocks to -encodedCommand ... -inputFormat xml -outputFormat text only ever makes sense:

    • if pwsh[.exe] or powershell.exe is the external program being invoked
    • and the script block is the - one and only - -c / -Command argument.

    That this was the - incompletely implemented - original intent can be gleaned from the error message emitted by the following:

    PS> pwsh -noprofile -c foo bar { 'hi' }
    
    pwsh : ScriptBlock should only be specified as a value of the Command parameter.
    

    Any other application of this argument translation is pointless and a bug worth fixing - see OP.

  10. changed the title [-]CLI: script blocks as -File arguments break the command[/-] [+]CLI: script blocks as external program arguments break the command[/+] on Oct 28, 2019
  11. mklement0 commented on Oct 28, 2019

    @mklement0
    ContributorAuthor

    As for when people may want to pass script blocks to non-PowerShell commands:

    Script blocks are often - treacherously - repurposed to serve as string literals that make embedded quoting easier.

    (It is treacherous, because a command then wrongly suggests that a piece of PowerShell code is being passed, whereas the stringification simply uses the verbatim content, without expansion of variables / expressions; this ill-advised use is what created the AD filter debacle, but at this point it is hard to eradicate).

    That is, user do craft commands such as the following:

    # The .ToString() value of the script block is bound to -ArgumentList
    Start-Process -Wait bash { -c "echo hi" }

    The above works, because Start-Process is a cmdlet, not an external program, so the misapplication of the -EncodedCommand argument transformation doesn't kick in - but there is no reason why

    bash { -c "echo hi" }

    shouldn't work the same (however ill-advised).

  12. lzybkr commented on Oct 28, 2019

    @lzybkr
    Contributor

    This behavior also causes problems calling commands that expect strings that happen to look like a scriptblock, e.g.

    bcdedit /default {18472fcd-c28f-11e8-9869-8f778f73c317}

    I feel reasonably sure this isn't the only such tool, but I can't recall specific examples.

  13. mklement0 commented on Oct 28, 2019

    @mklement0
    ContributorAuthor

    Good point, Jason Shirk (@lzybkr), though if we consistently apply .ToString() stringification to what are syntactically script-block arguments in string contexts (which by definition includes external-program arguments), bcdedit would only see 18472fcd-c28f-11e8-9869-8f778f73c317, which is not the intent - though a failure should still be easier to diagnose than the appearance of completely unexpected arguments.

    This takes us back to venerable #1761

    My vote is again not to special-case the external-program behavior.

  14. mklement0 commented on Aug 9, 2020

    @mklement0
    ContributorAuthor

    Just realized that this is ultimately a duplicate of #5187.

  15. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  16. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  17. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  18. added
    Resolution-No Activity
    on Nov 16, 2023
  19. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugResolution-No ActivityWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions