Tome's Land of IT

IT Notes from the Powertoe – Tome Tanasovski

Powerbits #7 – Copying and Pasting a List of Computers into a PowerShell Script as a Collection

It’s quite common to receive an e-mail from someone that has a list of computers that need a script run against it – or perhaps a list of perfmon counters that need to be collected – or even a list of usernames that someone needs you to pull from AD in order to create a custom report about the user and his attributes.  There are a few ways to put this data into your scripts.  Probably the most common method I have seen is to put this data into a file and run Get-Content file.txt.  This works fine,  but I generally just need to do a bit of one-off scripting and want to bang it out quick. When that happens I throw the list into a here string and break it up with the -split operator:

$computers = @"
Computer1
Computer2
Computer3
Computer4
"@ -split '\r\n'

This creates a collection of strings where each line has its own string.

PS C:\> $computers.gettype()

IsPublic IsSerial Name                                     BaseType                                         
-------- -------- ----                                     --------                                         
True     True     String[]                                 System.Array

Now you can throw this collection into a foreach loop

foreach ($computer in $computers) {
     #Do something to $computer
}

or better yet you can throw it at a parameter that takes a collection like Invoke-Command

Invoke-Command -Computername $computers -Scriptblock {Get-Process}

Nice! I just spanned out Get-Process to the four computers in my list!

Advertisements

One response to “Powerbits #7 – Copying and Pasting a List of Computers into a PowerShell Script as a Collection

  1. LittleJim August 21, 2014 at 9:11 pm

    I worked it out finally – for those that come after me; Powershell appears to be doing Unix-compatible line endings now, so you only need the \n and not the \r\n

    “@ -split ‘\n’

    PS H:\> $psversiontable

    Name Value
    —- —–
    CLRVersion 2.0.50727.5472
    BuildVersion 6.1.7601.17514
    PSVersion 2.0
    WSManStackVersion 2.0
    PSCompatibleVersions {1.0, 2.0}
    SerializationVersion 1.1.0.1
    PSRemotingProtocolVersion 2.1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: