I'm trying to automate the creating of remote repos using powershell and gh repo create
and the first thing that happens after running that command is an option to create a new repo on GitHub or push an existing local repo up. I want to select the former, which should just require hitting enter since this is the option that is highlighted by default. I'm trying to use this in my ps1 script:
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}");
When I try that without the gh repo create
command, it works as expected, creating a new line in the powershell console. But when following gh repo create
, it appears to do nothing. The console just sits on the following text which is output from the gh repo create
command:
What would you like to do? [Use arrows to move, type to filter]
> Create a new repository on GitHub from scratch
Push an existing local repository to GitHub
I have tried countless combinations of the following commands
gh repo create
[Microsoft.VisualBasic.Interaction]::AppActivate("Administrator: Microsoft Powershell")
Add-Type -AssemblyName System.Windows.Forms
Start-Sleep 3
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
and
$wshell = New-Object -ComObject wscript.shell;
$wshell.SendKeys("{ENTER}")
I'm new to powershell and can't tell if I'm doing something wrong or if sendkeys just doesn't work with gh commands for some reason, seems to be the latter. Any ideas would be appreciated.
Expanding on @mclayton's comments ...
SendKeys
is designed for scenarios that are similar to a multithreaded execution environment: you've got some bit of UI waiting for input on one thread but also have a script running on a different thread, and you can useSendKeys
in the script to send keystrokes to the UI.The problem is, as @mclayton points out, that console applications tend to behave more like a single-threaded environment: so, in this case, the
gh
command is blocking everything after it.If you want to go this route, try piping the output of
SendKeys
to thegh
command, something like[System.Windows.Forms.SendKeys]::SendWait("{ENTER}") | gh repo create
I'm not exactly sure how that would work (as I understand it, pipes behave somewhat differently in PowerShell than in the regular command line interface).
You might not even need to use
SendKeys
; you might just be able to useWrite-Host
or similar.Note that this was the original use case for pipes: to be able to send the output of one command to another i.e.
command1 [options] | command2 [options] ...
and therefore be able to communicate between programs, even in a "single-threaded" command-line interface.