Question: I'm trying to set size of PowerShell window using a PowerShell script. The code I'm using is

```
$pshost = Get-Host

$psWindow = $pshost.UI.RawUI

$newSize =$psWindow.BufferSize

$newSize.Height = 4000
$newSize.Width = 200

$psWindow.BufferSize = $newSize

$newSize = $psWindow.WindowSize
$newSize.Height = 95
$newSize.Width = 150

$psWindow.WindowSize= $newSize

```

It works fine in most cases, but sometimes I get the error on certain desktop sizes. For example, I tried with 95 and failed with the error below for my desktop screen size 1440x960.

```
Exception setting "WindowSize": "Window cannot be taller than 82.
Parameter name: value.Height
Actual value was 95."
At line:1 char:5
+     $psWindow.WindowSize= $newSize
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

```

Is there a way I can calculate the maximum window size setting on the machine that it is running the script on and set the size of PowerShell window?

Answer: 
Your were already on the right course.

```
(Get-Host).UI.RawUI.MaxWindowSize

```

Or more specifically:

```
$height = (Get-Host).UI.RawUI.MaxWindowSize.Height
$width = (Get-Host).UI.RawUI.MaxWindowSize.Width

```
You could attempt to set it to the desired value, and then on error, set it to whatever the error states the max value is. For the Width, set it to the same as the buffer width

```
function Set-ConsoleWindow
{
    param(
        [int]$Width,
        [int]$Height
    )

    $WindowSize = $Host.UI.RawUI.WindowSize
    $WindowSize.Width  = [Math]::Min($Width, $Host.UI.RawUI.BufferSize.Width)
    $WindowSize.Height = $Height

    try{
        $Host.UI.RawUI.WindowSize = $WindowSize
    }
    catch [System.Management.Automation.SetValueInvocationException] {
        $Maxvalue = ($_.Exception.Message |Select-String "\d+").Matches[0].Value
        $WindowSize.Height = $Maxvalue
        $Host.UI.RawUI.WindowSize = $WindowSize
    }
}

```