1

In WSL2 I want to run a powershell command and get the output of the command to print to stdout on my WSL2.

I have tried many variants but it seems I always just get the command given back and not its output:

$ pwsh.exe -Command {Get-Date}
Get-Date

$ pwsh.exe -Command '{Write-Output "hello"}'
Write-Output "hello"
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • See following : https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/types-of-cmdlet-output?view=powershell-7.3 – jdweng Feb 10 '23 at 21:56

2 Answers2

2

You should not use curly braces here :

pwsh.exe -Command 'Get-Date'
Philippe
  • 20,025
  • 2
  • 23
  • 32
1

Philippe's helpful answer provides the crucial pointer:

When calling pwsh, the PowerShell (Core) CLI, from outside PowerShell:

  • Do not use { ... } to enclose your command(s) - that only works from inside PowerShell.

    • Inside PowerShell, { ... } creates a script block literal, which is a reusable piece of PowerShell code that can be invoked on demand.

    • If you pass { ... } to pwsh from inside PowerShell, special processing happens behind the scenes, which notably preserves type fidelity in the output as much as possible - see this answer for details.

    • It should be noted that calling the PowerShell CLI from PowerShell is rarely necessary, except, for instance, on Windows, if you want to call the respective other PowerShell edition's CLI.

  • Instead, pass your command(s) as-is, inside a string.

    • If you pass a string to -Command from outside PowerShell with { ... } embedded, what happens is that PowerShell creates a script block and - in the absence of invoking it, with & or . - its string representation is output, which is the block's verbatim content (excluding { and }) - that is what you saw.

    • As an aside: There are many examples out there that use "& { ... }" as a -Command argument; while that technically works, it is unnecessary, and passing just "..." (or '...', from POSIX-compatible shells) is sufficient.

Thus:

# Simple case: no quoting necessary
$ pwsh.exe -Command Get-Date

# Command string that requires quoting:
$ pwsh.exe -Command 'Write-Output "hello"'
mklement0
  • 382,024
  • 64
  • 607
  • 775