MicrosoftDocs / PowerShell-Docs

The official PowerShell documentation sources
https://learn.microsoft.com/powershell
Creative Commons Attribution 4.0 International
1.93k stars 1.55k forks source link

Mention the quasi-interactive, REPL-like behavior of `-File -` and `-Command -` and a workaround #11098

Open mklement0 opened 2 months ago

mklement0 commented 2 months ago

Type of issue

Missing information

Feedback

It is reasonable for users - especially those familiar with POSIX-compatible shells such as Bash - to expect -File - to treat its stdin input as a whole as if it were the content of a script file. -Command - does not have a POSIX-compatible shell counterpart, but the expectation applies analogously.

Unfortunately, both -File - and -Command - exhibit quasi-interactive behavior that seems to be geared toward supporting REPL-like functionality via stdin: see https://github.com/PowerShell/PowerShell/issues/21808#issuecomment-2103258649 for a summary.

To get the expected behavior, the following workaround is currently required, which is worth mentioning:

Example:

@'
& { 
  Get-Date
  $PROFILE
}

'@ |
  pwsh -NoProfile -Command -
pwsh -NoProfile -Command - <<'EOF'
& { 
  Get-Date
  $PROFILE
}

EOF

Note that, without the extra newline (empty line), both commands above currently provide no output, which is a bug discussed in:

Page URL

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Pwsh?view=powershell-7.4

Content source URL

https://github.com/MicrosoftDocs/PowerShell-Docs/blob/main/reference/7.4/Microsoft.PowerShell.Core/About/about_Pwsh.md

Author

@sdwheeler

Document Id

4ccd2aa8-1a49-5b9d-04ee-5d2c61fb3c38