I develop on Windows. And somehow got into the habit of using both the powershell and the git bash. It's not clear cut, but generally speaking i use git bash for small tasks and moving around the file system. When writing longer scripts i tend to use powershell.
This week i stumbled about a nice way to execute a powershell script from the bash. This helps to reduce context switches.
You have to use the following Statement
$ powershell -File scriptToRun.ps1
When you use an alias it gets even more convinient
$ alias ps1='powershell -File'
$ ps1 scriptToRun.ps1
Addition
Another way to run powershell scripts was suggested by a reader in the comments.
❗ First you have to make sure that the powershell.exe is on the path.
Then add the following shebang line at the start of your script:
#!/usr/bin/env pwsh
"Hello world!"
$ ./helloWorld.ps1
Hello world!
Thank you again @vitalytseshkovsky!
Top comments (5)
The solution can be done in UX-script style by using shebang feature:
powershell
orpwsh
is in the path.#!/usr/bin/env powershell
or#!/usr/bin/env pwsh
at the beginning of scriptdos2unix
on it.Now the script can be launched as regular UX-script from bash and as regular power shell script from PS-shell or Windows File Explorer (because shebang is interpreted as a comment by power shell).
Example test.ps1:
I could not get it to run with
#!/usr/bin/env powershell
but the other shebang line worked. I updated the blog post. I will try to get the other shebang line working as well.Thank you. Will later try it out and add it to the post.
It's a bad idea to make an alias with the same name as an existing bash command "ps". In this case the better choice for alias is ps1, not ps.
Yes, you are absolutely right. Thank you for pointing this out. 😊
I changed it.