Add a User to the Local Administrators Group on Multiple Servers

This simple Perl script adds a user to the local Administrators group of multiple servers. You need to create a text file, servers.txt, that contains a list of the server names, one on each line. When you run the script, you should run it from the command line, and enter the name of the user you want to add as an argument to the script, for example:

addLocalAdmin mydomain\myuser

By the way, this script should be saved as a .cmd not a .pl. I'll explain that below.

The script demonstrates a number of other useful elements. First, this Perl script is wrapped in DOS batch commands (that's why you should save it as a .cmd). The only reason for that is that now you don't have to type scriptname.pl, you can just type scriptname. The first few lines at the top are DOS batch commands that launch Perl and tell it to run the Perl code in the file. Perl recognizes where the Perl code starts with the line that starts with #!, that's called the shebang. And Perl recognizes that the Perl code ends with __END__

Next, the script uses an argument passed from the command line. You can pass any number of command line parameters to a Perl script. Perl receives them in an array called @ARGV. The first parameter is $ARGV[0] and the second is $ARGV[1] and so on.

Finally, this script shows how to get Win32 error codes using the Win32::GetLastError() function (which returns a numeric error code) and how to display the related error text for that numeric code, using the Win32::FormatMessage() function.

@set file=%0
@if not exist %file% set file=%0.cmd
@perl -x %file%
@goto endofperl
#!perl
use Win32api::NET;
open IN,"servers.txt";
open OUT,">
results.txt";
@users=($ARGV[0]);
while(<IN>){
 chomp($server=$_);
 $server=~s/\s+//g;
 Win32API::Net::LocalGroupAddMembers($server, "administrators",\@users);
 $logevent=Win32::GetLastError();
 if($logevent eq "997"){
  $logevent=0;
 }
 print "$server\t- ".Win32::FormatMessage($logevent);
 print OUT "$server\t".Win32::FormatMessage($logevent);
}
close OUT;
__END__
:endofperl
pause

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...