Occasionally, you need to run a single
script against multiple computers. One way of doing so is to read a
list of the computers from a text file.
This script shows how to read the computer list from
a text file and then run the script against each computer in the list.
Although this script records the BIOS information for each computer in
the list, you can use it to do any other task by modifying the content
of the foreach loop.
The full script is presented here, with some comments on the lines in the following table.
$computers = get-content "c:\data\computerlist.txt"
"BIOS Information as of " + (get-date).tostring('MMM-dd-yyyy')
| out-file c:\data\computerbios.txt
foreach ($computer in $computers){
"Computer name: " + $computer -computername $computer
| out-file c:\data\computerbios.txt -append
get-wmiobject win32_bios | out-file c:\data\computerbios.txt -append
}
For this example, the computerlist.txt file has the following two lines:
Tip
This script reads from a file named computerlist.txt file. You can create the script manually or automatically.
Script Lines to Run Command Against Multiple Computers | Comments |
---|
$computers = get-content "c:\data\ computerlist.txt"
| This command reads the list of computer names from a file named computerlist.txt and places them in an array named $computers. You can view the array contents by entering $computers.
Note
If the file doesn’t exist, the script fails.
|
"BIOS Information as of " + (get-date).tostring('MMM-dd-yyyy') | out-file c:\data\computerbios.txt
| Next, a file header line is added, indicating what the file contains. The get-date cmdlet is used to add the month and year to the header, identifying when it was created.
Note
The -append switch is not used, so any existing data in the file is deleted.
|
foreach ($computer in $computers){ "Computer name: " + $computer | out-file c:\data\computerbios.txt -append get-wmiobject win32_bios -computername $computer | out-file c:\data\computerbios.txt -append }
| The foreach command loops through the $computers array. For each computer name in the array, it outputs data.
First, it outputs the name of the computer. Next, it uses the get-wmiobject cmdlet to retrieve information on the BIOS for the computer identified as $computer. It does this for each computer name retrieved from the computerlist.txt file and stored in the $computers variable. |
You can view the file with this command:
PS C:\> notepad c:\data\ computerbios.txt
| Figure 1 shows a screen shot of the opened file. |
Tip
This scripted used get-wmiobject, and there are thousands of commands you can execute using get-wmiobject.
You can’t know them all. However, Marc van Orsouw (AKA The PowerShell
Guy) wrote a great script known as the PowerShell WMI Explorer. You can
read about it and download it from http://thepowershellguy.com/blogs/posh/archive/2007/03/22/powershell-wmi-explorer-part-1.aspx. Figure 2 shows a screenshot of the WMI Explorer in action.