DEV Community

taijidude
taijidude

Posted on • Edited on

Execute a powershell script from inside the git bash

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
Enter fullscreen mode Exit fullscreen mode

When you use an alias it gets even more convinient

$ alias ps1='powershell -File'
$ ps1 scriptToRun.ps1
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode
$ ./helloWorld.ps1
Hello world!
Enter fullscreen mode Exit fullscreen mode

Thank you again @vitalytseshkovsky!

Top comments (5)

Collapse
 
vitalytseshkovsky profile image
Vitaly Tseshkovsky

The solution can be done in UX-script style by using shebang feature:

  1. Make sure that binary powershell or pwsh is in the path.
  2. Add the command #!/usr/bin/env powershell or #!/usr/bin/env pwsh at the beginning of script
  3. Be sure than the script is in UX-style line endings - just apply the command dos2unixon it.
  4. Enable execute permissions for the script.

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:

#!/usr/bin/env powershell

$cur_dir = Split-Path -Path (Get-Location) -Leaf
write-host "AppdData-Local  => $env:LOCALAPPDATA"
write-host "UserProfile     => $env:USERPROFILE"
write-host "CurrentDirName  => $cur_dir"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
taijidude profile image
taijidude

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.

Collapse
 
taijidude profile image
taijidude

Thank you. Will later try it out and add it to the post.

Collapse
 
vitalytseshkovsky profile image
Vitaly Tseshkovsky

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.

Collapse
 
taijidude profile image
taijidude • Edited

Yes, you are absolutely right. Thank you for pointing this out. 😊
I changed it.