Warning: sem_get() [function.sem-get]: failed for key 0x152b: Permission denied in /home3/adminsky/public_html/wp-content/plugins/wp-cache/wp-cache-phase2.php on line 98
AdminSky.org » CMD – PowerShell

Our Sponsors

PowerShell – Writing Messages to the Console Window

The Write-Host cmdlet enables you to write messages to the Windows PowerShell console. For example, do you have a pressing need to write the phrase This is a message to the console window? Then just call Write-Host followed by the message you’d like to write:

Write-Host "This is a message"

There’s nothing wrong with that; it writes the phrase This is a message to the console window. However, let’s see if we can get Write-Host to do something even more exciting. As it turns out, Write-Host includes two optional parameters – -foregroundcolor and –backgroundcolor – that enable you to specify a different text color and a different text background color. For example, here’s a command that sets the foreground (text) color to red and the background color to yellow:

Write-Host "This is red text on a yellow background"
-foregroundcolor red -backgroundcolor yellow

And here’s what the resulting console window looks like:

Windows PowerShell
We thought you’d like that. Here are the colors you can use with the –foregroundcolor and –backgroundcolor parameters:

Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White

Here’s an interesting variation that displays differently-colored text on the same line as regular text. The command first calls Write-Host and writes the phrase Data for. Notice, however, that it then appends the parameter –nonewline. As the name implies, -nonewline causes the cursor to stay on the current line.

Is that important? You bet it is: by default, any time you call write-Host it tacks a carriage-return linefeed on the end, causing the cursor to drop to the next line in the console window. However, by using –nonewline we leave the cursor in place; that enables us to call Write-Host a second time (separating the individual calls using a semi-colon). This time around we write the name of the computer, but we also do the red-text-on-a-yellow-background thing. We add a semi-colon and then call Write-Host a third time, this time writing the phrase retrieved May 12, 2006 in regular text.

Got all that? Here’s what the command looks like:

Write-Host "Data for " -nonewline; Write-Host "atl-ws-01"
 -foregroundcolor red -backgroundcolor yellow -nonewline;
Write-Host " retrieved May 12, 2006"

And here’s what the resulting console window looks like:

Windows PowerShell

PowerShell – Writing a Warning Message to the Console Window

The Write-Warning cmdlet is designed to write a warning message to the screen. What’s cool about Write-Warning is that this message appears, by default, in bright yellow, making it clearly stand out in the console window:

Windows PowerShell
Write-Warning is also one of the simplest of all cmdlets; all you do is call Write-Warning followed by the warning message you want to display:

Write-Warning "The folder C:\Scripts2 does not exist."

That’s all there is to it.

PowerShell – Viewing Data One Screen at a Time

The Out-Host cmdlet provides a way to write pipelined data to the console window. Big deal, you say: isn’t pipelined data typically written to the console window by default anyway? Yes. But Out-Host does have at least one intriguing capability missing from the standard output: by adding the –paging parameter you can view data one page (screen) at a time, rather than have it all scroll past in one big blur (and possibly overflow the console window buffer along the way). For example, perhaps you’d like to view the Windows PowerShell event log entries, but you’d like to view those entries one screen at a time. No problem: just call Get-EventLog, pipe the data to Out-Host, and add the –paging parameter. Your command should look like this:

Get-Eventlog PowerShell | Out-Host -paging

Or, if you don’t like typing, shorten –paging to –p:

Get-Eventlog PowerShell | Out-Host -p

Either way, your data will be displayed like this:

Windows PowerShell
Notice that only one screen of data is displayed. That screen will remain in place until you press the spacebar (to move to the next screen), press ENTER (to move to the next line), or press Q to quit.

Tip. Windows PowerShell includes a special function – more – that can also be used to display data one screen at a time:

Get-Eventlog PowerShell | more
Out-Host Aliases
oh

PowerShell – Sorting Returned Data

If you’re a script writer you’ve no doubt fantasized about being able to easily sort data any way you want to. Who said dreams never come true? In Windows PowerShell it’s amazingly easy to sort data, and to sort it any way you want.

For example, by default the Get-EventLog cmdlet returns data sorted by the time the event was written to the event log. But what if you’d prefer to sort data by the EventID. What then?

What then, indeed. To sort by EventID just retrieve your data and then pipe it to the Sort-Object cmdlet, telling Sort-Object which property to sort on:

Get-EventLog system -newest 5 | Sort-Object eventid

Run that command, and you’ll get back data similar to this:

Index Time          Type Source   EventID Message
----- ----          ---- ------   ------- -------
 6194 May 16 12:41  Info W32Time  35 The time service is n...
 6193 May 16 12:41  Erro Dhcp     1000 Your computer has los...
 6197 May 16 14:47  Warn Dhcp     1003 Your computer was not...
 6196 May 16 14:13  Warn Dhcp     1003 Your computer was not...
 6195 May 16 12:42  Warn Dhcp     1007 Your computer has aut...

Nice, huh? Would you rather have the events sorted in descending order; that is, with the largest EventID listed first? No problem; just tack on the –descending parameter:

Get-EventLog system -newest 5 | Sort-Object eventid -descending

Notice the change:

Index Time          Type Source     EventID Message
----- ----          ---- ------     ------- -------
 6195 May 16 12:42  Warn Dhcp     1007 Your computer has aut...
 6197 May 16 14:47  Warn Dhcp     1003 Your computer was not...
 6196 May 16 14:13  Warn Dhcp     1003 Your computer was not...
 6193 May 16 12:41  Erro Dhcp     1000 Your computer has los...
 6194 May 16 12:41  Info W32Time  35 The time service is n...

Windows PowerShell also allows you to sort by multiple properties: just separate the properties using commas. For example, suppose you retrieve a list of all the files in the folder C:\Scripts. You’d like to first sort the data by file extension and then by file size; in other words, you want to group all the .txt files together, then sort that little grouping by file size. Here’s the command (using the Get-ChildItem cmdlet) that can pull that off:

Get-ChildItem c:\scripts | Sort-Object extension,length

And here’s the kind of output you’ll get. Notice that not only are all the .vbs files listed together, but they are also arranged by file size, with the smallest .vbs file listed first and the largest .vbs file listed last:

-a---          5/5/2006   9:09 PM      53358 tee.txt
-a---         5/15/2006   8:57 AM        377 new_excel.vbs
-a---         3/15/2006  10:23 AM        399 imapi.vbs
-a---          3/3/2006   2:46 PM        537 methods.vbs
-a---          3/3/2006   2:55 PM        698 read-write.vbs
-a---         3/11/2006  10:10 PM        978 imapi2.vbs
-a---         3/17/2006   8:21 AM       1105 winsat.vbs
-a---          5/5/2006   2:55 PM      19225 test.vbs
-a---          4/4/2006   8:30 AM    2616487 HoneyPie.wma
Sort-Object Aliases
sort

PowerShell – Selecting Specific Properties of an Object

One of the more useful capabilities of the Select-Object cmdlet is the ability to grab a selected number of objects from the beginning (or the end) of a sorted collection. For example, suppose you use the Get-ChildItem cmdlet to get a list of all the files in the C:\Windows folder; you then pipe that information to the Sort-Object cmdlet and sort the files by size (length). Now suppose all you really care about are the three largest files in the folder; how do you go about determining that?

Here’s how:

Get-ChildItem c:\windows\*.* | Sort-Object length
-descending | Select-Object -first 3

After you’ve sorted the collection in descending order, the largest file will be at the top and the smallest file will be at the bottom. To determine the three largest files in the collection simply call Select-Object and include the –first parameter, specifying the number of items to return. In other words:

Select-Object -first 3

What if you wanted the three smallest files? Well, seeing as how those three files will be at the bottom of the list, you simply use the –last parameter, like so:

Get-ChildItem c:\windows\*.* | Sort-Object length
 -descending | Select-Object -last 3

You can also use Select-Object to specify that only selected properties from an object should be used in your command (e.g., only certain properties should be shown on-screen). For example, by default any time you run the Get-Process cmdlet and pipe it through Format-List, you get back something that looks like this:

Id      : 1924
Handles : 273
CPU     : 2.046875
Name    : svchost

But suppose all you really wanted was to see the process Name and ID? That’s fine: just pass the process information through Select-Object, and ask it to pick out only the Name and ID properties:

Get-Process | Select-Object name,id | Format-List

What will that give you? That will give you output that looks like this:

Name : atiptaxx
Id   : 2440

Name : BTStackServer
Id   : 524

To ensure that you retrieve all the properties and property values, use the wildcard character. This command retrieves process information and then displays all the properties as a list:

Get-Process | Select-Object *

Good question: suppose you did want all the properties except for Site and Container. No problem; just tack on the –exclude parameter and indicate the properties that should be excluded from the returned dataset:

Get-Process | Select-Object * -exclude site,container
Select-Object Aliases
select

Warning: sem_acquire(): supplied argument is not a valid SysV semaphore resource in /home3/adminsky/public_html/wp-content/plugins/wp-cache/wp-cache-phase2.php on line 107

Warning: sem_release(): supplied argument is not a valid SysV semaphore resource in /home3/adminsky/public_html/wp-content/plugins/wp-cache/wp-cache-phase2.php on line 116