Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

bash - How can I use a shebang in a PowerShell script?

I have several PowerShell scripts that I'd like to invoke directly as a command from a Bash shell in Cygwin. For example, if I write a script with the filename Write-Foo.ps1, I'd like to execute it as a command from any working directory:

$ Write-Foo.ps1 arg1 arg2 ...

To do this, I add the script to my PATH, make it executable, and include the following interpreter shebang/hashbang at the beginning of the file:

#!/usr/bin/env powershell

Write-Host 'Foo'
...

It's a common (ab)use of the env utility, but it decouples the scripts from Cygwin's path prefix (/cygdrive/c/...), at least for the interpreter declaration.

This works to start PowerShell, but the system passes the file as a Cygwin-formatted path, which PowerShell doesn't understand, of course:

The term '/cygdrive/c/path/to/Write-Foo.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.

MSYS (Git Bash) seems to translate the script path correctly, and the script executes as expected, as long as the path to the file contains no spaces. Is there a way to invoke a PowerShell script directly by relying on the shebang in Cygwin?

Ideally, I'd also like to omit the .ps1 extension from the script names if possible, but I understand that I may need to live with this limitation. I want to avoid manually aliasing or wrapping the scripts if possible.


A quick note for Linux/macOS users finding this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Quick note for Linux/macOS users finding this:

  • Ensure the pwsh or powershell command is in PATH
  • Use this interpreter directive: #!/usr/bin/env pwsh
  • Ensure the script uses Unix-style line endings ( , not )

Thanks to briantist's comments, I now understand that this isn't directly supported for PowerShell versions earlier than 6.0 without compromises:

...[in PowerShell Core 6.0] they specifically changed positional parameter 0 from ‑Command to ‑File to make that work. ...the error message you're getting is because it's passing a path to ‑Command...

A Unix-like system passes the PowerShell script's absolute filename to the interpreter specified by the "shebang" as the first argument when we invoke the script as a command. In general, this can sometimes work for PowerShell 5 and below because PowerShell, by default, interprets the script filename as the command to execute.

However, we cannot rely on this behavior because when PowerShell's handles -Command in this context, it re-interprets the filename as if it was typed at the prompt, so the path of a script that contains spaces or certain symbols will break the "command" that PowerShell sees as the argument. We also lose a bit of efficiency for the preliminary interpretation step.

When specifying the -File parameter instead, PowerShell loads the script directly, so we can avoid the problems we experience with -Command. Unfortunately, to use this option in the shebang line, we need to sacrifice the portability we gain by using the env utility described in the question because operating system program loaders usually allow only one argument to the program declared in the script for the interpreter.

For example, the following interpreter directive is invalid because it passes two arguments to the env command (powershell and -File):

#!/usr/bin/env powershell -File

In an MSYS system (like Git Bash), on the other hand, a PowerShell script that contains the following directive (with the absolute path to PowerShell) executes as expected:

#!/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -File

...but we cannot directly execute the script on another system that doesn't follow the same filesystem convention.


This also doesn't fix the original problem in Cygwin. As described in the question, the path to the script itself isn't translated to a Windows-style path, so PowerShell cannot locate the file (even in version 6). I figured out a couple of workarounds, but neither provide a perfect solution.

The simplest approach just exploits the default behavior of PowerShell's -Command parameter. After adding the Write-Foo.ps1 script to the environment's command search path (PATH), we can invoke PowerShell with the script name, sans the extension:

$ powershell Write-Foo arg1 arg2 ...

As long as the script file itself doesn't contain spaces in the filename, this allows us to run the script from any working directory—no shebang needed. PowerShell uses a native routine to resolve the command from the PATH, so we don't need to worry about spaces in the parent directories. We lose Bash's tab-completion for the command name, though.

To get the shebang to work in Cygwin, I needed to write a proxy script that converts the path style of the invoked script to a format that PowerShell understands. I called it pwsh (for portability with PS 6) and placed it in the PATH:

#!/bin/sh

if [ ! -f "$1" ]; then 
    exec "$(command -v pwsh.exe || command -v powershell.exe)" "$@"
    exit $?
fi

script="$(cygpath -w "$1")"
shift

if command -v pwsh.exe > /dev/null; then 
    exec pwsh.exe "$script" "$@"
else
    exec powershell.exe -File "$script" "$@"
fi

The script begins by checking the first argument. If it isn't a file, we just start PowerShell normally. Otherwise, the script translates the filename to a Windows-style path. This example falls back to powershell.exe if pwsh.exe from version 6 isn't available. Then we can use the following interpreter directive in the script...

#!/usr/bin/env pwsh

...and invoke a script directly:

$ Write-Foo.ps1 arg1 arg2 ...

For PowerShell versions before 6.0, the script can be extended to symlink or write out a temporary PowerShell script with a .ps1 extension if we want to create the originals without an extension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...