1

Ive got a very basic powershell script which uses Start-Process to start another .sh script, this is working and the scripts do execute but what I need is to be able to capture the output of the called script.

Content of the scripts is below:

main.ps1

Start-Process 'C:\Program Files\Git\git-bash.exe' -ArgumentList '-- C:\test\sub.sh' -Wait -RedirectStandardOutput output.txt

sub.sh

#!/bin/bash
echo "Hello World"

The sub.sh launches and prints out Hello World in its own console, but I really need the output to either go to the calling powershell scripts console window, or to a file. The file I specify in the -RedirectStandardOutput parameter is created, but is empty.

How can I get the sh script to print to standard out to the calling script?

Thank you

Kelly b
  • 171
  • 2
  • 14

2 Answers2

2

git-bash is in a different world than powershell so you can not directly redirect output or use -RedirectStandardOutput.

As you supposed, you can use an temporary file but the trick is to use internal bash operand ">" to redirect output to the file from bash process :

#!/bin/bash
echo "Hello from bash World" > /c/test/tempFile.txt

Then call it from powershell, you might hide the window also :

Start-Process 'C:\Program Files\Git\git-bash.exe' -ArgumentList C:\test\sub.sh -Wait -WindowStyle Hidden

$s = Get-Content c:\test\tempFile.txt
Write-Host "s=$s"
Remove-Item c:\test\tempFile.txt

Note : You have to specifilly fully qualified path.

Another option might be using Windows 10 own bash interpreter : https://stackoverflow.com/a/44359679/11867971

Bruno
  • 160
  • 6
2

As written in sub.sh, the program to execute sh files is /bin/bash, not git-bash.exe.

$output = & 'C:\Program Files\Git\usr\bin\bash.exe' C:\test\sub.sh
$output
Hello World
7cc
  • 1,149
  • 4
  • 10
  • 1
    `usr\bin\bash.exe` doesn't appear to work, it gives me all kinds of errors (`bash: cut: command not found`, `Permission denied`, etc.). However, `bin\bash.exe` works perfectly - thanks! – CodeManX Apr 08 '22 at 07:58