예제 #1
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;
		}
		public void Add(ScheduledJobDefinition jobDef)
		{
			if (jobDef != null)
			{
				lock (this._syncObject)
				{
					if (!this._definitions.ContainsKey(jobDef.Name))
					{
						this._definitions.Add(jobDef.Name, jobDef);
					}
					else
					{
						object[] name = new object[2];
						name[0] = jobDef.Name;
						name[1] = jobDef.GlobalId;
						string str = StringUtil.Format(ScheduledJobErrorStrings.DefinitionAlreadyExistsInLocal, name);
						throw new ScheduledJobException(str);
					}
				}
				return;
			}
			else
			{
				throw new PSArgumentNullException("jobDef");
			}
		}
예제 #3
0
        /// <summary>
        /// Create a new Job2 results instance.
        /// </summary>
        /// <param name="specification">Job specification</param>
        /// <returns>Job2</returns>
        public override Job2 NewJob(JobInvocationInfo specification)
        {
            if (specification == null)
            {
                throw new PSArgumentNullException("specification");
            }

            ScheduledJobDefinition scheduledJobDef = new ScheduledJobDefinition(
                specification, null, null, null);

            return new ScheduledJob(
                specification.Command, 
                specification.Name,
                scheduledJobDef);
        }
예제 #4
0
파일: StatusInfo.cs 프로젝트: nickchal/pash
		private StatusInfo(SerializationInfo info, StreamingContext context)
		{
			if (info != null)
			{
				this._instanceId = Guid.Parse(info.GetString("Status_InstanceId"));
				this._name = info.GetString("Status_Name");
				this._location = info.GetString("Status_Location");
				this._command = info.GetString("Status_Command");
				this._statusMessage = info.GetString("Status_Message");
				this._jobState = (JobState)info.GetValue("Status_State", typeof(JobState));
				this._hasMoreData = info.GetBoolean("Status_MoreData");
				this._definition = (ScheduledJobDefinition)info.GetValue("Status_Definition", typeof(ScheduledJobDefinition));
				DateTime dateTime = info.GetDateTime("Status_StartTime");
				if (dateTime == DateTime.MinValue)
				{
					this._startTime = null;
				}
				else
				{
					this._startTime = new DateTime?(dateTime);
				}
				DateTime dateTime1 = info.GetDateTime("Status_StopTime");
				if (dateTime1 == DateTime.MinValue)
				{
					this._stopTime = null;
					return;
				}
				else
				{
					this._stopTime = new DateTime?(dateTime1);
					return;
				}
			}
			else
			{
				throw new PSArgumentNullException("info");
			}
		}
예제 #5
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);
        }
예제 #6
0
        /// <summary>
        /// Remove ScheduledJobDefinition from repository.
        /// </summary>
        /// <param name="jobDef"></param>
        public void Remove(ScheduledJobDefinition jobDef)
        {
            if (jobDef == null)
            {
                throw new PSArgumentNullException("jobDef");
            }

            lock (_syncObject)
            {
                if (_definitions.ContainsKey(jobDef.Name))
                {
                    _definitions.Remove(jobDef.Name);
                }
            }
        }
예제 #7
0
		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;
		}
		public void AddOrReplace(ScheduledJobDefinition jobDef)
		{
			if (jobDef != null)
			{
				lock (this._syncObject)
				{
					if (this._definitions.ContainsKey(jobDef.Name))
					{
						this._definitions.Remove(jobDef.Name);
					}
					this._definitions.Add(jobDef.Name, jobDef);
				}
				return;
			}
			else
			{
				throw new PSArgumentNullException("jobDef");
			}
		}
예제 #9
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;
        }
예제 #10
0
		private void WriteTriggers(ScheduledJobDefinition definition)
		{
			List<int> nums = null;
			if (definition != null)
			{
				List<ScheduledJobTrigger> triggers = definition.GetTriggers(this._triggerIds, out nums);
				foreach (ScheduledJobTrigger trigger in triggers)
				{
					base.WriteObject(trigger);
				}
				foreach (int num in nums)
				{
					base.WriteTriggerNotFoundError(num, definition.Name, definition);
				}
				return;
			}
			else
			{
				return;
			}
		}
예제 #11
0
        private ScheduledJobDefinition CreateFilePathDefinition()
        {
            JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), FilePath, _name);
            jobDefinition.ModuleName = ModuleName;
            Dictionary<string, object> parameterCollection = CreateCommonParameters();

            // FilePath, mandatory
            if (!FilePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
            {
                string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePathFile);
                Exception reason = new RuntimeException(msg);
                ErrorRecord errorRecord = new ErrorRecord(reason, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this);
                WriteError(errorRecord);

                return null;
            }
            Collection<PathInfo> pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath(FilePath);
            if (pathInfos.Count != 1)
            {
                string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePath);
                Exception reason = new RuntimeException(msg);
                ErrorRecord errorRecord = new ErrorRecord(reason, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this);
                WriteError(errorRecord);

                return null;
            }
            parameterCollection.Add(ScheduledJobInvocationInfo.FilePathParameter, pathInfos[0].Path);

            JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameterCollection);

            ScheduledJobDefinition definition = new ScheduledJobDefinition(jobInvocationInfo, Trigger, 
                ScheduledJobOption, _credential);

            return definition;
        }
예제 #12
0
        private ScheduledJobDefinition CreateScriptBlockDefinition()
        {
            JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), ScriptBlock.ToString(), _name);
            jobDefinition.ModuleName = ModuleName;
            Dictionary<string, object> parameterCollection = CreateCommonParameters();

            // ScriptBlock, mandatory
            parameterCollection.Add(ScheduledJobInvocationInfo.ScriptBlockParameter, ScriptBlock);

            JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameterCollection);

            ScheduledJobDefinition definition = new ScheduledJobDefinition(jobInvocationInfo, Trigger, 
                ScheduledJobOption, _credential);

            return definition;
        }
예제 #13
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");
			}
		}
예제 #14
0
		internal ScheduledJobTrigger(ScheduledJobTrigger copyTrigger)
		{
			this._interval = 1;
			this._enabled = true;
			if (copyTrigger != null)
			{
				this._enabled = copyTrigger.Enabled;
				this._frequency = copyTrigger.Frequency;
				this._id = copyTrigger.Id;
				this._time = copyTrigger.At;
				this._daysOfWeek = copyTrigger.DaysOfWeek;
				this._interval = copyTrigger.Interval;
				this._randomDelay = copyTrigger.RandomDelay;
				this._repInterval = copyTrigger.RepetitionInterval;
				this._repDuration = copyTrigger.RepetitionDuration;
				this._user = copyTrigger.User;
				this._jobDefAssociation = copyTrigger.JobDefinition;
				return;
			}
			else
			{
				throw new PSArgumentNullException("copyTrigger");
			}
		}
예제 #15
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");
			}
		}
예제 #16
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;
        }
예제 #17
0
        /// <summary>
        /// Copy constructor.
        /// </summary>
        /// <param name="copyTrigger">ScheduledJobTrigger</param>
        internal ScheduledJobTrigger(ScheduledJobTrigger copyTrigger)
        {
            if (copyTrigger == null)
            {
                throw new PSArgumentNullException("copyTrigger");
            }

            _enabled = copyTrigger.Enabled;
            _frequency = copyTrigger.Frequency;
            _id = copyTrigger.Id;
            _time = copyTrigger.At;
            _daysOfWeek = copyTrigger.DaysOfWeek;
            _interval = copyTrigger.Interval;
            _randomDelay = copyTrigger.RandomDelay;
            _repInterval = copyTrigger.RepetitionInterval;
            _repDuration = copyTrigger.RepetitionDuration;
            _user = copyTrigger.User;

            _jobDefAssociation = copyTrigger.JobDefinition;
        }
예제 #18
0
        /// <summary>
        /// Copy Constructor.
        /// </summary>
        /// <param name="copyOptions">Copy from</param>
        internal ScheduledJobOptions(
            ScheduledJobOptions copyOptions)
        {
            if (copyOptions == null)
            {
                throw new PSArgumentNullException("copyOptions");
            }

            _startIfOnBatteries = copyOptions.StartIfOnBatteries;
            _stopIfGoingOnBatteries = copyOptions.StopIfGoingOnBatteries;
            _wakeToRun = copyOptions.WakeToRun;
            _startIfNotIdle = copyOptions.StartIfNotIdle;
            _stopIfGoingOffIdle = copyOptions.StopIfGoingOffIdle;
            _restartOnIdleResume = copyOptions.RestartOnIdleResume;
            _idleDuration = copyOptions.IdleDuration;
            _idleTimeout = copyOptions.IdleTimeout;
            _showInTaskScheduler = copyOptions.ShowInTaskScheduler;
            _runElevated = copyOptions.RunElevated;
            _runWithoutNetwork = copyOptions.RunWithoutNetwork;
            _donotAllowDemandStart = copyOptions.DoNotAllowDemandStart;
            _multipleInstancePolicy = copyOptions.MultipleInstancePolicy;

            _jobDefAssociation = copyOptions.JobDefinition;
        }
예제 #19
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;
        }
예제 #20
0
		private bool ValidateJobDefinition(ScheduledJobDefinition definition)
		{
			Exception exception = null;
			try
			{
				definition.SyncWithWTS();
			}
			catch (DirectoryNotFoundException directoryNotFoundException1)
			{
				DirectoryNotFoundException directoryNotFoundException = directoryNotFoundException1;
				exception = directoryNotFoundException;
			}
			catch (FileNotFoundException fileNotFoundException1)
			{
				FileNotFoundException fileNotFoundException = fileNotFoundException1;
				exception = fileNotFoundException;
			}
			catch (ArgumentNullException argumentNullException1)
			{
				ArgumentNullException argumentNullException = argumentNullException1;
				exception = argumentNullException;
			}
			if (exception != null)
			{
				this.WriteErrorLoadingDefinition(definition.Name, exception);
			}
			return exception == null;
		}
예제 #21
0
		private ScheduledJobDefinition CreateFilePathDefinition()
		{
			JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), this.FilePath, this._name);
			jobDefinition.ModuleName = "PSScheduledJob";
			Dictionary<string, object> strs = this.CreateCommonParameters();
			if (this.FilePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
			{
				Collection<PathInfo> resolvedPSPathFromPSPath = base.SessionState.Path.GetResolvedPSPathFromPSPath(this.FilePath);
				if (resolvedPSPathFromPSPath.Count == 1)
				{
					strs.Add("FilePath", resolvedPSPathFromPSPath[0].Path);
					JobInvocationInfo scheduledJobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, strs);
					ScheduledJobDefinition scheduledJobDefinition = new ScheduledJobDefinition(scheduledJobInvocationInfo, this.Trigger, this.ScheduledJobOption, this._credential);
					return scheduledJobDefinition;
				}
				else
				{
					string str = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePath, new object[0]);
					Exception runtimeException = new RuntimeException(str);
					ErrorRecord errorRecord = new ErrorRecord(runtimeException, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this);
					base.WriteError(errorRecord);
					return null;
				}
			}
			else
			{
				string str1 = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePathFile, new object[0]);
				Exception exception = new RuntimeException(str1);
				ErrorRecord errorRecord1 = new ErrorRecord(exception, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this);
				base.WriteError(errorRecord1);
				return null;
			}
		}
예제 #22
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);
            }
        }
예제 #23
0
        /// <summary>
        /// Add ScheduledJobDefinition to repository.
        /// </summary>
        /// <param name="jobDef"></param>
        public void Add(ScheduledJobDefinition jobDef)
        {
            if (jobDef == null)
            {
                throw new PSArgumentNullException("jobDef");
            }

            lock (_syncObject)
            {
                if (_definitions.ContainsKey(jobDef.Name))
                {
                    string msg = StringUtil.Format(ScheduledJobErrorStrings.DefinitionAlreadyExistsInLocal, jobDef.Name, jobDef.GlobalId);
                    throw new ScheduledJobException(msg);
                }
                _definitions.Add(jobDef.Name, jobDef);
            }
        }
예제 #24
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);
        }
예제 #25
0
        /// <summary>
        /// Creates a Once job trigger with provided repetition interval and an
        /// infinite duration, and adds the trigger to the provided scheduled job
        /// definition object.
        /// </summary>
        /// <param name="definition">ScheduledJobDefinition</param>
        /// <param name="repInterval">rep interval</param>
        /// <param name="save">save definition change</param>
        internal static void AddRepetitionJobTriggerToDefinition(
            ScheduledJobDefinition definition,
            TimeSpan repInterval,
            bool save)
        {
            if (definition == null)
            {
                throw new PSArgumentNullException("definition");
            }

            TimeSpan repDuration = TimeSpan.MaxValue;

            // Validate every interval value.
            if (repInterval < TimeSpan.Zero || repDuration < TimeSpan.Zero)
            {
                throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParamValues);
            }
            if (repInterval < TimeSpan.FromMinutes(1))
            {
                throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionIntervalValue);
            }
            if (repInterval > repDuration)
            {
                throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionInterval);
            }

            // Create job trigger.
            var trigger = ScheduledJobTrigger.CreateOnceTrigger(
                DateTime.Now,
                TimeSpan.Zero,
                repInterval,
                repDuration,
                0,
                true);

            definition.AddTriggers(new ScheduledJobTrigger[] { trigger }, save);
        }
예제 #26
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);
        }
예제 #27
0
파일: StatusInfo.cs 프로젝트: nickchal/pash
		internal StatusInfo(Guid instanceId, string name, string location, string command, string statusMessage, JobState jobState, bool hasMoreData, DateTime? startTime, DateTime? stopTime, ScheduledJobDefinition definition)
		{
			if (definition != null)
			{
				this._instanceId = instanceId;
				this._name = name;
				this._location = location;
				this._command = command;
				this._statusMessage = statusMessage;
				this._jobState = jobState;
				this._hasMoreData = hasMoreData;
				this._startTime = startTime;
				this._stopTime = stopTime;
				this._definition = definition;
				return;
			}
			else
			{
				throw new PSArgumentNullException("definition");
			}
		}
예제 #28
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);
            }
        }
예제 #29
0
        private void WriteTriggers(ScheduledJobDefinition definition)
        {
            if (definition == null)
            {
                return;
            }

            List<Int32> notFoundIds;
            List<ScheduledJobTrigger> triggers = definition.GetTriggers(_triggerIds, out notFoundIds);

            // Write found trigger objects.
            foreach (ScheduledJobTrigger trigger in triggers)
            {
                WriteObject(trigger);
            }

            // Report any triggers that were not found.
            foreach (Int32 notFoundId in notFoundIds)
            {
                WriteTriggerNotFoundError(notFoundId, definition.Name, definition);
            }
        }
예제 #30
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");
			}
		}