Reputation: 1
I want to create a C# function that connects to a given computer using WMI (CimSession), and schedule a given task at a given time. I decided to use the Win32_ScheduledJob class.
public static string Create_ScheduleTask(string path, string computer, string fqdn)
{
using var session = CimSession.Create(fqdn, DComOptions);
if (!session.TestConnection())
return $"{computer} - Failed to establish a connection to the computer.\n";
const string className = "Win32_ScheduledJob";
const string methodName = "Create";
var time = new DateTime(2024, 6, 7, 12, 0, 0, DateTimeKind.Utc);
try
{
var methodParameters = new CimMethodParametersCollection
{
CimMethodParameter.Create("Command", path, CimType.String, CimFlags.In),
CimMethodParameter.Create("StartTime", time, CimType.DateTime, CimFlags.In)
};
var result = session.InvokeMethod(WindowsNamespace, className, methodName, methodParameters);
if (result is not { ReturnValue: not null }) return $"{computer} - An unexpected error occurred. \n";
return (uint)result.ReturnValue.Value == 0
? $"{computer} - Scheduled task created successfully. \n"
: $"{computer} - Failed to create scheduled task. {result.ReturnValue.Value}\n";
}catch(Exception e)
{
Err.LogExceptionError(e);
return $"{computer} - Error executing script. {e.Message} \n";
}
}
This the code I am running but I am getting an exit code of 8. Which according to Microsoft, Unknown failure 8 Interactive process. I don't know where in my code I could of gone wrong.
Upvotes: 0
Views: 36