Typing enhancements (Intermediate)
In the previous recipes, we have covered the basic changes that took place with the release of Windows PowerShell v3.0. Let's have a look at typing enhancements in the Version 3 console.
We have tab completion for CMDLETs in each version of Windows PowerShell, especially in Version 3.0 where we have tab completion for parameter values as well.
Getting ready
We have some simplified syntax introduced in the latest version of Windows PowerShell with respect to the Where-Object
and ForEach-Object
CMDLETs.
How to do it...
In Version 2.0, the following command retrieves a list of running processes, which have a handles count greater than 1000 from the local machine:
PS C :\> Get-Process | Where-Object {$_.Handles -gt 1000}
In Version 3.0, the following command does the same operation as the previous command statement:
PS C :\> Get-Process | Where-Object Handles -gt 1000
Let's check use of
ForEach-Object
andWhere-Object
by using the following points:The following command statement lists down only files and directory names from the
C:\Scripts
location:PS C :\> Get-ChildItem C:\Scripts | ForEach-Object Name
The following command retrieves the list of running services on the local computer which have the
win
keyword in their names:PS C :\> Get-Service | Where-Object {$PSItem.Status -eq "Running" -and $PSItem.Name -like "*win*"}
How it works...
If we compare the preceding two different version's outputs, it is evident that PowerShell v3.0 has simplified syntax. Moreover, we do not need to use curly braces anymore to run a command statement.
Also, it automatically gets the previous command pipeline output as input for the Where
clause. We don't need to explicitly provide the parameter value with the $_
syntax.
Novice users would find the $_
syntax a bit strange; now, in PowerShell v3.0, we can use $PSItem
instead of $_
.
Tip
It is recommended to use full syntax with curly braces and $PSItem
when we draft a script.
The same is the case with Where-Object
; we don't need to use curly braces and the $_
syntax if we are dealing with ForEach-Object
in PowerShell v3.0.