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!
Advertisement
Like this:
Be the first to like this post.