Langsung ke konten utama

How to Draw a Vertical Rectangular Box

Draw Boxes and Lines in the Windows PowerShell Console Host

Summary: Microsoft MVP Sean Kearney shows how to draw boxes and lines in the Windows PowerShell panel while scripting three reusable functions.

Microsoft Scripting Guy Ed Wilson here. Just when I thought it was safe to open my e-mail, I get a tweet from Sean Kearney saying he has a present for me. Low and behold, Sean has sent me a really cool article.

Sean Kearney is a network administrator, a Microsoft Certified Technology Specialist in Windows Server Virtualization and Configuration, a Windows PowerShell MVP, and a Microsoft Certified Systems Engineer. Sean is a devoted and passionate computer enthusiast from the early 80s to the nowadays day, having used merely about every microcomputer ever. Sean taught himself estimator programming with 65xxmachine code, working with many technologies―but primarily Microsoft. Sean deals with "anything thrown at him," from gnawed keyboards to recovery of Exchange servers to networking setups and isolating the realm of the unknown. Currently, he tests and deploys merely almost any new Microsoft Engineering science; he also deals with users in an enterprise class surroundings. Sean loves Windows PowerShell, Windows 7, and Hyper-V, in that lodge. You will oftentimes find him hanging out online at http://www.powershell.ca.

Hither is Sean's article.

I decided to have some fun. Because isn't that why we got into computers in the commencement place? It was fun on some level? We enjoyed information technology? Right? So I was thinking back to my BBS days and ASCII fine art and plotting information on the console screen.

You run into, using the $HOST variable in Windows PowerShell allows you to move the cursor to any spot (within reason) on the console. After you take moved it, you can put something there. And then I'thousand thinking to myself, "Boy, I'd love to build a nice box on the screen!" And so I sabbatum downwardly and wrote a actually bad script.  It was bad because information technology worked, but the coding was merely horrible and repetitive. What I ended up with (for a single box) was about four foreach loops, a whole pile of $host.ui.raw.cursorposition settings, and about 90 lines of lawmaking.

And then I started reexamine information technology. Because a lot of the code did really repeat in almost respects, I idea at that place had to be a better style. The outset part was easy. Make a function to position the cursor, mostly to brand the code more than readable, simply also because I happen to similar readable functions.

————— Set Panel Position —————-
function global:fix-ConsolePosition ([int] $ten ,[int] $y ) {
# Go current cursor position and store away
$position = $host .ui.rawui.cursorposition
# Shop new X and Y Co-ordinates away
$position .x = $x
$position .y = $y
# Place modified location back to $HOST
$host .ui.rawui.cursorposition = $position
}
————— Ready Console Position —————-

Next, I realized the code kept cartoon lines. So I idea, "Wouldn't information technology make more sense to take a smart function that could draw those lines"?"

So onto task number two. Make a function that doesn't just draw a line on the screen just would be smart enough to know whether I was doing it vertically or horizontally. Information technology would have to know how long the line was and ideally what coordinates to draw it on.

The function has to receive the X and Y position of where the line has to get, receive length, and know if it is a vertical line:

office global:describe-line([int] $x , [int] $y , [int] $length ,[int] $vertical ){

Then ready the line to start at the defined coordinates. My last part, fix-ConsolePosition, makes this very piece of cake:

set-ConsolePosition $10 $y

Now hither'due south where the fun starts. I could but draw a box with asterisks and be done, simply I'd similar it to look nicer. And so each line will start with an asterisk merely have a "-" or a "!", depending on whether it'due south drawn vertically or horizontally:

If ([boolean] $vertical )
{ $linechar = "!" ; $vert = 1 ; $horz = 0 }
else
{ $linechar = "-" ; $vert = 0 ; $horz = 1 }

Instead of a big funky { if so else }, I decided to necktie it into the math. So I sat down and thought out the flow of the lawmaking. Okay, all I did really was call up "If I'grand cartoon vertically, the Y coordinate will e'er alter; otherwise, 10 is always going to alter":

set-ConsolePosition (( $horz * $count )+$10) (( $vert * $count )+$y)

Then with this little line above here I make certain to keep the counter changing the value of the 10 position or the Y position (but not both) depending on how it receives the $Vertical from the function. This line

write-host $linechar -nonewline

will always be the same for cartoon because we have predefined the character we are drawing with. Overall, y'all get this to draw a line at present:

————— Describe line Function —————-
function global:depict-line([int] $x , [int] $y , [int] $length ,[int] $vertical ){
# Move to assigned X/Y position in Console
fix-ConsolePosition $x $y
# Draw the Get-go of the line
write-host "*" -nonewline
# Is this vertically fatigued ? Gear up management variables and advisable character to draw
If ([boolean] $vertical )
{ $linechar = "!" ; $vert = one ; $horz = 0 }
else
{ $linechar = "-" ; $vert = 0 ; $horz = one }
# Depict the length of the line, moving in the appropriate management
foreach ( $count in 1 ..( $length-1 )) {
set-ConsolePosition (( $horz * $count )+$x) (( $vert * $count )+$y)
write-host $linechar -nonewline
}
# Bump up the counter and draw the terminate
$count++
set-ConsolePosition (( $horz * $count )+$ten) (( $vert * $count )+$y)
write-host "*" -nonewline
}
————— Draw line Function —————-

Now here is where I went overboard. My brain went, "Hey, I can draw a line, I can option a management, I could make a box!" You tin can tell my brain didn't become a lot of holiday fourth dimension during the summer. But I gave in and idea it out. Really, a box wasn't so difficult. Two horizontal lines, two vertical lines. I already have a office to describe lines.

And then I could just telephone call upwards the line draw part with the advisable data and just run information technology right? Nope. I could but there was this geeky piffling voice proverb "Reuse the lawmaking!" So with a Foreach loop and some fancy math, I figured out a way to reuse almost every slice of sanity.

So I thought, what is unique about each line in a box? The position, the X/Y beginning position, and the length. So:

  • The square would draw ii horizontal lines and and so two vertical lines.
  • Each horizontal line the "X" position does not change for starting point.
  • Each vertical line the "Y" position does not change for starting point.

Then you end up with a pattern like this:

  • 0 Horizontal
  • 0 Horizontal
  • i Vertical
  • ane Vertical

Each Row was either Top Left or Lesser Right:

  • 0 Top
  • i Bottom
  • 0 Left
  • 1 Right

Which gave me this pattern:

  • 0 0 Top Horizontal
  • 0 i Bottom Horizontal
  • 1 0 Left Vertical
  • 1 one Correct Vertical

We have a loop that goes through four times and can flip variables and do all sorts of funky stuff to make a box.

—————- Draw the Box ———————————-
function global:draw-box ([int] $width , [int] $length , [int] $x , [int] $y ) {
# Do the iv sides
foreach ( $box in 0 .. three ) {
# Variable to flip whether we're on the left / summit of the box or not
$side = $box%two
# Variable to switch whether information technology's a vertical or horizontal line
$vert = [int](( $box- . 5 )/ ii )
# compute the Width and Length so nosotros tin can "switch them"
$totalside = $width+$length
# Length of line volition exist dependant on the Direction
# (vertical or Horizontal)
$linelength = ( $vert * $length )+([int](! $vert )* $width )
$result = $totalside-$linelength
# flip in the correct Ten Y coordinates for the maximum
$ypass = ([int](! $vert )* $side * $event )+$y
$xpass = ( $vert * $side * $result )+$x
# Draw the line
draw-line $xpass $ypass $linelength $vert
}
}
—————- Draw the Box ———————————-

Then what exercise we have ? A series of iii functions, and a pretty box on the screen.

What have we learned?

  1. You tin use some incredibly powerful functions in Windows PowerShell.
  2. With proper math and functions, yous tin can make a lot of code reusable.
  3. Sean has way too much time on his hands.

Sean, thank you for sending me your post. I put all three functions into a single script, loaded it into my Windows PowerShell console, moved my console point, and drew a box and a line. The results are shown in the following image.

Image of script results

Nosotros would honey for you to follow us on Twitter and Facebook. If you have whatsoever questions, transport email to the states at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow when nosotros begin a new week on the Script Center. We volition have an awesome series of articles most Windows PowerShell cmdlets and SharePoint 2010, written by celebrated SharePoint author Niklas Goude. Until then, peace.

Ed Wilson and Craig Liebendorfer, Scripting Guys

thententonarmstead.blogspot.com

Source: https://devblogs.microsoft.com/scripting/draw-boxes-and-lines-in-the-windows-powershell-console-host/

Komentar




banner



Popular Posts

Ls Model : LS MODEL&沢村りさimouto.tv

Ls Model : LS MODEL&沢村りさimouto.tv . In some cases, the "value" of a. From the old vintage models to perennial classics, here are 13 of the most popular and iconic models from the automaker. Check out 15 of the best toyota models. In the market for a new (to you) used car? Advertisement ford models come in all shapes and price ranges. Would you like to take its web strategy for a test drive? See pictures and learn about the specs, features and history of dodge car models. Dodge cars come in all shapes and price ranges. In the market for a new (to you) used car? In some cases, the "value" of a. ls-models teenmasha and veronika babko from lifestylephotographers.s3.us-east-2.amazonaws.com Advertisement ford models come in all shapes and price ranges. In the market for a new (to you) used car? Check out 15 of the best toyota models....

Julia Maisie Ss Multi : S S M A I S I E S E C R E T Zonealarm Results : Mica andreas on kristina soboleva.

Julia Maisie Ss Multi : S S M A I S I E S E C R E T Zonealarm Results : Mica andreas on kristina soboleva. . Secret sessions star nita ss 8. , secret stars lisa скачать с star sessions. This page is about julia maisie ss multi,contains maisie (@maisie1dforever),sag awards 2017: Are trampolines too dangerous for. Julia maisie ss set star sessions maisie amp aleks multi models set 026. Enjoy with julia maisie ss multi video and pictures and have fun with our site. You need to select one and go! Star starsessions / gov t mule the tel star sessions cd. People interested in julia maisie ss multi also searched for. Enjoy julia maisie ss multi videos and pictures. Julia Maisie Ss Multi I6sppbcbzgp2cm 4k Aleksandra Angelina Bethany Download Elena Isabella Julia Kathy Leyla Lilu Lisa Maisie Michelle Mila Natalie Natasha Nina Nita Olivia Secret Stars Set Taso Video from i.pinimg.com ...

Холостяк. Жизнь После Проекта - Герои шоу "Холостяк": жизнь после проекта - Новости шоу ... - Проект «холостяк» — это невероятный жизненный этап, который меняет жизнь всегда в лучшую сторону.

Холостяк. Жизнь После Проекта - Герои шоу "Холостяк": жизнь после проекта - Новости шоу ... - Проект «холостяк» — это невероятный жизненный этап, который меняет жизнь всегда в лучшую сторону. . Соперница марии, алена, после «холостяка» отправилась покорять другие телешоу. Холостяком первого сезона проекта, вышедшего на экраны в 2013 году, стал футболист евгений левченко. Отношения не выдержали проверку расстоянием: Для многих это стало в студию к ведущему проекта григорию решетнику пришли не только многие участницы из 11 сезона шоу, но и герои прошлых сезонов. Он транслируется во многих странах и везде очень популярен. Как сложилась жизнь героев популярного шоу «холостяк». Как сложились отношения михаила заливако и анны богдан и вместе ли пара. И надо сказать, что пока ни один из главных героев в нашей стране не женился на победительнице проекта. За романтическим шоу канала тнт каждый год следят сотни тысяч зрителей. В финале он выбрал барбару пино, но долг...

Maitreyi Ramakrishnan - Stream Maitreyi Ramakrishnan Never Have I Ever By Four Quadrant Listen Online For Free On Soundcloud / She is an actress, known for never have i ever (2020), acting for a cause (2020) and 2020 canadian screen awards for children's & youth programming (2020).

Maitreyi Ramakrishnan - Stream Maitreyi Ramakrishnan Never Have I Ever By Four Quadrant Listen Online For Free On Soundcloud / She is an actress, known for never have i ever (2020), acting for a cause (2020) and 2020 canadian screen awards for children's & youth programming (2020). . Maitreyi ramakrishnan was born on december 29, 2001 in mississauga, ontario, canada. Maitreyi ramakrishnan is a canadian actress known for her leading role in the netflix teen comedy series never have i ever. After all, she was named one of time100's next most influential people of 2021. 1 day ago · maitreyi ramakrishnan, 19, star of mindy kaling's netflix show "never have i ever," is intimately familiar with this situation, and now she gets to portray it on screen. Born 28 december 2001) is a canadian actress known for her leading role in the netflix teen comedy series never have i ever (2020). She is an actress, known for never have i ever (2020), acting for a...

Something Went Really Wrong, and We Canã¢â‚¬â„¢t Process That File. Github

When making commits to any Git repository, you'll choose the files you want to stage and then you'll commit them. But you might not want to commit every single one of your files—there are files that never need to get committed. This is where the .gitignore file is useful: it tells Git exactly which files to ignore and never track. Let's take a look. What is gitignore? When you're working in your copy, Git watches every file in and considers it in three ways: Tracked: You've already staged or committed the file. Untracked: You've not staged or committed. Ignored: You've explicitly told Git to ignore the file(s). The .gitignore file tells Git which files to ig...

New Sofa Design 2021 - Pin On Manuals - Tips for buying a new sofa.

New Sofa Design 2021 - Pin On Manuals - Tips for buying a new sofa. . Think a living room that combines jute, oak, and linen with materials that are. Discover this season's latest collection of new sofa designs, and fresh new colorways for old favorites. With various sizes and a range of prices you'll be sure to find the sofa for you. Take a maximalist approach to decorating So go through the trendy list and pick one that suits your living space. Certain rustic features, like shiplap and barn doors, are starting to date themselves. Lounge your way with the ikea seating brochure 2021. Features of living room furniture trends 2021. 15+ interior design trends for 2021 you need to know about. Generally speaking, most of the popular trends among living room furniture 2021 primarily revolve around bold design choices and concepts that help to enhance the entire interior. Sofa Cover 7 S...

Baixar A Musica Do Vedo. You Got It / Baixar Programa De Gravar Musica : Você pode filtrar os ... : The new song is currently available for download on fakazahouse below.

Baixar A Musica Do Vedo. You Got It / Baixar Programa De Gravar Musica : Você pode filtrar os ... : The new song is currently available for download on fakazahouse below. . Seleccione el formato que desea descargar. You got it official music video for you got… baca selengkapnya baixar a musica do vedo. Você pode baixar músicas mp3 de graça. I live my life to be with you. Agora, os downloads aparecerão na fila. I live my life to be with you. If you feel you have liked it como baixar musica corretamente pelo tubidy mp3 song then are you know download mp3, or mp4 file 100% free! Você pode facilmente converter milhares de vídeos do youtube. Aprenda a baixar músicas do youtube facilmente usando ferramentas online, programas ou plugins. Nuestra página no posee ningún tipo de inconveniente a la. Como Baixar Músicas Direto do Celular - Android (2018 ... from i.ytimg.com ...

Animals Found In Tropical Rainforest : Rainforests Animals For Primary Children / Having these strong and long limbs help this animal to be one of the best equipped arboreal (living in the trees) animals found the rainforest.

Animals Found In Tropical Rainforest : Rainforests Animals For Primary Children / Having these strong and long limbs help this animal to be one of the best equipped arboreal (living in the trees) animals found the rainforest. . Iguanas are lizards found throughout most of the western half of the southern hemisphere. They are known to almost anything they can catch, including deer, crocodiles, snakes, monkeys, deer, sloths, tapirs, turtles, eggs, frogs and toads, and fish. Additionally, no greater plant diversity exists on earth than in the tropics. The species is found in the amazon basin (the region surrounding the amazon river) and other tropical parts of northern south america. The tropical regions of the planet house an enormously diverse group of plants and animals. We have identified approximately 15 million different species of animals, and yet there. A large number of reptiles, insects, and amphibians also occur in this layer. They have a poisonous skin and t...

Nn Tease : Nn Tease Tube Search 111 Videos / The burning of black wall street'.

Nn Tease : Nn Tease Tube Search 111 Videos / The burning of black wall street'. . Photos and video taken of the teacher's strip tease were posted to facebook and were quickly shared all over. Frankies bikinis tasha bottom in brownie tie dye ($85) pinterest. The video has been viewed more than. Browse 1,424 teenage girls feet stock photos and images available, or start a new search to explore more stock photos and images. As in, they're no longer only popular with a select group of fashion girls—they're everywhere. A documentary slated to hit new york city this month boasts a hefty tease. Soya keaveney, from cleveland, insists she is going to be a brilliant mother. How to use tease in a sentence. Checking myself out in hotel room mirror in black lingerie, seamed stockings and high heels. Browse 4,996 teenage girls barefoot stock photos and images available, or start a new search to explore more stock photos and images. ...

Cara Cheat Ppsspp 60 Fps Naruto : Cheat Naruto Shippudden Ultimate Ninja Impact Ppsspp Unlock Semua Karakter - Link setting ppsspp 60 fps :

Cara Cheat Ppsspp 60 Fps Naruto : Cheat Naruto Shippudden Ultimate Ninja Impact Ppsspp Unlock Semua Karakter - Link setting ppsspp 60 fps : . Ultimate ninja impact for psp. How to get 60 fps in naruto storm 4 dlc needed : Check the prevent fps from exceeding 60 and put 0 values in alternative sped (in %, 0. Install ppsspp emulator, then open it briefly and remove it again. (if file contains any cheats already > press enter then press up), now either press ctrl+v or right click and paste. You can play using emulator ppsspp on android and pc naruto mod storm 4 size 535mb link download iso/cso: Oct 15, 2018 how to play gta liberty city stories 60 fps ppsspp android? It's the sixth naruto title for playstation portable. I have np 60 fps runs in full speed but when i turned msaa on to 8 it def put my game in slow motion, make sure you got msaa off and see if that helps. Cheats can be activated separately and should be named for their function. ...
close