Thursday 26 November 2015

Why ' $_ ' Represents an Object ?

One of the key factor of PowerShell which made it most popular and successful Scripting language for management id the ability to process and handle everything as Objects and passing them throughout the pipeline .

Yes, The Pipeline. Lets check with an example.

PS C:\>Get-Service | Where-Object -FilterScript {$_.Status -eq 'Running'}

Status   Name               DisplayName
------   ----               -----------
Running  ALG                Application Layer Gateway Service
Running  AppHostSvc         Application Host Helper Service
Running  Appinfo            Application Information
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  BFE                Base Filtering Engine
Running  BITS               Background Intelligent Transfer Ser...
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  Browser            Computer Browser
Running  CertPropSvc        Certificate Propagation
Running  ClipSVC            Client License Service (ClipSVC)
Running  CoreMessagingRe... CoreMessaging
Running  CryptSvc           Cryptographic Services
Running  CscService         Offline Files
Running  CxAudMsg           Conexant Audio Message Service
Running  DcomLaunch         DCOM Server Process Launcher
Running  DeviceAssociati... Device Association Service
Running  Dhcp               DHCP Client
Running  DiagTrack          Diagnostics Tracking Service
Running  Dnscache           DNS Client
Running  DPS                Diagnostic Policy Service
Running  DsmSvc             Device Setup Manager
Running  DsSvc              Data Sharing Service
Running  EFS                Encrypting File System (EFS)
Running  EventLog           Windows Event Log
Running  EventSystem        COM+ Event System

Here,we Have the services in My Computer which are currently running.

We used  Where-Object cmdlet to select only Running Services and -FilteScript Parameter to filter the output of Get-Service cmdlet from the pipeline. The criteria given is {$_.Status -eq 'Running'} .

Lets have a look, why " $_.Status " .

PowerShell cmdlets returns output in the form of table(based on Formatting conditions) . We can See Table headrers , Rows , Colums etc .

Here $ is the output from Get-Service cmdlet , $_ represents each row in that output and $_.Status represent a row at a time but only the value for Status . Here " . " represents a fraction of that row.

Finally we got Only running services, PowerShell Parser takes each Row in that Table and will select status for each service then do an IncaseSensitive comparision using operator -eq to mach the string Running.