Monthly Archive

Categories

Using the Where method

You don’t usually see people using the where method. A recent question on the forums highlighted using the where method.

 

PowerShell deals in collections and will automatically create a collection of objects if the are multiple objects returned for instance

$procs = Get-Process

 

Iterating over a process can take time. PowerShell introduced 2 methods on collection to make this easier and much  faster to execute – where and foreach.

As an example

$Paths = @(
@{NodeName = 'VMNAme1'; Instance = 'Internal' ; Path = 'C:\Temp\'},
@{NodeName = 'AnotherName' ; Instance = 'External' ; Path = 'C:\Temp2'},
@{NodeName = 'VMNAME2'; Instance = 'Internal' ; Path = 'C:\Temp1\'}
)

Get-ChildItem -Path $paths.where({$_.Nodename -eq $env:COMPUTERNAME}).Path

 

Depending on the machine on which you’re running you’ll get the appropriate folder.

 

The important bit is the $_.Nodename . You need to use the old style Where syntax when using the where method.

Comments are closed.