Wednesday, May 30, 2012

PowerShell: Easy ways to get computer names into string arrays

Description:  In Powershell, there are a number of reasons that administrators require the ability to run a script against multiple machines.  In many of the cmdlets, there is a -ComputerName parameter that will usually accept a string[] array to run the command against multiple computers.

This post simply covers easy ways I've come across to get computers into a usable format for this parameter.  They're posted in no real particular order besides maybe most obvious to least obvious.

1.  Import from a basic text file of computer names separated by carriage return/line feeds; e.g.:

[Contents of computers.txt]
server1
server2
server3

[PowerShell command(s)]
  1. PS C:\>Get-Content computers.txt
  2. PS C:\>gc computers.txt
  3. PS C:\>[System.IO.File]::ReadAllLines(computers.txt)
First example uses the full cmdlet name.
Second example uses the alias for the Get-Content cmdlet.
Third example uses .NET.

2.  Import from a comma-separated file (CSV) of computer names and other data; e.g.:

[Contents of computers.csv]
Name,OS,IP
server1,w2k3,192.168.2.1
server2,w2k8,192.168.2.2
server3,w2k8,192.168.2.3

[PowerShell command(s)]
  1. PS C:\>Import-Csv computers.txt | Select-Object -Expand name

Import-Csv essentially reads in a properly formatted CSV file and turns it into a PSCustomObject that has assigns the columns of the CSV to object properties.  Because we only need an array of computer names, we Select only the object-property we care about 'name' and use the -ExpandProperty property to create the required string array [string[]].

3.  Get computer names from Active Directory:

[PowerShell command(s)]
  1. PS C:\>Import-Module ActiveDirectory; Get-ADComputer -Filter * | Select-Object -Expand name
  2. PS C:\>([adsisearcher]'(objectcategory=computer)').FindAll()
First example uses the ActiveDirectory module cmdlets
Second example uses the .NET ADSISearcher class via a type-accelerator ([adsisearcher]) to directly interface with AD via an LDAP search.

4.  Manually build a string[] array from computer names on the clipboard:

[PowerShell command(s)]
PS C:\>$computers = '
>>[ctrl-v to paste the contents of the clipboard here]
>>'
PS C:\>$computers = $computers.Trim().Split()

5.  Use some .NET methods:

PS C:\>$computers = [System.IO.File]::ReadAllLines($PathToFile)

...The System.IO.File class has many other methods for reading in data depending on whether you want to use a StreamReader or get the filebytes instead.

No comments:

Post a Comment