7

The maximum number of lines in my environment is 47.

Can I measure this value programmatically?

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
Hyundong Hwang
  • 711
  • 1
  • 8
  • 19

3 Answers3

11

To complement Christian.K's helpful answer:

  • A simpler and slightly more efficient method for obtaining the host object is to use the $Host automatic variable rather than the Get-Host cmdlet.

  • You're only guaranteed to have access to window-size information in the PowerShell console host, i.e., when running in a console (terminal) window

    • It is at a given host's discretion whether to expose this information, and, as Christian states, the PowerShell ISE does not - even though it arguably should, given that it has a console subsystem built in.
  • To test whether your code is running in a console (a.k.a terminal) or not, use
    $Host.UI.SupportsVirtualTerminal - $True indicates that the host is a console.


If running in the PowerShell console host:

You can access the console's properties either:

  • via $Host.UI.RawUI (as in Christian's answer), which is an object of type [System.Management.Automation.Internal.Host.InternalHostRawUserInterface] that - in the PowerShell console host only - wraps the .NET [Console] class (see below).

  • via the .NET [Console] class; e.g., to get the window height (count of rows) this way, use:

    • [Console]::WindowHeight

Sample $Host.UI.RawUI output:

PS> $Host.UI.RawUI

ForegroundColor       : DarkYellow
BackgroundColor       : DarkMagenta
CursorPosition        : 0,58
WindowPosition        : 0,0
CursorSize            : 25
BufferSize            : 160,9999
WindowSize            : 160,75
MaxWindowSize         : 160,94
MaxPhysicalWindowSize : 303,94
KeyAvailable          : True
WindowTitle           : Windows PowerShell

If running in the PowerShell ISE:

Written as of PowerShell version 5.1

Most of the properties in $Host.UI.RawUI are not populated and will return their data type's default value:

PS> $Host.UI.RawUI  # in the ISE

ForegroundColor       : -1
BackgroundColor       : -1
CursorPosition        : 0,0
WindowPosition        : 
CursorSize            : 
BufferSize            : 166,0
WindowSize            : 
MaxWindowSize         : 
MaxPhysicalWindowSize : 
KeyAvailable          : 
WindowTitle           : Windows PowerShell ISE

The only size-related information that is available is the buffer width (166 in the sample output above).

There is no point in trying to use the .NET [Console] class in the ISE, except to query / set the character encoding used for communication with external programs, [Console]::OutputEncoding:[1]

  • Initially in a session, trying to use the window-related members of [Console] causes exceptions, because the ISE does not allocate a console window on startup:

    # In a pristine session.
    PS> [Console]::WindowHeight
    The handle is invalid.     # EXCEPTION
    
  • While the ISE allocates a - hidden - console window on demand, namely the first time you run a console application in your session, that hidden console window's properties, as then reported on via [Console], do not reflect the properties of the simulated console that the ISE presents to the user.

    # chcp is a console application, so when it is run, 
    # the ISE allocates a (hidden) console window, 
    # after which the [Console] API becomes technically usable, 
    # but DOESN'T REPORT MEANINGFUL VALUES.
    PS> chcp >$null; [Console]::WindowHeight
    72  # No exception, but the value is meaningless.
    

[1] Note that the ISE defaults to the system's legacy ANSI code page, whereas regular console windows default to the OEM code page. Thus, these two environments decode output from external programs differently by default.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thank you, "[Console]::WindowHeight" it works well in powershell_ise. – Hyundong Hwang Jul 02 '17 at 16:23
  • 1
    @HyundongHwang: I'm glad to hear it, but it is surprising and contradicts my answer, so let's try to find out why: (a) When you paste `[Console]::WindowHeight` into the console pane in the ISE, you really get an integer value back (for me: the exception described above)? (b) What does `(Get-Command powershell_ise).Version.ToString()` report (for me: `10.0.15063.0`)? (c) What does `$PSVersionTable.PSVersion.ToString()` report (for me: `5.1.15063.413`)? – mklement0 Jul 02 '17 at 17:46
  • Yes, it is different from your expectation. I print a, b, and c values for debugging, and captured the screen. https://s23.postimg.org/y2kgpxpff/screenshot_2017_07_03_at_09_19_22.png – Hyundong Hwang Jul 03 '17 at 00:20
  • @HyundongHwang, mystery solved: Members such as `[Console]::WindowHeight` only start working _after you have run at least one external console application_ in a session, at which point a - hidden - console window is allocated. However, these members then report the properties of the _hidden_ console window, and these values have no meaningful relationship with the _simulated_ console that the ISE presents to the user. In short: Do not use `[Console]` in the ISE, except to query / set the _character encoding_ used for communication with external programs, `[Console]::OutputEncoding` – mklement0 Jun 22 '22 at 13:04
4

You could try something like

$(Get-Host).UI.RawUI.WindowSize.Height

Note a couple of things however:

  • Using the RawUI might not be particular "portable", depending on where your script runs. In "ISE" for example, that property returns nothing, while on the console it will work.

    For more difference here between the console and ISE, run $(Get-Host).UI.RawUI and compare the output.

    In other PowerShell hosts, besides the console or ISE, it might yet be still different.

  • There is also a BufferSize, which can be bigger than the WindowSize. The later being only the part that is currently "viewable" by the user.

Your question sounds a little like a xy problem. Consider explaining (as an edit to your question or a new question), what you're actually trying to achieve, i.e. why you need to know the number of lines?

Christian.K
  • 47,778
  • 10
  • 99
  • 143
  • Thank you for your good response. When I test it, there is no value in powershell_ise. I wanted to create a function corresponding to "more" when I needed page splitting in powershell_ise. Now that I know the maximum number of rows in powershell.exe, I think it will help me if I apply it well. – Hyundong Hwang Jul 02 '17 at 13:58
  • 1
    OK, note that even the built-in `more` does not work in ISE. Probably for the very reason that the necessary information is not available there. – Christian.K Jul 02 '17 at 14:03
0

The functionality I really need is git status, git diff in powershell_ise with highlight and output paging. It seems that the current version of powershell_ise does not solve the problem itself.

Although not completely satisfactory, I have devised a practical solution and created the following function.




source code

function hhd-git-diff
{
    [CmdletBinding()]
    param
    (
    )

    $res = git diff
    hhd-git-colored-output -INPUT_OBJECT $res
}



function hhd-git-status
{
    [CmdletBinding()]
    param
    (
    )

    $res = git status
    hhd-git-colored-output -INPUT_OBJECT $res
}



function hhd-git-colored-output
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelinebyPropertyName=$true)]
        [System.Object]
        $INPUT_OBJECT
    )



    $lineNum = 1



    $INPUT_OBJECT | 
    Out-String | 
    foreach {

        $_ -split "\n" |

        foreach {

            if($lineNum % [Console]::WindowHeight -eq 0)
            {
                Read-Host "continue? press any key..."
            }

            $lineNum++

            if($_ -like "diff --git *")
            {
                Write-Host ""
                Write-Host ""
                Write-Host ""
                Write-Host ("#"*80) -ForegroundColor Cyan
                Write-Host $_ -ForegroundColor Cyan
                Write-Host ("#"*80) -ForegroundColor Cyan
                Read-Host "continue? press any key..."
                $lineNum = 1
            }
            elseif($_ -like "--- *")
            {
            }
            elseif($_ -like "+++ *")
            {
            }
            elseif($_ -like "-*")
            {
                Write-Host $_ -ForegroundColor Red
            }
            elseif($_ -like "+*")
            {
                Write-Host $_ -ForegroundColor Green
            }
            elseif($_ -like "On branch *")
            {
                Write-Host ("#"*80) -ForegroundColor Cyan
                Write-Host $_ -ForegroundColor Cyan
            }
            elseif($_ -like "Your branch is*")
            {
                Write-Host $_ -ForegroundColor Cyan
                Write-Host ("#"*80) -ForegroundColor Cyan
            }
            elseif($_ -like "Changes to be committed:*")
            {
                Write-Host ("-"*80) -ForegroundColor Green
                Write-Host $_ -ForegroundColor Green
            }
            elseif($_ -like "Changes not staged for commit:*")
            {
                Write-Host ("-"*80) -ForegroundColor Red
                Write-Host $_ -ForegroundColor Red
            }
            elseif($_ -like "Untracked files:*")
            {
                Write-Host ("-"*80) -ForegroundColor Black
                Write-Host $_ -ForegroundColor Black
            }
            elseif($_ -like "*modified:*")
            {
                Write-Host $_ -ForegroundColor Yellow
            }
            elseif($_ -like "*deleted:*")
            {
                Write-Host $_ -ForegroundColor Red
            }
            else
            {
                Write-Host $_ -ForegroundColor Gray
            }
        }
    }



}



screen shot

Community
  • 1
  • 1
Hyundong Hwang
  • 711
  • 1
  • 8
  • 19