Skip to main content
PowerShell

Powershell A little color in our ouput with If and ForEach thrown in

By February 18, 2014September 12th, 2022No Comments

We now have to get the the nitty gritty of scripting with PowerShell. We have seen how we can create a simple module with a single function; let’s now expand upon this to start to create some usable code. In this tutorial we are are going to learn how to use color in our output and start using conditional statements with IF and ForEach.

Everything is an Object

In PowerShell all that we deal with our objects and objects have properties that we can read and perhaps manipulate. If I use the cmdlet Get-Service we are returned a list of services defines on the current host. The status property of each Service object will show if the service is running or not. If we read that the status then we can print the service differently if it is running or stopped. If we add the code to a function in a module we can then use it easily as required.

Function Get-AllServices {
$AllServices=Get-Service
ForEach ($SVC in $AllServices) { If ($SVC.Status -eq "Stopped") {
      WriteHost $SVC.name -ForeGroundColor Magenta
   } else { WriteHost $SVC.name -ForeGroundColor Cyan}
  }
}

get-service