September 24, 2010

PsExec and multiple hosts

This is to show how you can run a single command on multiple hosts in order to automate a process which would otherwise take up a lot of time.

Some will argue that VBScript might be a better idea but I like to keep it really simple and I'm a huge fan of Mark Russinovich and his SysInternals suite. So here it goes.

First create a TXT file with server host names (or IP addresses) listed in a column (one per line) like so:



Save the text file as whatever name you wish.. for example server_list.txt

Lets say you want to schedule the defrag command to run every Saturday of every week at 5am starting on the next occurrence of a Saturday.

The following assumes that you run PsExec from the same folder as your server_list.txt file and have administrative privileges on the machines defined in the list file. This would be the syntax for running defrag on the system partition:

psexec.exe @server_list.txt at 05:00 /every:S "defrag.exe c:"

Command exits out with the following:

Added a new job with job ID = 8
at exited on SERVER1 with error code 0.

You can now take a look at the servers Scheduled Tasks and will notice a new task with ID 8 as in the command output. A drive defrag will now run every week as scheduled.

As many of us like logging everything possible, you might want to do the following:

psexec.exe @server_list.txt at 05:00 /every:S "defrag.exe c:" > psexeclog.txt

This will log all events and errors and pipe them to psexeclog.txt created on your local machine. Output of psexeclog.txt looks like so:

Added a new job with job ID = 12
Added a new job with job ID = 13

This means that job 12 was created on SERVER1 and job 13 on SERVER2. Note that the job ID might be different on each server depending on the past scheduled jobs count.

If you wish to have a full error output add 2>&1 to the previous command like so:

psexec.exe @server_list.txt at 05:00 /every:S "defrag.exe c:" > psexeclog.txt 2>&1

Remember that you can also run batch commands using psexec. So in the case of this example you might schedule multiple jobs to run on multiple servers by simply adding the commands to the batch.

Have fun!

No comments:

Post a Comment