07-21-2023, 11:13 AM
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 <i>Write-Foo.ps1</i>, 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 <i>env</i> utility, but it decouples the scripts from Cygwin's path prefix (<i>/cygdrive/c/...</i>), 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 <i>.ps1</i> 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.**](
$ 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 <i>env</i> utility, but it decouples the scripts from Cygwin's path prefix (<i>/cygdrive/c/...</i>), 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 <i>.ps1</i> 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.**](
[To see links please register here]
)