C# Using WMI to Schedule a Task on a Remote Server

2.7k Views Asked by At

I'm try to run a batch file on a remote, Windows 2008 server. I need to the file to run in an interactive fashion as it will open up numerous interactive programs. I can't install services on the remote server. I'm having difficulty trying to create a task on the remote server

Code:

string command = @"c:\test.bat > c:\tmp_dr.dat";
ConnectionOptions conO = new ConnectionOptions();
conO.Username = username;
conO.Password = password;

ManagementScope scope = new ManagementScope(@"\\10.12.62.205\root\cimv2", conO);
scope.Connect();

//Getting time
string serverTime = null;
SelectQuery timeQuery = new SelectQuery(@"select LocalDateTime from Win32_OperatingSystem");
ManagementObjectSearcher timeQuerySearcher = new ManagementObjectSearcher(timeQuery);
foreach (ManagementObject mo in timeQuerySearcher.Get())
{
    serverTime = mo["LocalDateTime"].ToString();
}

//Adding 2 minutes to the time
string addTwoMinutes = (Convert.ToInt32(Strings.Mid(serverTime, 9, 4)) + 1).ToString();
if (Microsoft.VisualBasic.Strings.Mid(serverTime, 9, 1).Equals("0"))//Check if hour is zero
{
    addTwoMinutes = "0" + addTwoMinutes;
}
serverTime = Strings.Replace(serverTime, (Strings.Mid(serverTime, 9, 4)), addTwoMinutes, 1, -1, CompareMethod.Text);

//running command
object[] cmdParams = { command, serverTime, false, null, null, true, 0};
ManagementClass serverCommand = new ManagementClass(scope, new ManagementPath("Win32_ScheduledJob"), null);
serverCommand.InvokeMethod("Create", cmdParams);

I am able to retrieve the time but this does not seem to create a task on the remote server. I'm very new to all of this so I'd appreciate any guidance on the matter that people may be able to provide. Thanks

ALSO: psexec is not possible.

SOLUTION FOUND:

The command variable was being sent to AT as a string[]. Dumb mistake.

0

There are 0 best solutions below