All
you need is this one-liner:
Get-Service | ForEach {if ($_.Status -eq "Running") {write-host $_
.DisplayName}}
A few new constructs here need some explanation. Get-Service is straightforward:
It runs and its output is piped as the input to the next section, which is the ForEach loop.
Since Get-Service returns a collection of service objects, the ForEach statement is perfect
for looping through each item Get-Service returns. Inside the outer set of curly
braces is our block of code. In this case, we are using an If statement to check whether
the status of the service is equal to "Running", and if it is, it outputs the display name.
Two things must pop out to you. First is the $_ notation and second is the dot (.)
notation. The $_ variable is one of the system-defined automatic variables. In a pipe, it
holds the current pipeline object. In this example, for each iteration of the loop, $_ would
reference each service item in the collection returned by Get-Service. The dot (.) notation
is a member operator for object. Every object has a set of properties. For example,
452 Microsoft Windows Server 2008 Administration
a service has a status, name, and displayname among other things. To access each of
these individual properties of an object, you use the dot notation to get to that property
using the syntax objectname.propertyname.
Here??™s a practical solution to a common problem.
Pages:
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483