Frederick Reynolds
Frederick Reynolds

Reputation: 666

Find current console size in batch

I am working on a batch file and i need to print hyphens ( - ) across the screen as a separator. Is there a fast (under two seconds) command that can do this?

I have done multiple search queries and could not find the answer on various websites.

(code to find screen size) 
for /l %%a in (1,1,%screen size var%) do (set "line=%line%-")
echo %line%

The output should show a line of hyphens across the console.

Upvotes: 0

Views: 385

Answers (3)

double-beep
double-beep

Reputation: 5519

I would suggest you to use the following code:

@echo off
setlocal EnableDelayedExpansion

for /F "skip=4 tokens=2" %%A IN ('mode CON') do (
    for /L %%B IN (1 1 %%A) do set "hyphen=!hyphen!-"
    echo !hyphen!
    goto :subroutine
)

:subroutine
echo You may continue here
pause

which is a bit complicated, but should do what you want.

The code searches for the columns in mode CON's command output and adds to hyphen variable these accordingly.

Upvotes: -1

Compo
Compo

Reputation: 38719

This is untested, but based upon the output from Mode CON as used in gjpio's answer:

@Echo Off
For /F "Skip=4Tokens=1*Delims=:" %%A In ('Mode CON')Do (For /L %%C In (1,1,%%B)Do @Set/P "=-"<Nul)&Echo( &GoTo :Draw
:Draw
Pause

If you intend to use the separator multiple times within your script you could save it to a variable:

@Echo Off
For /F "Skip=4Tokens=1*Delims=:" %%A In ('Mode CON')Do (For /L %%C In (1,1,%%B)Do (Call Set "separator=%%separator%%-"))&GoTo :Next
:Next
Echo Welcome to %~nx0
Echo %separator%
Pause

As a final afterthought, and just in case you feel that it would perform quicker, I thought I'd better provide a version using delayed expansion too:

@Echo Off&SetLocal EnableDelayedExpansion&Set "separator="
For /F "Skip=4Tokens=1*Delims=:" %%A In ('Mode CON')Do (For /L %%C In (1,1,%%B)Do Set "separator=!separator!-")&GoTo :Next
:Next
Rem Uncomment the next line if you don't want to use delayed expansion in the rest of the script
::EndLocal&Set "separator=%separator%"
Rem Your code goes here
Echo Welcome to %~nx0
Echo %separator%
Pause

As an addition to all of the above, you could also leverage to do this too:

@Echo Off
For /F %%A In ('Powershell -NoP "Write-Host('-' * $(Get-Host).UI.RawUI.WindowSize.Width)"')Do Set "separator=%%A"
Echo Welcome to %~nx0
Echo %separator%
Pause

Upvotes: 1

gjpio
gjpio

Reputation: 46

If you can work out the batch commands retrieve the columns value you could use the output from the MODE command;

    MODE CON  
C:\Users\gjp>mode con

Status for device CON:  
----------------------  
    Lines:          9001  
    Columns:        120  
    Keyboard rate:  31  
    Keyboard delay: 1  
    Code page:      850  

Upvotes: 1

Related Questions