Saturday 13 January 2018

If Prompt() function throws exception

I have been into a problem many times during 3/4 months. Something crazy was happening to my PowerShell console(not always) . Being busy with work, I always close and re-open the console to get rid of it. Finally, one fine day I found the problem and just thought of sharing it here as any one can get into the same trouble.

Problem I faced

While using the PowerShell console, suddenly from one point, console stopped showing output. Any cmdlet/script execution after this point will not be showing its output even though the cmdlet/script I execute is doing what it has to do.

Why I'm sure about the execution completion is, If I pipe it Grid view or redirect to a file, I can see the output.

I thought of digging into this crazy behaviour and started by comparing output of Get-Variable cmdlet of current session to a working session.

From this comparison, I got the hint for finding the root cause of this problem. from the output, we can assure that the delta is of $Error variable and it is of the console where the problem is occurring. I then realised that , the problem is because of a code which sets the Window title, and the error is because of an attempt to set the Window title with more characters than it supports(max is 1023).

Finally I found the culprit in my $Profile script. I have my prompt function overwritten via my $Profile script. Below is my prompt function.

In this function, I'm setting the window title with
  1. User in context
  2. Last expression
  3. Total error count
  4. Present working directory
  5. Number modules loaded
  6. PID. 

Here the $^ last expression is causing the issue for me. While using the console, I use to paste function definitions directly into the console, If I do that, the last expression becomes the whole function definition, which will be pretty big(more than 1000 chars), If done so, the window title will become pretty huge including the last expression which is the function definition I pasted. Hence, the prompt function throws exception while setting the $Host.ui.RawUI.WindowTitle . So nothing is thrown to the output stream.

Have  fun exploring the shell !!!