© Michael Mihin, 123RF.com
Keeping PowerShell in the loop
Loop-the-Loop
Gathering information from a local system or a single remote system is all well and good, but often you need information from several systems at once. PowerShell can help. All you need is a little patience and light scripting skills. PowerShell versions 1.0 and 2.0 have a somewhat limited ability to grab information from remote systems singly or in bulk. Therefore, you have to work around those limitations to create automation tools that "trick" PowerShell into performing actions on remote systems as if they were operating on a local host.
In the previous issue [1], I talked about starting PowerShell, running some basic Get commands, and using the Help system. Then, I showed you how to control services, processes, and commands on local and remote systems. In this article, you'll discover the power of loops to automate repetitive processes.
PowerShell [2] has a Get-Content cmdlet that reads a text file into the buffer one line at a time. This feature is especially handy for use in loops to extract the same information from several systems within a single script.
Consider the following comparatively simple Linux Bash script that reads in a text file (systems.txt) one line at a time, performs an operation (echoes the system name) on each line, then exits. The file is a list of systems.
while read system do echo $system done < systems.txt
The equivalent PowerShell script is:
ForEach ($system in Get-Content "systems.txt")
{
Write-Host $system
}Both scripts read the systems.txt file line-by-line from top to bottom and perform the specified function until there are no more entries in the text file. Loops allow you to automate repetitive processes that are too tedious even for the newest of newbie in your group.
Buy this article as PDF
(incl. VAT)
Buy ADMIN Magazine
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Most Popular
Support Our Work
ADMIN content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.

