PowerShell with a Purpose Blog

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.
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish