Git commands via ssh in a Windows Scheduled task

How to set up a scheduled task in windows that can run git commands and clone from a remote server using ssh instead of http. The examples in this article is using bitbucket.org as git repository.

Install Git

First download and install git. A windows version of git can be downloaded from https://git-scm.com/. During installation, choose the following options: Use Windows Prompt, use windows default console.

Git commands via ssh

Run the Git GUI program. Click help->show SSH key. If none is shown, generate a key and do not enter a passphrase. When the key has been generated, copy the public key to the clipboard.
Then go to bitbucket.org, click on your avatar and choose settings. Open the menu item named SSH Keys and click Add Key. Give the key a label and paste in the public key from the previous step – then save.The go to the repo you want to manage and copy the ssh-url. It can be found in the top right corner, you might need to select ssh from the dropdown instead of https. On your windows machine, open a command prompt and run the following command:

c:\> git ls-remote git@bitbucket.org:myaccount/myrepo.git

If it says git is an unknown command, add the git/cmd folder til the path environment variable and run the command again. You need to close the prompt first and open a new one for the updated environment variables to take effect.Answer yes to storing the key, then try to run the command again and verify that this time you are not prompted.

Create batch file

Create a file git.bat with the following content

git clone git@bitbucket.org:myaccount/myrepo.git > git.log 2>&1

This command will clone the repo and write output to git.log. The last section of the command pipes the error log into the standard log which is written to git.log.

Run the batch file and verify that it works as intended.

Setup scheduled task

Create a scheduled task in windows that run the batch file. Remember to specify the “Start In” setting to have control of which folder the batch is executed within and specify to run even when logged out.

Now the most important step:
Copy the folder c:\users\<youraccount>\.ssh to c:\users\default\.ssh

This is important since when NOT logged in when a scheduled task is run, it cannot find the ssh keys unless they are in the default profile folder.