Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell equivalent of LINQ's Select command?

I am trying to run the following Powershell script.

import-module ActiveDirectory  $computers = Get-ADComputer -filter * -SearchBase "OU=myOU,DC=vw,DC=local" | select-object name  Invoke-Command -ComputerName $computers -ScriptBlock {gpupdate /target:Computer} 

The issue is $computers is not a string[] like -ComputerName expects. It really is a Array of ADComputer with one paramter called name.

# Get-ADComputer -filter * -SearchBase "OU=myOU,DC=vw,DC=local" | select-object name | Format-Custom  class ADComputer {   name = PC1 }  class ADComputer {   name = PC2 }  class ADComputer {   name = PC3 } 

What is the correct way to get a array of strings for the names? If I was in C# I know it would be

string[] computerNames = computers.Select(computer => computer.name).ToArray(); 

but I want to learn how to do it in Powershell correctly.

like image 556
Scott Chamberlain Avatar asked Jun 06 '12 20:06

Scott Chamberlain


1 Answers

You can use

Select-Object -ExpandProperty Name 

or (probably the closest equivalent)

ForEach-Object { $_.Name } 

Note that to force the result to be an array (e.g. if you want access to its Count property), you should surround the expression with @(). Otherwise the result might be an array or a single object.

like image 131
Joey Avatar answered Sep 23 '22 15:09

Joey