Posts
47
Comments
55
Trackbacks
0
Something fun, totally useless but educational before I go…
Ok, I couldn't help myself. One more post. Here's a script that is totally totally useless, but will teach you about a few features in PowerShell scripting:
  • Script blocks. These are *incredibly* powerful. If you master them, you will be able to do some pretty fantastic things.
  • Host APIs. Ever wanted to control your output (color, location of text etc.)? This will show you how to do that.
  • Passing in parameters into scripts. This is a great way to make your scripts generic, while making them have intelligent defaults.

What does the script do? It makes pretty pictures in the console :). Its basically a demo screensaver. The script takes scripts blocks as input, each script block is basically a functor which is used to define the coordinates of the console cursor. So the default function is basically x = x + 1 and y = y + 1, but because we use the param statement to make the script generic, you can define it to be anything! So try stuff like this:

drawit { $cx + 1 } { $cy + 2 }  -chars "."

Btw: you can also control the milliseconds between the draws and also the characters you want to use. Here is the script.

param( [ScriptBlock]$fx={$cX + 1} ,[ScriptBlock]$fy={$cY + 1}, $chars = @("_", "|", " ") , $m = 1 )

$wH = $host.ui.RawUI.WindowSize.Height - 1 $wW = $host.ui.RawUI.WindowSize.Width - 1
$random = new-object System.Random
$coords = new-object management.automation.host.coordinates [Console]::Clear()

#
$host.UI.RawUI.CursorSize = 0
$global:cX = $random.Next(0,($wW))
$global:cY = $random.Next(0,($wH))  
$fore = $random.Next(0, 15)
$back = "black"

while (1)
{  
    sleep -m $m  $cX = &$fx  $cY = &$fy    
 
    if( $cX -gt $wW -or $cX -eq 0)  
    {   
        $cX = $random.Next(0,($wW))   
        $fore = $random.Next(0, 15)  
    }  

    if( $cY -gt ($wH-1) -or $cY -eq 0)  
    {   
        $cY = $random.Next(0,($wH))   
       
#$back = $random.Next(0, 15)  
    }

    $coords.x = $cX  $coords.y = $cY  

    trap { $coords }  

    [void] $host.UI.RawUI.Set_CursorPosition( $coords )  
    write-host -fore $fore -back $back  $chars[ $random.Next(0, $chars.Length) ]
}

posted on Tuesday, November 30, 1999 12:11 AM Print
Comments
No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  
Please add 4 and 4 and type the answer here:
News
A little slow these days as I'm busy working on exchangelabs.com. I will try and post tidbits when I get some time. Enjoy the older posts till then!