The unwritten rules of changing the console window's size

When changing the console window size in PowerShell you must also change the underlying buffer size. Doing so might require a bit more than just copy-paste-replace-window-keyword-with-buffer-keyword. There are apparently special rules for doing this without failing.

 

These are the unwritten (but carefully upheld) rules of resizing the console window via a PowerShell script:

   1. The buffer width can't be resized to be narrower  than the window's current width.
   2. The window's width can't be resized to be wider  than the buffer's current width.

So, if you want to make the console window narrower, you set the window size first.
But if you want to make the console window wider, you must set the buffer size first.

Try not to follow these rules - and you get a lovely exception + the console window isn't resized.

Now we have only one problem - The starting width of the console window may vary on different machines/resolutions.

The solution - check the width before setting and act accordingly.

Here's an example:

    1:  $width = 127
    2:  $sizeWindow = new-object System.Management.Automation.Host.Size $width,50
    3:  $sizeBuffer = new-object System.Management.Automation.Host.Size $width,9999
    4:   
    5:  if ($Host.UI.RawUI.WindowSize.width -gt $width) {
    6:      $Host.UI.RawUI.WindowSize = $sizeWindow
    7:      $Host.UI.RawUI.BufferSize = $sizeBuffer
    8:  }
    9:  else {
   10:      $Host.UI.RawUI.BufferSize = $sizeBuffer
   11:      $Host.UI.RawUI.WindowSize = $sizeWindow
   12:  }