PowerShell中的窗口大小

时间:2016-08-17 14:11:18

标签: powershell powershell-v3.0

我尝试使用PowerShell脚本设置PowerShell窗口的大小。我使用的代码是

$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

在大多数情况下它工作正常,但有时我会在某些桌面尺寸上出错。例如,我尝试使用95并因以下错误而失败,我的桌面屏幕尺寸为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

有没有办法可以计算运行脚本的机器上的最大窗口大小设置并设置PowerShell窗口的大小?

2 个答案:

答案 0 :(得分:9)

你们已经在正确的路线上了。

(Get-Host).UI.RawUI.MaxWindowSize

或更具体地说:

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

答案 1 :(得分:3)

您可以尝试将其设置为所需的值,然后在出错时将其设置为错误状态最大值。对于宽度,将其设置为与缓冲区宽度相同

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
    }
}