Write-Host


You've seen this cmdlet used many times in this book. It is used to provide information to you while a script or command block is executing. The information is outside of the command pipeline. In other words, the cmdlet does not affect the objects that are being manipulated. Instead, it provides the feedback you requested:

 PS C:\> foreach ($svc in (get-service)) { >> if ($svc.status -eq "running") { >> write-host "Running: " $svc.DisplayName >> } >> } >> Running:  Windows Audio Running:  AVG7 Alert Manager Server Running:  AVG7 Update Service Running:  AVG E-mail Scanner Running:  Background Intelligent Transfer Running:  Cryptographic Services Running:  DCOM Server Process Launcher Running:  DHCP Client Running:  DNS Client Running:  Event Log Running:  COM+ Event System Running:  IIS Admin … 

In this example, the status of each service is checked. If it is running, then we call Write-Host to help display a message.

One of the slickest features with Write-Host is the ability to colorize the output. Write-Host has two optional parameters: -backgroundcolor SystemColor and -foregroundcolor SystemColor. You can use either or both of these parameters. In addition, you can select any system color from this list:

  • Black

  • DarkBlue

  • DarkGreen

  • DarkCyan

  • DarkRed

  • DarkMagenta

  • DarkYellow

  • Gray

  • DarkGray

  • Blue

  • Green

  • Cyan

  • Red

  • Magenta

  • Yellow

  • White

Here's an example of how you might use this feature:

ServiceDemo.ps1

image from book
 #ServiceDemo.ps1 $services=Get-wmiobject -class "Win32_service" foreach ($svc in $services) {  if (($svc.startmode -eq "Auto") -AND ($svc.state -ne "Running")) {   write-host $svc.displayname $svc.state $svc.startmode `   -backgroundcolor "White" -foregroundcolor "Red"   }  else   {   write-host $svc.displayname $svc.state $svc.startmode   }  }$services=Get-wmiobject -class "Win32_service" foreach ($svc in $services) {  if (($svc.startmode -eq "Auto") -AND ($svc.state -ne "Running")) {   write-host $svc.displayname "["$svc.state"]" "["$svc.startmode"]" `   -backgroundcolor "White" -foregroundcolor "Red"   }  else   {   write-host $svc.displayname "["$svc.state"]" "["$svc.startmode"]"   }  } 
image from book

This script examines each service as queried from WMI, and displays the service's display name, status, and start mode. However, we've added one PowerShell feature. Any service with a start type of "Auto" but is not running will be displayed in a red font with a white background to make it stand out when the script is run.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net