< Back
You are here:
Print

Use the ‘faster’ methods

The following filtering example with a Where-Object is quite common.

Get-VM | Where-Object {$_.PowerState -eq 'PoweredOn’}

Since PowerShell v4 there is now a Where method available. And this method tends to be faster than the equivalent Where-Object cmdlet.

The previous snippet can now be coded as this.

(Get-VM).Where{$_.PowerState -eq 'PoweredOn'}

Note that this option is not limited to the Where method, you can also do

(Get-VM).ForEach('Name’)

Which is basically the same as

(Get-VM).Name

The Where method can also take an addition parameter. This for example a handy way to create two variables, one with powered on and one with powered off VMs.

$vmOn, $vmOff = (Get-VM).Where( {$_.PowerState -eq 'PoweredOn'}, 'Split')

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Table of Contents