Getting Computer Names into a Cmdlet

Much of what folks do in PowerShell involves multi-computer management, and that means you need a way to tell commands (cmdlets) which computers to manage. Here are several techniques, all of which assume you're using a cmdlet that has a -computername parameter.

If you have a cmdlet whose -computername parameter binds pipeline input ByPropertyName, then you need to pipe in objects that contain a ComputerName property. You might start with AD Computer objects - but those have a name property instead. So you'll need to "rename" the property mid-pipeline:

Get-ADComputer -filter * | Select *,@{n='computername';e={$_.name}} | Do-Whatever

You can use a CSV file, too. If the file contains a ComputerName column:

Import-CSV computers.csv | Do-Something

Again, that'll connect the "ComputerName" column to the -computername parameter of Do-Something (that is, whatever cmdlet you're using). What if your CSV has a "host" column instead? Use the same "renaming" trick as the first example:

Import-CSV data.csv | Select *,@{n='computername';e={$_.host}} | Do-Something

Another trick is to use a parenthetical expression. The results of the expression are fed to the parameter. Here, I'll retrieve names from a text file, which lists one per line:

Do-Something -computername (Get-Content names.txt)

You can use that same parenthetical expression trick with any command that returns computer names. For example, let's go back to pulling them from AD. In this case, I'm getting Computer objects - but I don't want the entire object. I only want the contents of the Name properties. The -expandproperty parameter of Select-Object will take that one property and just returns its values:

Do-Whatever -computername (Get-ADComputer -filter * | Select -expandproperty Name)

With clever use of pipeline binding or parenthetical expressions, you can get computer names from almost any source and feed them to whatever cmdlet you like.

Discuss this Blog Entry 1

on Mar 10, 2011
There is also one more technique that I've learned on VUG (FreeNode #PowerShell IRC channel), that allows you to use scriptblock for parameters that read from pipe and use $_ there and properties of the object:
Get-ADComputer -Filter * | Test-Connection -ComputerName { $_.Name } -Count 1
Really nice for working with AD results. :)

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×