How to Execute a Command on Each Computer in a Domain

written by: Len Parov; article published: year 2007, month 05;



In: Categories » Computers and technology » Microsoft OS family » How to Execute a Command on Each Computer in a Domain

This handy script lets you easily run any command on a specified subset of computers in your domain.

Running the same command on multiple computers in your domain can be tedious indeed, but such a scenario is common in an administrator's life. I've written this hack to make this chore easier. The script traverses member systems of a domain, executing a command against each system that has a name that matches a particular specification you specify in the command line. Note that regular expressions are legal in this script, which makes it a powerful and flexible addition to the administrator's toolkit.

The Code

To use this script, type it into a text editor such as Notepad (make sure Word Wrap is disabled) and save it with a .vbs extension as ExecuteAll.vbs.

'Script Name: ExecuteAll.vbs
 
Option Explicit
 
Dim oDomain, oService, oItem, oShell
Dim strDomain, strSpec, strCommand, intButton
Dim oArgs, strFinalCommand, oRegEx, boolConfirm
 
' Prepare to execute commands & do popups
Set oShell = CreateObject("WScript.Shell")
 
GetArguments
 
' Access the domain so we can traverse objects
WScript.Echo "Accessing NT Domain " & strDomain
Set oDomain = GetObject("WinNT://" & strDomain)
 
' Initiate our regular expression support
Set oRegEx = New RegExp
oRegEx.Pattern = strSpec
oRegEx.IgnoreCase = True
 
' Traverse each computer (WinNT) object in the domain
WScript.Echo "Searching for " & strSpec
oDomain.Filter = Array("Computer") ' only look at computers
For Each oItem In oDomain
If oRegEx.Test(oItem.Name) Then
WScript.Echo " Matched " & oItem.Name
strFinalCommand = Replace(strCommand, "$n", oItem.Name)
 
intButton = vbNo
If boolConfirm Then
intButton = oShell.Popup("Execute " & strFinalCommand & "?",,_
"System " & oItem.Name, vbYesno + vbQuestion)
End If
If (boolConfirm = False) Or (intButton = vbYes) Then
WScript.Echo " Executing: " & strFinalCommand
execute strFinalCommand
End If
End If
Next
 
' All done; clean up
Set oItem = Nothing
Set oRegEx = Nothing
Set oDomain = Nothing
Set oShell = Nothing
Set oArgs = Nothing
 
'
' Glean the arguments for our run from the command line, if provided.
' If any are missing, prompt for input. A blank input signals an abort.
'
' /Y is an optional last argument
Sub GetArguments
Dim i, strConfirm, intButton
Set oArgs = WScript.Arguments
 
boolConfirm = True ' assume always confirm
strDomain = "" ' domain to be traversed
strSpec = "" ' name specification to be matched
strCommand = "" ' command to be executed on each match
strConfirm = "" ' track prompting for confirmation setting
 
' Look for our optional 4th argument
If oArgs.Length = 4 Then
If UCase(oArgs.Item(3)) = "/Y" Then
boolConfirm = False
strConfirm = "/Y" ' don't prompt below
End If
End If
 
' Look for any specified arguments, in order
If oArgs.Length >= 1 Then strDomain = oArgs(0)
If oArgs.Length >= 2 Then strSpec = oArgs(1)
If oArgs.Length >= 3 Then strCommand = oArgs(2)
 
' Prompt for any arguments not specified on the command line
If strDomain = "" Then
strDomain = InputBox _
("Enter the name of the NT Domain to be traversed", _
"NT Domain")
End If
If strDomain = "" Then WScript.Quit
strDomain = UCase(strDomain)
 
If strSpec = "" Then
strSpec = InputBox _
("Enter your name specification for the computer(s) " & _
"that will be matched within the " & strDomain & " Domain." & _
vbCrlf & "Regular Expressions are acceptable.", _
"Name Specification")
End If
If strSpec = "" Then WScript.Quit
 
If strCommand = "" Then
strCommand = InputBox _
("Enter the command to be executed on each computer matching " & _
strSpec & " within the " & strDomain & " Domain." & _
vbCrlf & "$n will be substituted for the computer name.", _
"Command to Execute")
End If
If strCommand = "" Then WScript.Quit
 
If strConfirm = "" Then
intButton = oShell.Popup("Confirm each command prior to execution?",,_
"Confirm?", vbYesNo + vbQuestion)
If intButton = vbNo Then
boolConfirm = False
End If
End If
End Sub
 
' Execute a command. Each is always run under a new instance of the command
' processor. This allows the use of built-in commands and I/O redirection.
'
' We won't wait for command completion.
Sub Execute(strCommand)
Dim RetVal
 
strCommand = "%COMSPEC% /c " & strCommand
 
RetVal = oShell.Run(strCommand, 1, False)
End Sub

Running the Hack

Here is the syntax for running the script:

ExexcuteAll.vbs <DomainToTraverse> <ComputerSpecification> <Command> [/Y]

When the script runs, the matched system's name will be substituted for the occurrence of $n in the command to be performed. By default, each command instance is confirmed before it is executed, but you can specify /Y to always answer Yes instead.

Here's an example of how to run the script:

ExexcuteAll.vbs MYDOMAIN WKSATL* "del \\$n\admin$\activitylog.txt"

This example traverses the MYDOMAIN domain, looking for computer names that start with WKSATL* (note the wildcard) and deletes the activitylog.txt file from the C:\Winnt folder

legal disclaimer

1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service

Useful tools and features

Translate this article to...    Send this article to you or to a friend

Link to this article from your page   
If you like this article (tutorial), please link to it from your web page using the information above. Linking to this page, this is the only way to help us improve our service, the same time providing your visitors with a way to improve their online experience.

related articles

1. MS DOS Versus PC DOS
With modern PCs having a very high level of standardization and compatibility, today it is easy to see how Microsoft can market complete packaged operating systems that will install and work unmodified on practically any PC you can purchase or build. Without the standardization and compatibility we have come to depend on, different specific "flavors" of a given operating system would be required for specific different hardware. That is exactly how things were back in the early '80s when the IBM PC was introduced. Many o...

2. How to make your PC Available for Remote Desktop Connection
To use Remote Desktop to reach your computer from the Internet, both the computer and your Internet connection must always be up and running. In addition, you must be able to make connections from the outside world to your computer, so there are additional requirements: If you use dial-up Internet service, you'll need someone at home to establish the connection before you can connect to your computer. If you use cable or DSL Internet service, you must either have a static IP address ass...

3. How to Update DirectX ~ Advantages
Although most Windows applications place fairly low demands on the display system, putting up fairly static displays and updating them relatively infrequently, interactive games and video displays are very graphics intensive. Game players pay big bucks for fps, or frames per second, which is a measure of how fast the hardware and software can generate new images as the scene changes and objects move. Under about 30fps, the image flickers and motion is noticeably jerky. Beyond 30fps, faster updates aren't noticeable, and the e...

4. Using Simple File Sharing in Windows
Although most home users are typically happy letting anyone at any computer read or modify any file, business users need to restrict access to files with payroll, personnel, and proprietary information. Windows XP and its predecessors, Windows NT and Windows 2000, were primarily designed for business use, so they require usernames and passwords for identification, and have a security system that lets computer owners restrict access to sensitive files on a user-by-user and file-by-file basis on each computer. Unfortunate...

5. The Evolution of Microsoft Windows ~ The Windows 9x Family
By the mid-1990s, processor power had increased and memory prices had decreased dramatically since Windows' original release. The Internet had also sprung onto the world stage, from an academic tool to an instrument of global communication and commerce. (You may recall that Windows 3.1 did not even include support for the TCP/IP network protocol used on the Internetyou had to purchase it from a third-party vendor.) Users' expectations likewise had grown with computers' capabilities, and desktop publishing, graphics editing, and...

6. How to install Windows and Installation Types
Deciding on the type of installation to perform is dictated by many factors, such as the following: Is there an operating system currently installed? If so, do you want to preserve settings and configurations, or start from scratch? Will the installation be performed interactively or remotely? How many computers are to be installed at a single time? Is your network arranged in a domain model using Active Directory? These are ...

7. How to adjust Text Icons and Window Element Sizes
If you find the items on the screen difficult to read or see, you can either lower the screen resolution, which makes everything larger but blurrier, or ask Windows to make the elements themselves larger while keeping a crisper, high screen resolution. There are two ways you can do this. Here's the first procedure: 1. Right-click the Desktop and select Properties. 2. Save the current screen settings so if you're unhappy with the results, you can back the changes out. Select the Themes tab, click Save As, and enter ...