FSI, PsExec and Console.Clear

I recently struggled with an error that I encountered during the process of setting up a continuous deployment TFS build and I thought that I would write briefly about it in the hope of helping anyone else running into the same issue. The issue arises running FSI remotely using PsExec.

As a part of our continuous deployment build process I had created an F# script responsible for running the installer and performing environment specific configuration. My plan was to have the TFS build process remotely run this script on the deployment machine using PsExec. The script had been tested manually and worked as expected, so running it via PsExec should have been fairly straight forward.

PsExec.exe \\machine -h -accepteula "C:\Program Files (x86)\Microsoft SDKs\F#\3.0\Framework\v4.0\fsi.exe" "C:\Path\To\My\Script.fsx"

However, I immediately ran into problems. Whenever I tried to run the script using PsExec I was greeted with the error System.IO.IOException: The handle is invalid. Google suggested a number of possible issues from administrative access to writing to the console. After what felt like an eternity of tweaking command line options, changes to the deployment script and installer I stumbled upon the cause by reducing the script to "Hello, World" and re-introducing functionality piece by piece.

So what was the cause of this error? Running an MSI? Tweaking the registry? Starting and stopping websites in IIS? No, the culprit was this line.

Console.Clear ()

At the beginning of the script I clear the console to make the output more readable. It turns out that clearing the console in a PsExec context is not allowed (although Console.WriteLine etc. all still work as expected), presumably because it is a remote console "nested" inside PsExec on a local console.

You can see this effect for yourself by attempting to run this fairly inoffensive script using PsExec.

open System

Console.Clear ()
Console.WriteLine ("Hello, World")

If you found your way here after running into the same issue I hope this helped!