/// <summary>
        /// Process input.
        /// </summary>
        protected override void ProcessRecord()
        {
            // Get ScheduledJobDefinition object.
            ScheduledJobDefinition definition = null;

            switch (ParameterSetName)
            {
            case JobDefinitionParameterSet:
                definition = _definition;
                break;

            case JobDefinitionIdParameterSet:
                definition = GetJobDefinitionById(_id);
                break;

            case JobDefinitionNameParameterSet:
                definition = GetJobDefinitionByName(_name);
                break;
            }

            // Return options from the definition object.
            if (definition != null)
            {
                WriteObject(definition.Options);
            }
        }
示例#2
0
 private ScheduledJobTrigger(SerializationInfo info, StreamingContext context)
 {
     this._interval = 1;
     this._enabled  = true;
     if (info != null)
     {
         DateTime dateTime = info.GetDateTime("Time_Value");
         if (dateTime == DateTime.MinValue)
         {
             this._time = null;
         }
         else
         {
             this._time = new DateTime?(dateTime);
         }
         this.RepetitionInterval = (TimeSpan?)info.GetValue("RepetitionInterval_Value", typeof(TimeSpan));
         this.RepetitionDuration = (TimeSpan?)info.GetValue("RepetitionDuration_Value", typeof(TimeSpan));
         this._daysOfWeek        = (List <DayOfWeek>)info.GetValue("DaysOfWeek_Value", typeof(List <DayOfWeek>));
         this._randomDelay       = (TimeSpan)info.GetValue("RandomDelay_Value", typeof(TimeSpan));
         this._interval          = info.GetInt32("Interval_Value");
         this._user              = info.GetString("User_Value");
         this._frequency         = (TriggerFrequency)info.GetValue("TriggerFrequency_Value", typeof(TriggerFrequency));
         this._id                = info.GetInt32("ID_Value");
         this._enabled           = info.GetBoolean("Enabled_Value");
         this._jobDefAssociation = null;
         return;
     }
     else
     {
         throw new PSArgumentNullException("info");
     }
 }
示例#3
0
        /// <summary>
        /// Creates a new task in WTS with information from ScheduledJobDefinition.
        /// </summary>
        /// <param name="definition">ScheduledJobDefinition</param>
        public void CreateTask(
            ScheduledJobDefinition definition)
        {
            if (definition == null)
            {
                throw new PSArgumentNullException("definition");
            }

            // Create task definition
            ITaskDefinition iTaskDefinition = _taskScheduler.NewTask(0);

            // Add task options.
            AddTaskOptions(iTaskDefinition, definition.Options);

            // Add task triggers.
            foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers)
            {
                AddTaskTrigger(iTaskDefinition, jobTrigger);
            }

            // Add task action.
            AddTaskAction(iTaskDefinition, definition);

            // Create a security descriptor for the current user so that only the user
            // (and Local System account) can see/access the registered task.
            string startSddl = "D:P(A;;GA;;;SY)(A;;GA;;;BA)";   // DACL Allow Generic Access to System and BUILTIN\Administrators.

            System.Security.Principal.SecurityIdentifier userSid =
                System.Security.Principal.WindowsIdentity.GetCurrent().User;
            CommonSecurityDescriptor SDesc = new CommonSecurityDescriptor(false, false, startSddl);

            SDesc.DiscretionaryAcl.AddAccess(AccessControlType.Allow, userSid, 0x10000000, InheritanceFlags.None, PropagationFlags.None);
            string sddl = SDesc.GetSddlForm(AccessControlSections.All);

            // Register this new task with the Task Scheduler.
            if (definition.Credential == null)
            {
                // Register task to run as currently logged on user.
                _iRootFolder.RegisterTaskDefinition(
                    definition.Name,
                    iTaskDefinition,
                    (int)_TASK_CREATION.TASK_CREATE,
                    null,       // User name
                    null,       // Password
                    _TASK_LOGON_TYPE.TASK_LOGON_S4U,
                    sddl);
            }
            else
            {
                // Register task to run under provided user account/credentials.
                _iRootFolder.RegisterTaskDefinition(
                    definition.Name,
                    iTaskDefinition,
                    (int)_TASK_CREATION.TASK_CREATE,
                    definition.Credential.UserName,
                    GetCredentialPassword(definition.Credential),
                    _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD,
                    sddl);
            }
        }
示例#4
0
        private ScheduledJobTrigger(
            SerializationInfo info,
            StreamingContext context)
        {
            if (info == null)
            {
                throw new PSArgumentNullException("info");
            }

            DateTime time = info.GetDateTime("Time_Value");

            if (time != DateTime.MinValue)
            {
                _time = time;
            }
            else
            {
                _time = null;
            }

            RepetitionInterval = (TimeSpan?)info.GetValue("RepetitionInterval_Value", typeof(TimeSpan));
            RepetitionDuration = (TimeSpan?)info.GetValue("RepetitionDuration_Value", typeof(TimeSpan));

            _daysOfWeek  = (List <DayOfWeek>)info.GetValue("DaysOfWeek_Value", typeof(List <DayOfWeek>));
            _randomDelay = (TimeSpan)info.GetValue("RandomDelay_Value", typeof(TimeSpan));
            _interval    = info.GetInt32("Interval_Value");
            _user        = info.GetString("User_Value");
            _frequency   = (TriggerFrequency)info.GetValue("TriggerFrequency_Value", typeof(TriggerFrequency));
            _id          = info.GetInt32("ID_Value");
            _enabled     = info.GetBoolean("Enabled_Value");

            // Runtime reference and not saved to store.
            _jobDefAssociation = null;
        }
示例#5
0
        /// <summary>
        /// Returns an array of ScheduledJobDefinition objects from the local
        /// scheduled job definition repository corresponding to the provided Ids.
        /// </summary>
        /// <param name="ids">Local repository scheduled job definition ids</param>
        /// <param name="writeErrorsAndWarnings">Errors/warnings are written to host</param>
        /// <returns>List of ScheduledJobDefinition objects</returns>
        internal List <ScheduledJobDefinition> GetJobDefinitionsById(
            Int32[] ids,
            bool writeErrorsAndWarnings = true)
        {
            Dictionary <string, Exception> errors = ScheduledJobDefinition.RefreshRepositoryFromStore(null);

            HandleAllLoadErrors(errors);

            List <ScheduledJobDefinition> definitions = new List <ScheduledJobDefinition>();
            HashSet <Int32> findIds = new HashSet <Int32>(ids);

            foreach (var definition in ScheduledJobDefinition.Repository.Definitions)
            {
                if (findIds.Contains(definition.Id) &&
                    ValidateJobDefinition(definition))
                {
                    definitions.Add(definition);
                    findIds.Remove(definition.Id);
                }
            }

            if (writeErrorsAndWarnings)
            {
                foreach (int id in findIds)
                {
                    WriteDefinitionNotFoundByIdError(id);
                }
            }

            return(definitions);
        }
        /// <summary>
        /// Creates a new Job2 object based on a definition name
        /// that can be run manually.  If the path parameter is
        /// null then a default location will be used to find the
        /// job definition by name.
        /// </summary>
        /// <param name="definitionName">ScheduledJob definition name.</param>
        /// <param name="definitionPath">ScheduledJob definition file path.</param>
        /// <returns>Job2 object.</returns>
        public override Job2 NewJob(string definitionName, string definitionPath)
        {
            if (string.IsNullOrEmpty(definitionName))
            {
                throw new PSArgumentException("definitionName");
            }

            Job2 rtnJob = null;

            try
            {
                ScheduledJobDefinition scheduledJobDef =
                    ScheduledJobDefinition.LoadFromStore(definitionName, definitionPath);

                rtnJob = new ScheduledJob(
                    scheduledJobDef.Command,
                    scheduledJobDef.Name,
                    scheduledJobDef);
            }
            catch (FileNotFoundException)
            {
                // Return null if no job definition exists.
            }

            return(rtnJob);
        }
示例#7
0
        /// <summary>
        /// Returns an array of ScheduledJobDefinition objects from the local
        /// scheduled job definition repository corresponding to the given name.
        /// </summary>
        /// <param name="name">Scheduled job definition name</param>
        /// <param name="writeErrorsAndWarnings">Errors/warnings are written to host</param>
        /// <returns>ScheduledJobDefinition object</returns>
        internal ScheduledJobDefinition GetJobDefinitionByName(
            string name,
            bool writeErrorsAndWarnings = true)
        {
            Dictionary <string, Exception> errors = ScheduledJobDefinition.RefreshRepositoryFromStore(null);

            // Look for match.
            WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase);

            foreach (var definition in ScheduledJobDefinition.Repository.Definitions)
            {
                if (namePattern.IsMatch(definition.Name) &&
                    ValidateJobDefinition(definition))
                {
                    return(definition);
                }
            }

            // Look for load error.
            foreach (var error in errors)
            {
                if (namePattern.IsMatch(error.Key))
                {
                    HandleLoadError(error.Key, error.Value);
                }
            }

            if (writeErrorsAndWarnings)
            {
                WriteDefinitionNotFoundByNameError(name);
            }

            return(null);
        }
示例#8
0
        /// <summary>
        /// Validates the job definition object retrieved from store by syncing
        /// its data with the corresponding Task Scheduler task.  If no task
        /// is found then validation fails.
        /// </summary>
        /// <param name="definition"></param>
        /// <returns></returns>
        private bool ValidateJobDefinition(ScheduledJobDefinition definition)
        {
            Exception ex = null;

            try
            {
                definition.SyncWithWTS();
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                ex = e;
            }
            catch (System.IO.FileNotFoundException e)
            {
                ex = e;
            }
            catch (System.ArgumentNullException e)
            {
                ex = e;
            }

            if (ex != null)
            {
                WriteErrorLoadingDefinition(definition.Name, ex);
            }

            return(ex == null);
        }
        private void RefreshRepository()
        {
            Collection <DateTime> jobRuns = null;
            Job2 job2;

            this.CreateFileSystemWatcher();
            IEnumerable <string> jobDefinitions = ScheduledJobStore.GetJobDefinitions();

            foreach (string str in jobDefinitions)
            {
                jobRuns = ScheduledJobSourceAdapter.GetJobRuns(str);
                if (jobRuns == null)
                {
                    continue;
                }
                ScheduledJobDefinition scheduledJobDefinition = null;
                IEnumerator <DateTime> enumerator             = jobRuns.GetEnumerator();
                using (enumerator)
                {
                    while (enumerator.MoveNext())
                    {
                        DateTime dateTime = enumerator.Current;
                        if (dateTime <= ScheduledJobSourceAdapter.JobRepository.GetLatestJobRun(str))
                        {
                            continue;
                        }
                        try
                        {
                            if (scheduledJobDefinition == null)
                            {
                                scheduledJobDefinition = ScheduledJobDefinition.LoadFromStore(str, null);
                            }
                            job2 = ScheduledJobSourceAdapter.LoadJobFromStore(scheduledJobDefinition.Name, dateTime);
                        }
                        catch (ScheduledJobException scheduledJobException)
                        {
                            continue;
                        }
                        catch (DirectoryNotFoundException directoryNotFoundException)
                        {
                            continue;
                        }
                        catch (FileNotFoundException fileNotFoundException)
                        {
                            continue;
                        }
                        catch (UnauthorizedAccessException unauthorizedAccessException)
                        {
                            continue;
                        }
                        catch (IOException oException)
                        {
                            continue;
                        }
                        ScheduledJobSourceAdapter.JobRepository.AddOrReplace(job2);
                        ScheduledJobSourceAdapter.JobRepository.SetLatestJobRun(str, dateTime);
                    }
                }
            }
        }
示例#10
0
        /// <summary>
        /// Makes delegate callback call for each scheduledjob definition object found.
        /// </summary>
        /// <param name="ids">Local repository scheduled job definition ids</param>
        /// <param name="itemFound">Callback delegate for each discovered item.</param>
        /// <param name="writeErrorsAndWarnings">Errors/warnings are written to host</param>
        internal void FindJobDefinitionsById(
            Int32[] ids,
            Action <ScheduledJobDefinition> itemFound,
            bool writeErrorsAndWarnings = true)
        {
            HashSet <Int32> findIds = new HashSet <Int32>(ids);
            Dictionary <string, Exception> errors = ScheduledJobDefinition.RefreshRepositoryFromStore((definition) =>
            {
                if (findIds.Contains(definition.Id) &&
                    ValidateJobDefinition(definition))
                {
                    itemFound(definition);
                    findIds.Remove(definition.Id);
                }
            });

            HandleAllLoadErrors(errors);

            if (writeErrorsAndWarnings)
            {
                foreach (Int32 id in findIds)
                {
                    WriteDefinitionNotFoundByIdError(id);
                }
            }
        }
示例#11
0
 public void UpdateTask(ScheduledJobDefinition definition)
 {
     if (definition != null)
     {
         ITaskDefinition enabled = this.FindTask(definition.Name);
         this.AddTaskOptions(enabled, definition.Options);
         enabled.Settings.Enabled = definition.Enabled;
         enabled.Triggers.Clear();
         foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers)
         {
             this.AddTaskTrigger(enabled, jobTrigger);
         }
         enabled.Actions.Clear();
         this.AddTaskAction(enabled, definition);
         if (definition.Credential != null)
         {
             this._iRootFolder.RegisterTaskDefinition(definition.Name, enabled, 4, definition.Credential.UserName, this.GetCredentialPassword(definition.Credential), _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD, null);
             return;
         }
         else
         {
             this._iRootFolder.RegisterTaskDefinition(definition.Name, enabled, 4, null, null, _TASK_LOGON_TYPE.TASK_LOGON_S4U, null);
             return;
         }
     }
     else
     {
         throw new PSArgumentNullException("definition");
     }
 }
        protected override void ProcessRecord()
        {
            ScheduledJobDefinition jobDefinitionById = null;
            string parameterSetName = base.ParameterSetName;
            string str = parameterSetName;

            if (parameterSetName != null)
            {
                if (str == "JobDefinition")
                {
                    jobDefinitionById = this._definition;
                }
                else
                {
                    if (str == "JobDefinitionId")
                    {
                        jobDefinitionById = base.GetJobDefinitionById(this._id, true);
                    }
                    else
                    {
                        if (str == "JobDefinitionName")
                        {
                            jobDefinitionById = base.GetJobDefinitionByName(this._name, true);
                        }
                    }
                }
            }
            if (jobDefinitionById != null)
            {
                base.WriteObject(jobDefinitionById.Options);
            }
        }
示例#13
0
 public void CreateTask(ScheduledJobDefinition definition)
 {
     if (definition != null)
     {
         ITaskDefinition variable = this._taskScheduler.NewTask(0);
         this.AddTaskOptions(variable, definition.Options);
         foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers)
         {
             this.AddTaskTrigger(variable, jobTrigger);
         }
         this.AddTaskAction(variable, definition);
         string                   str  = "D:P(A;;GA;;;SY)(A;;GA;;;BA)";
         SecurityIdentifier       user = WindowsIdentity.GetCurrent().User;
         CommonSecurityDescriptor commonSecurityDescriptor = new CommonSecurityDescriptor(false, false, str);
         commonSecurityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, user, 0x10000000, InheritanceFlags.None, PropagationFlags.None);
         string sddlForm = commonSecurityDescriptor.GetSddlForm(AccessControlSections.All);
         if (definition.Credential != null)
         {
             this._iRootFolder.RegisterTaskDefinition(definition.Name, variable, 2, definition.Credential.UserName, this.GetCredentialPassword(definition.Credential), _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD, sddlForm);
             return;
         }
         else
         {
             this._iRootFolder.RegisterTaskDefinition(definition.Name, variable, 2, null, null, _TASK_LOGON_TYPE.TASK_LOGON_S4U, sddlForm);
             return;
         }
     }
     else
     {
         throw new PSArgumentNullException("definition");
     }
 }
示例#14
0
        private ScheduledJobOptions(
            SerializationInfo info,
            StreamingContext context)
        {
            if (info == null)
            {
                throw new PSArgumentNullException("info");
            }

            _startIfOnBatteries     = info.GetBoolean("StartIfOnBatteries_Value");
            _stopIfGoingOnBatteries = info.GetBoolean("StopIfGoingOnBatteries_Value");
            _wakeToRun              = info.GetBoolean("WakeToRun_Value");
            _startIfNotIdle         = info.GetBoolean("StartIfNotIdle_Value");
            _stopIfGoingOffIdle     = info.GetBoolean("StopIfGoingOffIdle_Value");
            _restartOnIdleResume    = info.GetBoolean("RestartOnIdleResume_Value");
            _idleDuration           = (TimeSpan)info.GetValue("IdleDuration_Value", typeof(TimeSpan));
            _idleTimeout            = (TimeSpan)info.GetValue("IdleTimeout_Value", typeof(TimeSpan));
            _showInTaskScheduler    = info.GetBoolean("ShowInTaskScheduler_Value");
            _runElevated            = info.GetBoolean("RunElevated_Value");
            _runWithoutNetwork      = info.GetBoolean("RunWithoutNetwork_Value");
            _donotAllowDemandStart  = info.GetBoolean("DoNotAllowDemandStart_Value");
            _multipleInstancePolicy = (TaskMultipleInstancePolicy)info.GetValue("TaskMultipleInstancePolicy_Value", typeof(TaskMultipleInstancePolicy));

            // Runtime reference and not saved to store.
            _jobDefAssociation = null;
        }
示例#15
0
        internal void FindJobDefinitionsByName(string[] names, Action <ScheduledJobDefinition> itemFound, bool writeErrorsAndWarnings = true)
        {
            HashSet <string> strs = new HashSet <string>(names);
            Dictionary <string, WildcardPattern> strs1 = new Dictionary <string, WildcardPattern>();

            string[] strArrays = names;
            for (int i = 0; i < (int)strArrays.Length; i++)
            {
                string str = strArrays[i];
                if (!strs1.ContainsKey(str))
                {
                    strs1.Add(str, new WildcardPattern(str, WildcardOptions.IgnoreCase));
                }
            }
            Dictionary <string, Exception> strs2 = ScheduledJobDefinition.RefreshRepositoryFromStore((ScheduledJobDefinition definition) => {
                foreach (KeyValuePair <string, WildcardPattern> pattern in strs1)
                {
                    if (!pattern.Value.IsMatch(definition.Name) || !this.ValidateJobDefinition(definition))
                    {
                        continue;
                    }
                    itemFound(definition);
                    if (!strs.Contains(pattern.Key))
                    {
                        continue;
                    }
                    strs.Remove(pattern.Key);
                }
            }
                                                                                                     );

            foreach (KeyValuePair <string, Exception> keyValuePair in strs2)
            {
                Dictionary <string, WildcardPattern> .Enumerator enumerator = strs1.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        var keyValuePair1 = enumerator.Current;
                        if (!keyValuePair1.Value.IsMatch(keyValuePair.Key))
                        {
                            continue;
                        }
                        this.HandleLoadError(keyValuePair.Key, keyValuePair.Value);
                    }
                }
                finally
                {
                    enumerator.Dispose();
                }
            }
            if (writeErrorsAndWarnings)
            {
                foreach (string str1 in strs)
                {
                    this.WriteDefinitionNotFoundByNameError(str1);
                }
            }
        }
示例#16
0
        private void AddTaskAction(ITaskDefinition iTaskDefinition, ScheduledJobDefinition definition)
        {
            IExecAction pSExecutionPath = iTaskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction;

            pSExecutionPath.Id        = "StartPowerShellJob";
            pSExecutionPath.Path      = definition.PSExecutionPath;
            pSExecutionPath.Arguments = definition.PSExecutionArgs;
        }
示例#17
0
 private void HandleLoadError(string name, Exception e)
 {
     if (e as IOException != null || e as XmlException != null || e as TypeInitializationException != null || e as SerializationException != null || e as ArgumentNullException != null)
     {
         ScheduledJobDefinition.RemoveDefinition(name);
         this.WriteErrorLoadingDefinition(name, e);
     }
 }
示例#18
0
        internal List <ScheduledJobDefinition> GetAllJobDefinitions()
        {
            Dictionary <string, Exception> strs = ScheduledJobDefinition.RefreshRepositoryFromStore(null);

            this.HandleAllLoadErrors(strs);
            this.ValidateJobDefinitions();
            return(ScheduledJobDefinition.Repository.Definitions);
        }
示例#19
0
        private void RefreshRepository()
        {
            ScheduledJobStore.CreateDirectoryIfNotExists();
            CreateFileSystemWatcher();

            IEnumerable <string> jobDefinitions = ScheduledJobStore.GetJobDefinitions();

            foreach (string definitionName in jobDefinitions)
            {
                // Create Job2 objects for each job run in store.
                Collection <DateTime> jobRuns = GetJobRuns(definitionName);
                if (jobRuns == null)
                {
                    continue;
                }

                ScheduledJobDefinition definition = null;
                foreach (DateTime jobRun in jobRuns)
                {
                    if (jobRun > JobRepository.GetLatestJobRun(definitionName))
                    {
                        Job2 job;
                        try
                        {
                            if (definition == null)
                            {
                                definition = ScheduledJobDefinition.LoadFromStore(definitionName, null);
                            }

                            job = LoadJobFromStore(definition.Name, jobRun);
                        }
                        catch (ScheduledJobException)
                        {
                            continue;
                        }
                        catch (DirectoryNotFoundException)
                        {
                            continue;
                        }
                        catch (FileNotFoundException)
                        {
                            continue;
                        }
                        catch (UnauthorizedAccessException)
                        {
                            continue;
                        }
                        catch (IOException)
                        {
                            continue;
                        }

                        JobRepository.AddOrReplace(job);
                        JobRepository.SetLatestJobRun(definitionName, jobRun);
                    }
                }
            }
        }
        protected override void ProcessRecord()
        {
            string str;
            ScheduledJobDefinition jobDefinitionById = null;
            string parameterSetName = base.ParameterSetName;
            string str1             = parameterSetName;

            if (parameterSetName != null)
            {
                if (str1 == "Definition")
                {
                    jobDefinitionById = this._definition;
                }
                else
                {
                    if (str1 == "DefinitionId")
                    {
                        jobDefinitionById = base.GetJobDefinitionById(this._definitionId, true);
                    }
                    else
                    {
                        if (str1 == "DefinitionName")
                        {
                            jobDefinitionById = base.GetJobDefinitionByName(this._definitionName, true);
                        }
                    }
                }
            }
            if (this.Enabled)
            {
                str = "Enable";
            }
            else
            {
                str = "Disable";
            }
            string str2 = str;

            if (jobDefinitionById != null && base.ShouldProcess(jobDefinitionById.Name, str2))
            {
                try
                {
                    jobDefinitionById.SetEnabled(this.Enabled, true);
                }
                catch (ScheduledJobException scheduledJobException1)
                {
                    ScheduledJobException scheduledJobException = scheduledJobException1;
                    string      str3             = StringUtil.Format(ScheduledJobErrorStrings.CantSetEnableOnJobDefinition, jobDefinitionById.Name);
                    Exception   runtimeException = new RuntimeException(str3, scheduledJobException);
                    ErrorRecord errorRecord      = new ErrorRecord(runtimeException, "CantSetEnableOnScheduledJobDefinition", ErrorCategory.InvalidOperation, jobDefinitionById);
                    base.WriteError(errorRecord);
                }
                if (this._passThru)
                {
                    base.WriteObject(jobDefinitionById);
                }
            }
        }
示例#21
0
        /// <summary>
        /// Starts task running from Task Scheduler.
        /// </summary>
        /// <param name="definition">ScheduledJobDefinition</param>
        /// <exception cref="System.IO.DirectoryNotFoundException"></exception>
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        public void RunTask(
            ScheduledJobDefinition definition)
        {
            // Get registered task.
            IRegisteredTask iRegisteredTask = _iRootFolder.GetTask(definition.Name);

            // Run task.
            iRegisteredTask.Run(null);
        }
示例#22
0
 private static void Transports(IRegistrar <ITransport> services)
 {
     services
     .Add(new DemoTransport(new[] { new CompositeCommand() }))
     //throw
     .Add(new DemoTransport(new[]
     {
         new ThrowCommand(), new ThrowCommand {
             Type = nameof(TimeoutException)
         }
     }))
     // delays
     .Add(new DemoTransport(new[]
     {
         new DelayCommand(TimeSpan.FromSeconds(2)), new DelayCommand(TimeSpan.FromMinutes(2)),
         new DelayCommand(TimeSpan.FromSeconds(20))
         {
             WatchDogTimeout = TimeSpan.FromSeconds(30)
         }
     }))
     // combined
     .Add(new DemoTransport(new[]
     {
         new CompositeCommand {
             Delay = new DelayCommand(TimeSpan.FromSeconds(2))
         },
         new CompositeCommand {
             Delay = new DelayCommand(TimeSpan.FromMinutes(2))
         },
         new CompositeCommand
         {
             Delay = new DelayCommand(TimeSpan.FromSeconds(2)), Throw = new ThrowCommand()
         },
         new CompositeCommand
         {
             Delay = new DelayCommand(TimeSpan.FromMinutes(2)), Throw = new ThrowCommand()
         }
     }))
     // scheduled
     .Add(new ScheduledTransport(new InMemoryScheduledJobStore(new[]
     {
         ScheduledJobDefinition.Create("* * * * *", new HelloCommand {
             Message = "Hi (every min)"
         }),
         ScheduledJobDefinition.Create("*/2 * * * *", new ProduceInProcess()),
         new ScheduledJobDefinition
         {
             Cron        = "*/5 * * * *",
             Name        = typeof(HelloCommand).FullName,
             Content     = "{\"Message\":\"How are you (every 5 min)\"}",
             ContentType = "json"
         }
     })))
     // in process
     .Add(InProcess.Instance);
 }
		private ScheduledJobDefinition CreateScriptBlockDefinition()
		{
			JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), this.ScriptBlock.ToString(), this._name);
			jobDefinition.ModuleName = "PSScheduledJob";
			Dictionary<string, object> strs = this.CreateCommonParameters();
			strs.Add("ScriptBlock", this.ScriptBlock);
			JobInvocationInfo scheduledJobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, strs);
			ScheduledJobDefinition scheduledJobDefinition = new ScheduledJobDefinition(scheduledJobInvocationInfo, this.Trigger, this.ScheduledJobOption, this._credential);
			return scheduledJobDefinition;
		}
示例#24
0
        /// <summary>
        /// Updates an existing task in WTS with information from
        /// ScheduledJobDefinition.
        /// </summary>
        /// <param name="definition">ScheduledJobDefinition</param>
        public void UpdateTask(
            ScheduledJobDefinition definition)
        {
            if (definition == null)
            {
                throw new PSArgumentNullException("definition");
            }

            // Get task to update.
            ITaskDefinition iTaskDefinition = FindTask(definition.Name);

            // Replace options.
            AddTaskOptions(iTaskDefinition, definition.Options);

            // Set enabled state.
            iTaskDefinition.Settings.Enabled = definition.Enabled;

            // Replace triggers.
            iTaskDefinition.Triggers.Clear();
            foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers)
            {
                AddTaskTrigger(iTaskDefinition, jobTrigger);
            }

            // Replace action.
            iTaskDefinition.Actions.Clear();
            AddTaskAction(iTaskDefinition, definition);

            // Register updated task.
            if (definition.Credential == null)
            {
                // Register task to run as currently logged on user.
                _iRootFolder.RegisterTaskDefinition(
                    definition.Name,
                    iTaskDefinition,
                    (int)_TASK_CREATION.TASK_UPDATE,
                    null,           // User name
                    null,           // Password
                    _TASK_LOGON_TYPE.TASK_LOGON_S4U,
                    null);
            }
            else
            {
                // Register task to run under provided user account/credentials.
                _iRootFolder.RegisterTaskDefinition(
                    definition.Name,
                    iTaskDefinition,
                    (int)_TASK_CREATION.TASK_UPDATE,
                    definition.Credential.UserName,
                    GetCredentialPassword(definition.Credential),
                    _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD,
                    null);
            }
        }
示例#25
0
        /// <summary>
        /// Removes the WTS task for this ScheduledJobDefinition.
        /// Throws error if one or more instances of this task are running.
        /// Force parameter will stop all running instances and remove task.
        /// </summary>
        /// <param name="definition">ScheduledJobDefinition</param>
        /// <param name="force">Force running instances to stop and remove task</param>
        public void RemoveTask(
            ScheduledJobDefinition definition,
            bool force = false)
        {
            if (definition == null)
            {
                throw new PSArgumentNullException("definition");
            }

            RemoveTaskByName(definition.Name, force, false);
        }
示例#26
0
        private void AddTaskAction(
            ITaskDefinition iTaskDefinition,
            ScheduledJobDefinition definition)
        {
            IExecAction iExecAction = iTaskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction;

            Debug.Assert(iExecAction != null);

            iExecAction.Id        = ScheduledJobTaskActionId;
            iExecAction.Path      = definition.PSExecutionPath;
            iExecAction.Arguments = definition.PSExecutionArgs;
        }
示例#27
0
        internal void FindAllJobDefinitions(Action <ScheduledJobDefinition> itemFound)
        {
            Dictionary <string, Exception> strs = ScheduledJobDefinition.RefreshRepositoryFromStore((ScheduledJobDefinition definition) => {
                if (this.ValidateJobDefinition(definition))
                {
                    itemFound(definition);
                }
            }
                                                                                                    );

            this.HandleAllLoadErrors(strs);
        }
 public override Job2 NewJob(JobInvocationInfo specification)
 {
     if (specification != null)
     {
         ScheduledJobDefinition scheduledJobDefinition = new ScheduledJobDefinition(specification, null, null, null);
         return(new ScheduledJob(specification.Command, specification.Name, scheduledJobDefinition));
     }
     else
     {
         throw new PSArgumentNullException("specification");
     }
 }
示例#29
0
        /// <summary>
        /// Process input.
        /// </summary>
        protected override void ProcessRecord()
        {
            // Validate the parameter set and write any errors.
            TriggerFrequency newTriggerFrequency = TriggerFrequency.None;

            if (!ValidateParameterSet(ref newTriggerFrequency))
            {
                return;
            }

            // Update each trigger object with the current parameter set.
            // The associated scheduled job definition will also be updated.
            foreach (ScheduledJobTrigger trigger in _triggers)
            {
                ScheduledJobTrigger originalTrigger = new ScheduledJobTrigger(trigger);
                if (!UpdateTrigger(trigger, newTriggerFrequency))
                {
                    continue;
                }

                ScheduledJobDefinition definition = trigger.JobDefinition;
                if (definition != null)
                {
                    bool jobUpdateFailed = false;

                    try
                    {
                        trigger.UpdateJobDefinition();
                    }
                    catch (ScheduledJobException e)
                    {
                        jobUpdateFailed = true;

                        string      msg         = StringUtil.Format(ScheduledJobErrorStrings.CantUpdateTriggerOnJobDef, definition.Name, trigger.Id);
                        Exception   reason      = new RuntimeException(msg, e);
                        ErrorRecord errorRecord = new ErrorRecord(reason, "CantSetPropertiesOnJobTrigger", ErrorCategory.InvalidOperation, trigger);
                        WriteError(errorRecord);
                    }

                    if (jobUpdateFailed)
                    {
                        // Restore trigger to original configuration.
                        originalTrigger.CopyTo(trigger);
                    }
                }

                if (_passThru)
                {
                    WriteObject(trigger);
                }
            }
        }
示例#30
0
        /// <summary>
        /// Makes delegate callback call for each scheduledjob definition object found.
        /// </summary>
        /// <param name="names">Scheduled job definition names</param>
        /// <param name="itemFound">Callback delegate for each discovered item.</param>
        /// <param name="writeErrorsAndWarnings">Errors/warnings are written to host</param>
        internal void FindJobDefinitionsByName(
            string[] names,
            Action <ScheduledJobDefinition> itemFound,
            bool writeErrorsAndWarnings = true)
        {
            HashSet <string> notFoundNames = new HashSet <string>(names);
            Dictionary <string, WildcardPattern> patterns = new Dictionary <string, WildcardPattern>();

            foreach (string name in names)
            {
                if (!patterns.ContainsKey(name))
                {
                    patterns.Add(name, new WildcardPattern(name, WildcardOptions.IgnoreCase));
                }
            }

            Dictionary <string, Exception> errors = ScheduledJobDefinition.RefreshRepositoryFromStore((definition) =>
            {
                foreach (var item in patterns)
                {
                    if (item.Value.IsMatch(definition.Name) &&
                        ValidateJobDefinition(definition))
                    {
                        itemFound(definition);
                        if (notFoundNames.Contains(item.Key))
                        {
                            notFoundNames.Remove(item.Key);
                        }
                    }
                }
            });

            // Look for load error.
            foreach (var error in errors)
            {
                foreach (var item in patterns)
                {
                    if (item.Value.IsMatch(error.Key))
                    {
                        HandleLoadError(error.Key, error.Value);
                    }
                }
            }

            if (writeErrorsAndWarnings)
            {
                foreach (var name in notFoundNames)
                {
                    WriteDefinitionNotFoundByNameError(name);
                }
            }
        }