コード例 #1
0
        protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception failureException, out ErrorRecord failureErrorRecord)
        {
            RemotePipeline pipeline = helper.Pipeline as RemotePipeline;
            RemoteRunspace runspace = pipeline.GetRunspace() as RemoteRunspace;

            failureException   = null;
            failureErrorRecord = null;
            if (helper.InternalException != null)
            {
                string errorId = "RemotePipelineExecutionFailed";
                failureException = helper.InternalException;
                if ((failureException is InvalidRunspaceStateException) || (failureException is InvalidRunspacePoolStateException))
                {
                    errorId = "InvalidSessionState";
                    if (!string.IsNullOrEmpty(failureException.Source))
                    {
                        errorId = string.Format(CultureInfo.InvariantCulture, "{0},{1}", new object[] { errorId, failureException.Source });
                    }
                }
                failureErrorRecord = new ErrorRecord(helper.InternalException, errorId, ErrorCategory.OperationStopped, helper);
            }
            else if (runspace.RunspaceStateInfo.State == RunspaceState.Broken)
            {
                failureException = runspace.RunspaceStateInfo.Reason;
                object computerName = runspace.ConnectionInfo.ComputerName;
                string str2         = null;
                PSRemotingTransportException exception = failureException as PSRemotingTransportException;
                string fQEIDFromTransportError         = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception != null) ? exception.ErrorCode : 0, "PSSessionStateBroken");
                if (exception != null)
                {
                    str2 = "[" + runspace.ConnectionInfo.ComputerName + "] ";
                    if (exception.ErrorCode == -2144108135)
                    {
                        string str4 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" });
                        str2 = str2 + str4;
                    }
                    else if (!string.IsNullOrEmpty(exception.Message))
                    {
                        str2 = str2 + exception.Message;
                    }
                    else if (!string.IsNullOrEmpty(exception.TransportMessage))
                    {
                        str2 = str2 + exception.TransportMessage;
                    }
                }
                if (failureException == null)
                {
                    failureException = new RuntimeException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { runspace.RunspaceStateInfo.State }));
                }
                failureErrorRecord = new ErrorRecord(failureException, computerName, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str2, null);
            }
            else if (pipeline.PipelineStateInfo.State == PipelineState.Failed)
            {
                object targetObject = runspace.ConnectionInfo.ComputerName;
                failureException = pipeline.PipelineStateInfo.Reason;
                if (failureException != null)
                {
                    RemoteException exception2  = failureException as RemoteException;
                    ErrorRecord     errorRecord = null;
                    if (exception2 != null)
                    {
                        errorRecord = exception2.ErrorRecord;
                    }
                    else
                    {
                        errorRecord = new ErrorRecord(pipeline.PipelineStateInfo.Reason, "JobFailure", ErrorCategory.OperationStopped, targetObject);
                    }
                    string     str5       = ((RemoteRunspace)pipeline.GetRunspace()).ConnectionInfo.ComputerName;
                    Guid       instanceId = pipeline.GetRunspace().InstanceId;
                    OriginInfo originInfo = new OriginInfo(str5, instanceId);
                    failureErrorRecord = new RemotingErrorRecord(errorRecord, originInfo);
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Remove a job from the appropriate store.
        /// </summary>
        /// <param name="job">Job object to remove.</param>
        /// <param name="cmdlet"></param>
        /// <param name="writeErrorOnException"></param>
        /// <param name="throwExceptions">If true, will throw all JobSourceAdapter exceptions to caller.
        /// This is needed if RemoveJob is being called from an event handler in Receive-Job.</param>
        /// <returns>True if job is found.</returns>
        internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, bool throwExceptions = false)
        {
            bool jobFound = false;

            lock (_syncObject)
            {
                foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values)
                {
                    Job2 foundJob = null;
#pragma warning disable 56500
                    try
                    {
                        foundJob = sourceAdapter.GetJobByInstanceId(job.InstanceId, true);
                    }
                    catch (Exception exception)
                    {
                        // Since we are calling into 3rd party code
                        // catching Exception is allowed. In all
                        // other cases the appropriate exception
                        // needs to be caught.

                        // sourceAdapter.GetJobByInstanceId() threw unknown exception.
                        _tracer.TraceException(exception);
                        if (throwExceptions)
                        {
                            throw;
                        }
                        WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", sourceAdapter);
                    }
#pragma warning restore 56500

                    if (foundJob == null)
                    {
                        continue;
                    }
                    jobFound = true;
                    RemoveJobIdForReuse(foundJob);

#pragma warning disable 56500
                    try
                    {
                        sourceAdapter.RemoveJob(job);
                    }
                    catch (Exception exception)
                    {
                        // Since we are calling into 3rd party code
                        // catching Exception is allowed. In all
                        // other cases the appropriate exception
                        // needs to be caught.
                        // sourceAdapter.RemoveJob() threw unknown exception.

                        _tracer.TraceException(exception);
                        if (throwExceptions)
                        {
                            throw;
                        }
                        WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterRemoveJobError", sourceAdapter);
                    }
#pragma warning restore 56500
                }
            }

            if (!jobFound && throwExceptions)
            {
                var message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository,
                                                                             "Job repository", job.InstanceId.ToString());
                throw new ArgumentException(message);
            }

            return(jobFound);
        }
コード例 #3
0
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> collection = null;
            string parameterSetName = base.ParameterSetName;

            if (parameterSetName != null)
            {
                if (!(parameterSetName == "NameParameterSet"))
                {
                    if (parameterSetName == "InstanceIdParameterSet")
                    {
                        collection = base.FindJobsMatchingByInstanceId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "SessionIdParameterSet")
                    {
                        collection = base.FindJobsMatchingBySessionId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "StateParameterSet")
                    {
                        collection = base.FindJobsMatchingByState(false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "FilterParameterSet")
                    {
                        collection = base.FindJobsMatchingByFilter(false);
                        goto Label_00A2;
                    }
                }
                else
                {
                    collection = base.FindJobsMatchingByName(true, false, true, false);
                    goto Label_00A2;
                }
            }
            collection = base.CopyJobsToList(this.jobs, false, false);
Label_00A2:
            this._allJobsToSuspend.AddRange(collection);
            foreach (System.Management.Automation.Job job in collection)
            {
                Job2 key = job as Job2;
                if (key == null)
                {
                    base.WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException("RemotingErrorIdStrings", "JobSuspendNotSupported", new object[] { job.Id }), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, job));
                }
                else
                {
                    string target = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, new object[] { job.Command, job.Id });
                    if (base.ShouldProcess(target, "Suspend"))
                    {
                        if (this._wait)
                        {
                            this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleSuspendJobCompleted));
                        }
                        else
                        {
                            if (key.IsFinishedState(key.JobStateInfo.State) || (key.JobStateInfo.State == JobState.Stopping))
                            {
                                this._warnInvalidState = true;
                                goto Label_0277;
                            }
                            if ((key.JobStateInfo.State == JobState.Suspending) || (key.JobStateInfo.State == JobState.Suspended))
                            {
                                goto Label_0277;
                            }
                            key.StateChanged += new EventHandler <JobStateEventArgs>(this.noWait_Job2_StateChanged);
                        }
                        key.SuspendJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleSuspendJobCompleted);
                        lock (this._syncObject)
                        {
                            if (!this._pendingJobs.Contains(key.InstanceId))
                            {
                                this._pendingJobs.Add(key.InstanceId);
                            }
                        }
                        if (!this._wait && ((key.IsFinishedState(key.JobStateInfo.State) || (key.JobStateInfo.State == JobState.Suspending)) || (key.JobStateInfo.State == JobState.Suspended)))
                        {
                            this.ProcessExecutionErrorsAndReleaseWaitHandle(key);
                        }
                        key.SuspendJobAsync(this.force, RemotingErrorIdStrings.ForceSuspendJob);
                    }
                    Label_0277 :;
                }
            }
        }
コード例 #4
0
ファイル: SuspendJob.cs プロジェクト: x1m0/PowerShell
        /// <summary>
        /// Suspend the Job.
        /// </summary>
        protected override void ProcessRecord()
        {
            //List of jobs to suspend
            List <Job> jobsToSuspend = null;

            switch (ParameterSetName)
            {
            case NameParameterSet:
            {
                jobsToSuspend = FindJobsMatchingByName(true, false, true, false);
            }
            break;

            case InstanceIdParameterSet:
            {
                jobsToSuspend = FindJobsMatchingByInstanceId(true, false, true, false);
            }
            break;

            case SessionIdParameterSet:
            {
                jobsToSuspend = FindJobsMatchingBySessionId(true, false, true, false);
            }
            break;

            case StateParameterSet:
            {
                jobsToSuspend = FindJobsMatchingByState(false);
            }
            break;

            case FilterParameterSet:
            {
                jobsToSuspend = FindJobsMatchingByFilter(false);
            }
            break;

            default:
            {
                jobsToSuspend = CopyJobsToList(_jobs, false, false);
            }
            break;
            }

            _allJobsToSuspend.AddRange(jobsToSuspend);

            foreach (Job job in jobsToSuspend)
            {
                var job2 = job as Job2;

                // If the job is not Job2, the suspend operation is not supported.
                if (job2 == null)
                {
                    WriteError(
                        new ErrorRecord(
                            PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobSuspendNotSupported, job.Id),
                            "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job));
                    continue;
                }

                string targetString =
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget,
                                                                   job.Command, job.Id);
                if (ShouldProcess(targetString, VerbsLifecycle.Suspend))
                {
                    if (_wait)
                    {
                        _cleanUpActions.Add(job2, HandleSuspendJobCompleted);
                    }
                    else
                    {
                        if (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Stopping)
                        {
                            _warnInvalidState = true;
                            continue;
                        }

                        if (job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended)
                        {
                            continue;
                        }

                        job2.StateChanged += noWait_Job2_StateChanged;
                    }

                    job2.SuspendJobCompleted += HandleSuspendJobCompleted;

                    lock (_syncObject)
                    {
                        if (!_pendingJobs.Contains(job2.InstanceId))
                        {
                            _pendingJobs.Add(job2.InstanceId);
                        }
                    }

                    // there could be possiblility that the job gets completed befor or after the
                    // subscribing to nowait_job2_statechanged event so checking it again.
                    if (!_wait && (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended))
                    {
                        this.ProcessExecutionErrorsAndReleaseWaitHandle(job2);
                    }

                    job2.SuspendJobAsync(_force, RemotingErrorIdStrings.ForceSuspendJob);
                }
            }
        }
コード例 #5
0
        private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs)
        {
            ErrorRecord errorRecord;
            PSRemotingTransportException exception2;
            string str;

            if (sender == null)
            {
                throw PSTraceSource.NewArgumentNullException("sender");
            }
            if (stateEventArgs == null)
            {
                throw PSTraceSource.NewArgumentNullException("stateEventArgs");
            }
            RunspaceStateEventArgs baseEvent        = stateEventArgs.BaseEvent as RunspaceStateEventArgs;
            RunspaceState          state            = baseEvent.RunspaceStateInfo.State;
            OpenRunspaceOperation  operation        = sender as OpenRunspaceOperation;
            RemoteRunspace         operatedRunspace = operation.OperatedRunspace;

            if (operatedRunspace != null)
            {
                operatedRunspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
            }
            PipelineWriter objectWriter = this.stream.ObjectWriter;
            Exception      reason       = baseEvent.RunspaceStateInfo.Reason;

            switch (state)
            {
            case RunspaceState.Opened:
            {
                PSSession remoteRunspaceInfo = new PSSession(operatedRunspace);
                base.RunspaceRepository.Add(remoteRunspaceInfo);
                Action <Cmdlet> action = cmdlet => cmdlet.WriteObject(remoteRunspaceInfo);
                if (objectWriter.IsOpen)
                {
                    objectWriter.Write(action);
                }
                return;
            }

            case RunspaceState.Closed:
            {
                Uri             uri     = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(operatedRunspace.ConnectionInfo, "ConnectionUri", null);
                string          message = base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, new object[] { (uri != null) ? uri.AbsoluteUri : string.Empty });
                Action <Cmdlet> action3 = cmdlet => cmdlet.WriteVerbose(message);
                if (objectWriter.IsOpen)
                {
                    objectWriter.Write(action3);
                }
                if (reason != null)
                {
                    ErrorRecord     errorRecord2 = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, operatedRunspace);
                    Action <Cmdlet> action4      = cmdlet => cmdlet.WriteError(errorRecord2);
                    if (objectWriter.IsOpen)
                    {
                        objectWriter.Write(action4);
                    }
                }
                return;
            }

            case RunspaceState.Closing:
                return;

            case RunspaceState.Broken:
                exception2 = reason as PSRemotingTransportException;
                str        = null;
                if (exception2 != null)
                {
                    OpenRunspaceOperation operation2 = sender as OpenRunspaceOperation;
                    if (operation2 != null)
                    {
                        string computerName = operation2.OperatedRunspace.ConnectionInfo.ComputerName;
                        if (exception2.ErrorCode != -2144108135)
                        {
                            str = "[" + computerName + "] ";
                            if (!string.IsNullOrEmpty(exception2.Message))
                            {
                                str = str + exception2.Message;
                            }
                            else if (!string.IsNullOrEmpty(exception2.TransportMessage))
                            {
                                str = str + exception2.TransportMessage;
                            }
                            break;
                        }
                        string str3 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" });
                        str = "[" + computerName + "] " + str3;
                    }
                }
                break;

            default:
                return;
            }
            PSRemotingDataStructureException exception3 = reason as PSRemotingDataStructureException;

            if (exception3 != null)
            {
                OpenRunspaceOperation operation3 = sender as OpenRunspaceOperation;
                if (operation3 != null)
                {
                    string str4 = operation3.OperatedRunspace.ConnectionInfo.ComputerName;
                    str = "[" + str4 + "] " + exception3.Message;
                }
            }
            if (reason == null)
            {
                reason = new RuntimeException(base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { state }));
            }
            string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception2 != null) ? exception2.ErrorCode : 0, this._defaultFQEID);

            errorRecord = new ErrorRecord(reason, operatedRunspace, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str, null);
            Action <Cmdlet> action2 = cmdlet => cmdlet.WriteError(errorRecord);

            if (objectWriter.IsOpen)
            {
                objectWriter.Write(action2);
            }
            this.toDispose.Add(operatedRunspace);
        }
コード例 #6
0
        /// <summary>
        /// Stop the Job.
        /// </summary>
        protected override void ProcessRecord()
        {
            //List of jobs to stop
            List <Job> jobsToStop = null;

            switch (ParameterSetName)
            {
            case NameParameterSet:
            {
                jobsToStop = FindJobsMatchingByName(true, false, true, false);
            }
            break;

            case InstanceIdParameterSet:
            {
                jobsToStop = FindJobsMatchingByInstanceId(true, false, true, false);
            }
            break;

            case SessionIdParameterSet:
            {
                jobsToStop = FindJobsMatchingBySessionId(true, false, true, false);
            }
            break;

            case StateParameterSet:
            {
                jobsToStop = FindJobsMatchingByState(false);
            }
            break;

            case FilterParameterSet:
            {
                jobsToStop = FindJobsMatchingByFilter(false);
            }
            break;

            default:
            {
                jobsToStop = CopyJobsToList(_jobs, false, false);
            }
            break;
            }

            _allJobsToStop.AddRange(jobsToStop);

            foreach (Job job in jobsToStop)
            {
                if (this.Stopping)
                {
                    return;
                }
                if (job.IsFinishedState(job.JobStateInfo.State))
                {
                    continue;
                }
                string targetString =
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget,
                                                                   job.Command, job.Id);
                if (ShouldProcess(targetString, VerbsLifecycle.Stop))
                {
                    Job2 job2 = job as Job2;
                    // if it is a Job2, then async is supported
                    // stop the job asynchronously
                    if (job2 != null)
                    {
                        _cleanUpActions.Add(job2, HandleStopJobCompleted);
                        job2.StopJobCompleted += HandleStopJobCompleted;

                        lock (_syncObject)
                        {
                            if (!job2.IsFinishedState(job2.JobStateInfo.State) &&
                                !_pendingJobs.Contains(job2.InstanceId))
                            {
                                _pendingJobs.Add(job2.InstanceId);
                            }
                        }

                        job2.StopJobAsync();
                    }
                    else
                    {
                        job.StopJob();
                    }
                }
            }
        }
コード例 #7
0
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            this._syncObject = new object();
            string pSExePath = PSExePath;

            if (useWow64)
            {
                string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
                if (!string.IsNullOrEmpty(environmentVariable) && (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    pSExePath = PSExePath.ToLowerInvariant().Replace(@"\system32\", @"\syswow64\");
                    if (!System.IO.File.Exists(pSExePath))
                    {
                        throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.IPCWowComponentNotPresent, new object[] { pSExePath }));
                    }
                }
            }
            string  str4    = string.Empty;
            Version version = powerShellVersion ?? PSVersionInfo.PSVersion;

            if (null == version)
            {
                version = new Version(3, 0);
            }
            str4 = string.Format(CultureInfo.InvariantCulture, "-Version {0}", new object[] { new Version(version.Major, version.Minor) });
            str4 = string.Format(CultureInfo.InvariantCulture, "{0} -s -NoLogo -NoProfile", new object[] { str4 });
            if (initializationScript != null)
            {
                string str5 = initializationScript.ToString();
                if (!string.IsNullOrEmpty(str5))
                {
                    string str6 = Convert.ToBase64String(Encoding.Unicode.GetBytes(str5));
                    str4 = string.Format(CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", new object[] { str4, str6 });
                }
            }
            ProcessStartInfo info = new ProcessStartInfo {
                FileName               = useWow64 ? pSExePath : PSExePath,
                Arguments              = str4,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                WindowStyle            = ProcessWindowStyle.Hidden,
                CreateNoWindow         = true,
                LoadUserProfile        = true
            };

            this._startInfo = info;
            if (credential != null)
            {
                NetworkCredential networkCredential = credential.GetNetworkCredential();
                this._startInfo.UserName = networkCredential.UserName;
                this._startInfo.Domain   = string.IsNullOrEmpty(networkCredential.Domain) ? "." : networkCredential.Domain;
                this._startInfo.Password = credential.Password;
            }
            System.Diagnostics.Process process = new System.Diagnostics.Process {
                StartInfo           = this._startInfo,
                EnableRaisingEvents = true
            };
            this._process = process;
        }
コード例 #8
0
 public InvalidJobStateException(JobState currentState, string actionMessage) : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidJobStateSpecific, new object[] { currentState, actionMessage }))
 {
     this.currState = currentState;
 }
コード例 #9
0
ファイル: StopJobCommand.cs プロジェクト: modulexcite/pash-1
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> collection = null;
            string parameterSetName = base.ParameterSetName;

            if (parameterSetName != null)
            {
                if (!(parameterSetName == "NameParameterSet"))
                {
                    if (parameterSetName == "InstanceIdParameterSet")
                    {
                        collection = base.FindJobsMatchingByInstanceId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "SessionIdParameterSet")
                    {
                        collection = base.FindJobsMatchingBySessionId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "StateParameterSet")
                    {
                        collection = base.FindJobsMatchingByState(false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "FilterParameterSet")
                    {
                        collection = base.FindJobsMatchingByFilter(false);
                        goto Label_00A2;
                    }
                }
                else
                {
                    collection = base.FindJobsMatchingByName(true, false, true, false);
                    goto Label_00A2;
                }
            }
            collection = base.CopyJobsToList(this.jobs, false, false);
Label_00A2:
            this._allJobsToStop.AddRange(collection);
            foreach (System.Management.Automation.Job job in collection)
            {
                if (base.Stopping)
                {
                    break;
                }
                if (!job.IsFinishedState(job.JobStateInfo.State))
                {
                    string target = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, new object[] { job.Command, job.Id });
                    if (base.ShouldProcess(target, "Stop"))
                    {
                        Job2 key = job as Job2;
                        if (key != null)
                        {
                            this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted));
                            key.StopJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted);
                            lock (this._syncObject)
                            {
                                if (!key.IsFinishedState(key.JobStateInfo.State) && !this._pendingJobs.Contains(key.InstanceId))
                                {
                                    this._pendingJobs.Add(key.InstanceId);
                                }
                            }
                            key.StopJobAsync();
                        }
                        else
                        {
                            job.StopJob();
                            ContainerParentJob job3 = job as ContainerParentJob;
                            if ((job3 != null) && (job3.ExecutionError.Count > 0))
                            {
                                foreach (ErrorRecord record in from e in job3.ExecutionError
                                         where e.FullyQualifiedErrorId == "ContainerParentJobStopError"
                                         select e)
                                {
                                    base.WriteError(record);
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #10
0
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> collection = null;
            string parameterSetName = base.ParameterSetName;

            if (parameterSetName != null)
            {
                if (!(parameterSetName == "NameParameterSet"))
                {
                    if (parameterSetName == "InstanceIdParameterSet")
                    {
                        collection = base.FindJobsMatchingByInstanceId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "SessionIdParameterSet")
                    {
                        collection = base.FindJobsMatchingBySessionId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "StateParameterSet")
                    {
                        collection = base.FindJobsMatchingByState(false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "FilterParameterSet")
                    {
                        collection = base.FindJobsMatchingByFilter(false);
                        goto Label_00A2;
                    }
                }
                else
                {
                    collection = base.FindJobsMatchingByName(true, false, true, false);
                    goto Label_00A2;
                }
            }
            collection = base.CopyJobsToList(this.jobs, false, false);
Label_00A2:
            this._allJobsToResume.AddRange(collection);
            foreach (System.Management.Automation.Job job in collection)
            {
                Job2 key = job as Job2;
                if (key == null)
                {
                    base.WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException("RemotingErrorIdStrings", "JobResumeNotSupported", new object[] { job.Id }), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, job));
                }
                else
                {
                    string target = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, new object[] { job.Command, job.Id });
                    if (base.ShouldProcess(target, "Resume"))
                    {
                        this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleResumeJobCompleted));
                        key.ResumeJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleResumeJobCompleted);
                        lock (this._syncObject)
                        {
                            if (!this._pendingJobs.Contains(key.InstanceId))
                            {
                                this._pendingJobs.Add(key.InstanceId);
                            }
                        }
                        key.ResumeJobAsync();
                    }
                }
            }
        }
コード例 #11
0
 internal static Exception NewRemoteHostCallFailedException(RemoteHostMethodId methodId) => (Exception) new PSRemotingDataStructureException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.RemoteHostCallFailed, (object)RemoteHostMethodInfo.LookUp(methodId).Name));
コード例 #12
0
 internal static Exception NewDecodingFailedException() => (Exception) new PSRemotingDataStructureException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.RemoteHostDecodingFailed));
コード例 #13
0
 internal static Exception NewRemoteRunspaceDoesNotSupportPushRunspaceException() => (Exception) new PSRemotingDataStructureException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.RemoteRunspaceDoesNotSupportPushRunspace));
コード例 #14
0
 public InvalidJobStateException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidJobStateGeneral, new object[0]))
 {
 }
コード例 #15
0
 public InvalidJobStateException()
     : base(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.InvalidJobStateGeneral))
 {
 }
コード例 #16
0
 internal InvalidJobStateException(JobState currentState) : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidJobStateGeneral, new object[0]))
 {
     this.currState = currentState;
 }
コード例 #17
0
 internal InvalidJobStateException(JobState currentState)
     : base(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.InvalidJobStateGeneral))
 {
     using (InvalidJobStateException.tracer.TraceConstructor((object)this))
         this.currState = currentState;
 }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PowerShellProcessInstance"/> class. Initializes the underlying dotnet process class.
        /// </summary>
        /// <param name="powerShellVersion">Specifies the version of powershell.</param>
        /// <param name="credential">Specifies a user account credentials.</param>
        /// <param name="initializationScript">Specifies a script that will be executed when the powershell process is initialized.</param>
        /// <param name="useWow64">Specifies if the powershell process will be 32-bit.</param>
        /// <param name="workingDirectory">Specifies the initial working directory for the new powershell process.</param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64, string workingDirectory)
        {
            string exePath = PwshExePath;
            bool   startingWindowsPowerShell51 = false;

#if !UNIX
            // if requested PS version was "5.1" then we start Windows PS instead of PS Core
            startingWindowsPowerShell51 = (powerShellVersion != null) && (powerShellVersion.Major == 5) && (powerShellVersion.Minor == 1);
            if (startingWindowsPowerShell51)
            {
                if (WinPwshExePath is null)
                {
                    throw new PSInvalidOperationException(RemotingErrorIdStrings.WindowsPowerShellNotPresent);
                }

                exePath = WinPwshExePath;

                if (useWow64)
                {
                    string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                    if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                              procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                    {
                        exePath = WinPwshExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                        if (!File.Exists(exePath))
                        {
                            string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WowComponentNotPresent, exePath);
                            throw new PSInvalidOperationException(message);
                        }
                    }
                }
            }
#endif
            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = exePath,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
#if !UNIX
                LoadUserProfile = true,
#endif
            };
#if !UNIX
            if (startingWindowsPowerShell51)
            {
                _startInfo.ArgumentList.Add("-Version");
                _startInfo.ArgumentList.Add("5.1");

                // if starting Windows PowerShell, need to remove PowerShell specific segments of PSModulePath
                _startInfo.Environment["PSModulePath"] = ModuleIntrinsics.GetWindowsPowerShellModulePath();
            }
#endif
            _startInfo.ArgumentList.Add("-s");
            _startInfo.ArgumentList.Add("-NoLogo");
            _startInfo.ArgumentList.Add("-NoProfile");

            if (!string.IsNullOrWhiteSpace(workingDirectory) && !startingWindowsPowerShell51)
            {
                _startInfo.ArgumentList.Add("-wd");
                _startInfo.ArgumentList.Add(workingDirectory);
            }

            if (initializationScript != null)
            {
                var scriptBlockString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scriptBlockString))
                {
                    var encodedCommand = Convert.ToBase64String(Encoding.Unicode.GetBytes(scriptBlockString));
                    _startInfo.ArgumentList.Add("-EncodedCommand");
                    _startInfo.ArgumentList.Add(encodedCommand);
                }
            }

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
                _startInfo.Password = credential.Password;
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
コード例 #19
0
        internal override void ConnectAsync()
        {
            string path = Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), "powershell.exe");

            if (this.connectionInfo != null && this.connectionInfo.RunAs32)
            {
                string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
                if (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase))
                {
                    path = path.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");
                    if (!System.IO.File.Exists(path))
                    {
                        throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.IPCWowComponentNotPresent, (object)path));
                    }
                }
            }
            string str = string.Format((IFormatProvider)CultureInfo.InvariantCulture, "-s -NoLogo -NoProfile");

            if (this.connectionInfo.InitializationScript != null && !string.IsNullOrEmpty(this.connectionInfo.InitializationScript.ToString()))
            {
                string base64String = Convert.ToBase64String(Encoding.Unicode.GetBytes(this.connectionInfo.InitializationScript.ToString()));
                str = string.Format((IFormatProvider)CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", (object)str, (object)base64String);
            }
            ProcessStartInfo processStartInfo = new ProcessStartInfo();

            processStartInfo.FileName               = path;
            processStartInfo.Arguments              = str;
            processStartInfo.UseShellExecute        = false;
            processStartInfo.RedirectStandardInput  = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError  = true;
            processStartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            processStartInfo.CreateNoWindow         = true;
            processStartInfo.LoadUserProfile        = true;
            if (this.connectionInfo.Credential != null)
            {
                NetworkCredential networkCredential = this.connectionInfo.Credential.GetNetworkCredential();
                processStartInfo.UserName = networkCredential.UserName;
                processStartInfo.Domain   = !string.IsNullOrEmpty(networkCredential.Domain) ? networkCredential.Domain : ".";
                processStartInfo.Password = this.connectionInfo.Credential.Password;
            }
            BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManCreateShell, PSOpcode.Connect, PSTask.CreateRunspace, (object)this.RunspacePoolInstanceId);
            try
            {
                lock (this.syncObject)
                {
                    if (this.isClosed)
                    {
                        return;
                    }
                    this.serverProcess                     = new Process();
                    this.serverProcess.StartInfo           = processStartInfo;
                    this.serverProcess.EnableRaisingEvents = true;
                    this.serverProcess.OutputDataReceived += new DataReceivedEventHandler(this.OnOutputDataReceived);
                    this.serverProcess.ErrorDataReceived  += new DataReceivedEventHandler(this.OnErrorDataReceived);
                    this.serverProcess.Exited             += new EventHandler(this.OnExited);
                    this.serverProcess.Start();
                    this.serverProcess.BeginOutputReadLine();
                    this.serverProcess.BeginErrorReadLine();
                    this.stdInWriter = new OutOfProcessTextWriter((TextWriter)this.serverProcess.StandardInput);
                }
            }
            catch (Win32Exception ex)
            {
                this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, new object[1]
                {
                    (object)ex.Message
                })
                {
                    ErrorCode = ex.ErrorCode
                }, TransportMethodEnum.CreateShellEx));
                return;
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, new object[1]
                {
                    (object)ex.Message
                }), TransportMethodEnum.CreateShellEx));
                return;
            }
            this.SendOneItem();
        }
コード例 #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = s_PSExePath;

            if (useWow64)
            {
                string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                          procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    psWow64Path = s_PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                    if (!File.Exists(psWow64Path))
                    {
                        string message =
                            PSRemotingErrorInvariants.FormatResourceString(
                                RemotingErrorIdStrings.IPCWowComponentNotPresent,
                                psWow64Path);
                        throw new PSInvalidOperationException(message);
                    }
                }
            }

            string processArguments = string.Empty;
            // Adding Version parameter to powershell.exe
            // Version parameter needs to go before all other parameters because the native layer looks for Version or
            // PSConsoleFile parameters before parsing other parameters.
            // The other parameters get parsed in the managed layer.
            Version tempVersion = powerShellVersion ?? PSVersionInfo.PSVersion;

            processArguments = string.Format(CultureInfo.InvariantCulture,
                                             "-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));

            processArguments = string.Format(CultureInfo.InvariantCulture,
                                             "{0} -s -NoLogo -NoProfile", processArguments);

            if (initializationScript != null)
            {
                string scripBlockAsString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scripBlockAsString))
                {
                    string encodedCommand =
                        Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
                    processArguments = string.Format(CultureInfo.InvariantCulture,
                                                     "{0} -EncodedCommand {1}", processArguments, encodedCommand);
                }
            }

            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = useWow64 ? psWow64Path : s_PSExePath,
                Arguments              = processArguments,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
                LoadUserProfile        = true,
            };

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
#if CORECLR
                _startInfo.PasswordInClearText = ClrFacade.ConvertSecureStringToString(credential.Password);
#else
                _startInfo.Password = credential.Password;
#endif
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
コード例 #21
0
        protected override void ProcessRecord()
        {
            IHostSupportsInteractiveSession session = base.Host as IHostSupportsInteractiveSession;

            if (session == null)
            {
                base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(), ErrorCategory.InvalidArgument, null));
            }

            /*
             * else if (((base.Context != null) && (base.Context.EngineHostInterface != null)) && ((base.Context.EngineHostInterface.ExternalHost != null) && (base.Context.EngineHostInterface.ExternalHost is ServerRemoteHost)))
             * {
             * base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.RemoteHostDoesNotSupportPushRunspace)), PSRemotingErrorId.RemoteHostDoesNotSupportPushRunspace.ToString(), ErrorCategory.InvalidArgument, null));
             * }
             */
            else
            {
                InternalHost targetObject = base.Host as InternalHost;
                if ((targetObject != null) && targetObject.HostInNestedPrompt())
                {
                    base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HostInNestedPrompt, new object[0])), "HostInNestedPrompt", ErrorCategory.InvalidOperation, targetObject));
                }
                RemoteRunspace runspaceMatchingRunspaceId = null;
                string         parameterSetName           = base.ParameterSetName;
                if (parameterSetName != null)
                {
                    if (!(parameterSetName == "ComputerName"))
                    {
                        if (parameterSetName == "Uri")
                        {
                            runspaceMatchingRunspaceId = this.CreateRunspaceWhenUriParameterSpecified();
                        }
                        else if (parameterSetName == "Session")
                        {
                            runspaceMatchingRunspaceId = (RemoteRunspace)this.remoteRunspaceInfo.Runspace;
                        }
                        else if (parameterSetName == "InstanceId")
                        {
                            runspaceMatchingRunspaceId = this.GetRunspaceMatchingRunspaceId(this.InstanceId);
                        }
                        else if (parameterSetName == "Id")
                        {
                            runspaceMatchingRunspaceId = this.GetRunspaceMatchingSessionId(this.Id);
                        }
                        else if (parameterSetName == "Name")
                        {
                            runspaceMatchingRunspaceId = this.GetRunspaceMatchingName(this.Name);
                        }
                    }
                    else
                    {
                        runspaceMatchingRunspaceId = this.CreateRunspaceWhenComputerNameParameterSpecified();
                    }
                }
                if (runspaceMatchingRunspaceId != null)
                {
                    if (runspaceMatchingRunspaceId.RunspaceStateInfo.State == RunspaceState.Disconnected)
                    {
                        if (!runspaceMatchingRunspaceId.CanConnect)
                        {
                            string message = StringUtil.Format(RemotingErrorIdStrings.SessionNotAvailableForConnection, new object[0]);
                            base.WriteError(new ErrorRecord(new RuntimeException(message), "EnterPSSessionCannotConnectDisconnectedSession", ErrorCategory.InvalidOperation, runspaceMatchingRunspaceId));
                            return;
                        }
                        Exception innerException = null;
                        try
                        {
                            runspaceMatchingRunspaceId.Connect();
                        }
                        catch (PSRemotingTransportException exception2)
                        {
                            innerException = exception2;
                        }
                        catch (PSInvalidOperationException exception3)
                        {
                            innerException = exception3;
                        }
                        catch (InvalidRunspacePoolStateException exception4)
                        {
                            innerException = exception4;
                        }
                        if (innerException != null)
                        {
                            string str2 = StringUtil.Format(RemotingErrorIdStrings.SessionConnectFailed, new object[0]);
                            base.WriteError(new ErrorRecord(new RuntimeException(str2, innerException), "EnterPSSessionConnectSessionFailed", ErrorCategory.InvalidOperation, runspaceMatchingRunspaceId));
                            return;
                        }
                        if (runspaceMatchingRunspaceId.RunspaceAvailability == RunspaceAvailability.Busy)
                        {
                            string str3 = StringUtil.Format(RemotingErrorIdStrings.EnterPSSessionDisconnected, runspaceMatchingRunspaceId.Name);
                            base.WriteError(new ErrorRecord(new RuntimeException(str3, innerException), "EnterPSSessionConnectSessionNotAvailable", ErrorCategory.InvalidOperation, this.remoteRunspaceInfo));
                            runspaceMatchingRunspaceId.DisconnectAsync();
                            return;
                        }
                    }
                    if (runspaceMatchingRunspaceId.RunspaceStateInfo.State != RunspaceState.Opened)
                    {
                        if (base.ParameterSetName == "Session")
                        {
                            string str4 = (this.remoteRunspaceInfo != null) ? this.remoteRunspaceInfo.Name : string.Empty;
                            base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.EnterPSSessionBrokenSession, new object[] { str4, runspaceMatchingRunspaceId.ConnectionInfo.ComputerName, runspaceMatchingRunspaceId.InstanceId })), PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(), ErrorCategory.InvalidArgument, null));
                        }
                        else
                        {
                            base.WriteError(new ErrorRecord(new ArgumentException(base.GetMessage(RemotingErrorIdStrings.PushedRunspaceMustBeOpen)), PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(), ErrorCategory.InvalidArgument, null));
                        }
                    }
                    else
                    {
                        if (runspaceMatchingRunspaceId.RunspaceAvailability != RunspaceAvailability.Available)
                        {
                            base.WriteWarning(base.GetMessage(RunspaceStrings.RunspaceNotReady));
                        }
                        try
                        {
                            session.PushRunspace(runspaceMatchingRunspaceId);
                        }
                        catch (Exception)
                        {
                            if ((runspaceMatchingRunspaceId != null) && runspaceMatchingRunspaceId.ShouldCloseOnPop)
                            {
                                runspaceMatchingRunspaceId.Close();
                            }
                            throw;
                        }
                    }
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// Resume the Job.
        /// </summary>
        protected override void ProcessRecord()
        {
            //List of jobs to resume
            List <Job> jobsToResume = null;

            switch (ParameterSetName)
            {
            case NameParameterSet:
            {
                jobsToResume = FindJobsMatchingByName(true, false, true, false);
            }
            break;

            case InstanceIdParameterSet:
            {
                jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false);
            }
            break;

            case SessionIdParameterSet:
            {
                jobsToResume = FindJobsMatchingBySessionId(true, false, true, false);
            }
            break;

            case StateParameterSet:
            {
                jobsToResume = FindJobsMatchingByState(false);
            }
            break;

            case FilterParameterSet:
            {
                jobsToResume = FindJobsMatchingByFilter(false);
            }
            break;

            default:
            {
                jobsToResume = CopyJobsToList(_jobs, false, false);
            }
            break;
            }

            _allJobsToResume.AddRange(jobsToResume);

            // Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state
            // Setting Wait to true so that this cmdlet will wait for the running job state.
            if (_allJobsToResume.Count == 1)
            {
                Wait = true;
            }

            foreach (Job job in jobsToResume)
            {
                var job2 = job as Job2;

                // If the job is not Job2, the resume operation is not supported.
                if (job2 == null)
                {
                    WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job));
                    continue;
                }

                string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id);
                if (ShouldProcess(targetString, VerbsLifecycle.Resume))
                {
                    _cleanUpActions.Add(job2, HandleResumeJobCompleted);
                    job2.ResumeJobCompleted += HandleResumeJobCompleted;

                    lock (_syncObject)
                    {
                        if (!_pendingJobs.Contains(job2.InstanceId))
                        {
                            _pendingJobs.Add(job2.InstanceId);
                        }
                    }

                    job2.ResumeJobAsync();
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = PwshExePath;

            if (useWow64)
            {
                string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                if (!string.IsNullOrEmpty(procArch) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                        procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    psWow64Path = PwshExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                    if (!File.Exists(psWow64Path))
                    {
                        string message =
                            PSRemotingErrorInvariants.FormatResourceString(
                                RemotingErrorIdStrings.IPCWowComponentNotPresent,
                                psWow64Path);
                        throw new PSInvalidOperationException(message);
                    }
                }
            }

            string processArguments = " -s -NoLogo -NoProfile";

            if (initializationScript != null)
            {
                string scripBlockAsString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scripBlockAsString))
                {
                    string encodedCommand =
                        Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
                    processArguments = string.Format(CultureInfo.InvariantCulture,
                                                     "{0} -EncodedCommand {1}", processArguments, encodedCommand);
                }
            }

            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = useWow64 ? psWow64Path : PwshExePath,
                Arguments              = processArguments,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
#if !UNIX
                LoadUserProfile = true,
#endif
            };

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
                _startInfo.Password = credential.Password;
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }