Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to bash "expect" in powershell

I'm using powershell to run another powershell script, at some point the other script asks for some input, I would like to be able to read the output from the other script and based on that supply input to it. Similar to what you can do with expect on bash.

Any ideas?

Thanks

like image 284
lander16 Avatar asked Oct 17 '11 22:10

lander16


1 Answers

You just use Expect program in your powershell. It works. Powershell is a shell too, you can run code wrote by powershell, which call bash code, which call powershell again.

Bellow is a test, it passed.

It "can work with tcl expect" {
    $bs = @'
    echo "Do you wish to install this program?"
    select yn in "Yes" "No"; do
    case $yn in
        Yes ) echo "install"; break;;
        No ) exit;;
    esac
done
'@

$bsf = New-TemporaryFile
$bs | Set-Content -Path $bsf

$tcls = @'
#!/bin/sh
# exp.tcl \
exec tclsh "$0" ${1+"$@"}

package require Expect
set timeout 100000
spawn {spawn-command}
expect {
    "Enter password: $" {
        exp_send "$password\r"
        exp_continue
    }
    "#\? $" {
            exp_send "1"
    }
    eof {}
    timeout {}
}
'@

$tclf = New-TemporaryFile
$tcls -replace "{spawn-command}",("bash",$bsf -join " ") | Set-Content -Path $tclf
"bash", $tclf -join " " | Invoke-Expression

Remove-Item $bsf
Remove-Item $tclf
}

Let me explain the test.

  1. create a bash file which expect an input.
  2. create a tcl file which call bash created in step one.
  3. invoke tcl program from powershell, it works, will not waiting for input.
like image 195
Jiang Libo Avatar answered Sep 22 '22 14:09

Jiang Libo