Exemplo n.º 1
0
            private void WriteConnectFailed(Exception e, PSSession session)
            {
                Exception runtimeException;

                if (this._writeStream.ObjectWriter.IsOpen)
                {
                    string fQEIDFromTransportError = "PSSessionConnectFailed";
                    if (e == null || string.IsNullOrEmpty(e.Message))
                    {
                        runtimeException = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name, session.Runspace.RunspaceStateInfo.State.ToString()), null);
                    }
                    else
                    {
                        PSRemotingTransportException pSRemotingTransportException = e as PSRemotingTransportException;
                        if (pSRemotingTransportException != null)
                        {
                            fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError(pSRemotingTransportException.ErrorCode, fQEIDFromTransportError);
                        }
                        runtimeException = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailedWithMessage, session.Name, e.Message), e);
                    }
                    ErrorRecord     errorRecord = new ErrorRecord(runtimeException, fQEIDFromTransportError, ErrorCategory.InvalidOperation, null);
                    Action <Cmdlet> action      = (Cmdlet cmdlet) => cmdlet.WriteError(errorRecord);
                    this._writeStream.ObjectWriter.Write(action);
                }
            }
Exemplo n.º 2
0
        internal static void DispatchModuleInfoProcessing(PSModuleInfo moduleInfo, Action localAction, Action <CimSession, Uri, string> cimSessionAction, Action <PSSession> psSessionAction)
        {
            object obj2;

            if (!_moduleInfoToSession.TryGetValue(moduleInfo, out obj2))
            {
                localAction();
            }
            else
            {
                Tuple <CimSession, Uri, string> tuple = obj2 as Tuple <CimSession, Uri, string>;
                if (tuple != null)
                {
                    cimSessionAction(tuple.Item1, tuple.Item2, tuple.Item3);
                }
                else
                {
                    PSSession session = obj2 as PSSession;
                    if (session != null)
                    {
                        psSessionAction(session);
                    }
                }
            }
        }
Exemplo n.º 3
0
        private RemoteRunspace CreateTemporaryRemoteRunspace(PSHost host, WSManConnectionInfo connectionInfo)
        {
            int            num;
            string         name     = PSSession.GenerateRunspaceName(out num);
            RemoteRunspace runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, host, this.SessionOption.ApplicationArguments, name, num);

            runspace.URIRedirectionReported += new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
            this.stream = new ObjectStream();
            try
            {
                runspace.Open();
                runspace.ShouldCloseOnPop = true;
            }
            finally
            {
                runspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
                this.stream.ObjectWriter.Close();
                if (runspace.RunspaceStateInfo.State != RunspaceState.Opened)
                {
                    runspace.Dispose();
                    runspace = null;
                }
            }
            return(runspace);
        }
Exemplo n.º 4
0
            private void WriteConnectedPSSession()
            {
                // Use temporary variable because we need to preserve _session class variable
                // for later clean up.
                PSSession outSession = _session;

                if (_queryRunspaces != null)
                {
                    lock (s_LockObject)
                    {
                        // Pass back the original session if possible.
                        if (_oldSession != null &&
                            _oldSession.InsertRunspace(_session.Runspace as RemoteRunspace))
                        {
                            outSession = _oldSession;
                            _retryList.Add(_oldSession);
                        }
                        else
                        {
                            _retryList.Add(_session);
                        }
                    }
                }

                if (_writeStream.ObjectWriter.IsOpen)
                {
                    // This code is based on ThrottleManager infrastructure
                    // and this particular method may be called on a thread that
                    // is different from Pipeline Execution Thread. Hence using
                    // a delegate to perform the WriteObject.
                    Action <Cmdlet> outputWriter = (Cmdlet cmdlet) => cmdlet.WriteObject(outSession);
                    _writeStream.ObjectWriter.Write(outputWriter);
                }
            }
Exemplo n.º 5
0
        /// <summary>
        /// EndProcessing override.
        /// </summary>
        protected override void BeginProcessing()
        {
            // Convert ConnectingTimeout value from seconds to milliseconds.
            _connectionInfo = new NamedPipeInfo(
                processId: ProcessId,
                connectingTimeout: (ConnectingTimeout == Timeout.Infinite) ? Timeout.Infinite : ConnectingTimeout * 1000);

            _runspace = RunspaceFactory.CreateRunspace(
                connectionInfo: _connectionInfo,
                host: Host,
                typeTable: TypeTable.LoadDefaultTypeFiles(),
                applicationArguments: null,
                name: Name);

            _openAsync              = new ManualResetEvent(false);
            _runspace.StateChanged += HandleRunspaceStateChanged;

            try
            {
                _runspace.OpenAsync();
                _openAsync.WaitOne();

                WriteObject(
                    PSSession.Create(
                        runspace: _runspace,
                        transportName: "PSNPTest",
                        psCmdlet: this));
            }
            finally
            {
                _openAsync.Dispose();
            }
        }
Exemplo n.º 6
0
 private PSSession ConnectSession(PSSession session, out Exception ex)
 {
     ex = null;
     if ((session == null) || ((session.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) && (session.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected)))
     {
         return(null);
     }
     if (session.Runspace.RunspaceStateInfo.State != RunspaceState.Opened)
     {
         try
         {
             session.Runspace.Connect();
         }
         catch (PSInvalidOperationException exception)
         {
             ex = exception;
         }
         catch (InvalidRunspaceStateException exception2)
         {
             ex = exception2;
         }
         catch (RuntimeException exception3)
         {
             ex = exception3;
         }
         if (ex != null)
         {
             return(null);
         }
     }
     return(session);
 }
Exemplo n.º 7
0
        internal static void DispatchModuleInfoProcessing(
            PSModuleInfo moduleInfo,
            Action localAction,
            Action <CimSession, Uri, string> cimSessionAction,
            Action <PSSession> psSessionAction)
        {
            object weaklyTypeSession;

            if (!s_moduleInfoToSession.TryGetValue(moduleInfo, out weaklyTypeSession))
            {
                localAction();
                return;
            }

            Tuple <CimSession, Uri, string> cimSessionInfo = weaklyTypeSession as Tuple <CimSession, Uri, string>;

            if (cimSessionInfo != null)
            {
                cimSessionAction(cimSessionInfo.Item1, cimSessionInfo.Item2, cimSessionInfo.Item3);
                return;
            }

            PSSession psSession = weaklyTypeSession as PSSession;

            if (psSession != null)
            {
                psSessionAction(psSession);
                return;
            }

            Dbg.Assert(false, "PSModuleInfo was associated with an unrecognized session type");
        }
        public void ExitSession()
        {
            _runspace.Close();
            _runspace.Dispose();

            _session = null;
        }
        public void EnterSession()
        {
            _runspace = RunspaceFactory.CreateRunspace();
            _runspace.Open();

            var sessionOptionsCommand = new Command("New-PSSessionOption");

            sessionOptionsCommand.Parameters.Add("OperationTimeout", 0);
            sessionOptionsCommand.Parameters.Add("IdleTimeout", TimeSpan.FromMinutes(20).TotalMilliseconds);
            var sessionOptionsObject = RunLocalCommand(_runspace, sessionOptionsCommand).Single().BaseObject;

            var sessionCommand = new Command("New-PSSession");

            sessionCommand.Parameters.Add("ComputerName", IpAddress);
            sessionCommand.Parameters.Add("Port", Port);
            sessionCommand.Parameters.Add("Authentication", Authentication);
            if (!string.IsNullOrEmpty(_username) && _password != null && !string.IsNullOrEmpty(_password.ToString()))
            {
                var powershellCredentials = new PSCredential(_username, _password);
                sessionCommand.Parameters.Add("Credential", powershellCredentials);
            }
            sessionCommand.Parameters.Add("SessionOption", sessionOptionsObject);
            var sessionObject = RunLocalCommand(_runspace, sessionCommand).Single().BaseObject;

            _session = (PSSession)sessionObject;
        }
Exemplo n.º 10
0
            private void WriteConnectFailed(
                Exception e,
                PSSession session)
            {
                if (_writeStream.ObjectWriter.IsOpen)
                {
                    string    FQEID = "PSSessionConnectFailed";
                    Exception reason;
                    if (e != null && !string.IsNullOrEmpty(e.Message))
                    {
                        // Update fully qualified error Id if we have a transport error.
                        PSRemotingTransportException transportException = e as PSRemotingTransportException;
                        if (transportException != null)
                        {
                            FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(transportException.ErrorCode, FQEID);
                        }

                        reason = new RuntimeException(
                            StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailedWithMessage, session.Name, e.Message),
                            e);
                    }
                    else
                    {
                        reason = new RuntimeException(
                            StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name,
                                              session.Runspace.RunspaceStateInfo.State.ToString()), null);
                    }
                    ErrorRecord     errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, null);
                    Action <Cmdlet> errorWriter = delegate(Cmdlet cmdlet)
                    {
                        cmdlet.WriteError(errorRecord);
                    };
                    _writeStream.ObjectWriter.Write(errorWriter);
                }
            }
Exemplo n.º 11
0
        private PSRemotingJob FindJobForSession(PSSession session)
        {
            PSRemotingJob  job      = null;
            RemoteRunspace runspace = session.Runspace as RemoteRunspace;

            if ((runspace == null) || (runspace.RemoteCommand != null))
            {
                return(null);
            }
            foreach (Job job2 in base.JobRepository.Jobs)
            {
                if (!(job2 is PSRemotingJob))
                {
                    continue;
                }
                foreach (PSRemotingChildJob job3 in job2.ChildJobs)
                {
                    if (job3.Runspace.InstanceId.Equals(session.InstanceId) && (job3.JobStateInfo.State == JobState.Disconnected))
                    {
                        job = (PSRemotingJob)job2;
                        break;
                    }
                }
                if (job != null)
                {
                    return(job);
                }
            }
            return(job);
        }
Exemplo n.º 12
0
            private void WriteConnectedPSSession()
            {
                Action <Cmdlet> action = null;

                if (this._queryRunspaces != null)
                {
                    lock (ConnectPSSessionCommand.ConnectRunspaceOperation.s_LockObject)
                    {
                        if (this._oldSession == null || !this._oldSession.InsertRunspace(this._session.Runspace as RemoteRunspace))
                        {
                            this._retryList.Add(this._session);
                        }
                        else
                        {
                            this._session = this._oldSession;
                            this._retryList.Add(this._oldSession);
                        }
                    }
                }
                if (this._writeStream.ObjectWriter.IsOpen)
                {
                    if (action == null)
                    {
                        action = (Cmdlet cmdlet) => cmdlet.WriteObject(this._session);
                    }
                    Action <Cmdlet> action1 = action;
                    this._writeStream.ObjectWriter.Write(action1);
                }
            }
Exemplo n.º 13
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (FullyQualifiedName.Expression != null)
            {
                targetCommand.AddParameter("FullyQualifiedName", FullyQualifiedName.Get(context));
            }

            if (All.Expression != null)
            {
                targetCommand.AddParameter("All", All.Get(context));
            }

            if (ListAvailable.Expression != null)
            {
                targetCommand.AddParameter("ListAvailable", ListAvailable.Get(context));
            }

            if (Refresh.Expression != null)
            {
                targetCommand.AddParameter("Refresh", Refresh.Get(context));
            }

            if (PSSession.Expression != null)
            {
                targetCommand.AddParameter("PSSession", PSSession.Get(context));
            }

            if (CimSession.Expression != null)
            {
                targetCommand.AddParameter("CimSession", CimSession.Get(context));
            }

            if (CimResourceUri.Expression != null)
            {
                targetCommand.AddParameter("CimResourceUri", CimResourceUri.Get(context));
            }

            if (CimNamespace.Expression != null)
            {
                targetCommand.AddParameter("CimNamespace", CimNamespace.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Exemplo n.º 14
0
 /// <summary>
 /// Sets a session and writes its timestamp to the cache
 /// </summary>
 /// <param name="ComputerName">The hostname it connects to.</param>
 /// <param name="Session">The session that is being registered.</param>
 public void Set(string ComputerName, PSSession Session)
 {
     if (!ConnectionHost.PSSessionCacheEnabled)
     {
         return;
     }
     Sessions[ComputerName.ToLower()]             = Session;
     ConnectionTimestamps[ComputerName.ToLower()] = DateTime.Now;
 }
Exemplo n.º 15
0
 internal ConnectRunspaceOperation(PSSession session, ObjectStream stream, PSHost host, QueryRunspaces queryRunspaces, Collection <PSSession> retryList)
 {
     this._session        = session;
     this._writeStream    = stream;
     this._host           = host;
     this._queryRunspaces = queryRunspaces;
     this._retryList      = retryList;
     this._session.Runspace.StateChanged += new EventHandler <RunspaceStateEventArgs>(this.StateCallBackHandler);
 }
Exemplo n.º 16
0
        private string GetRunspaceName(int rsIndex, out int rsId)
        {
            string str = PSSession.GenerateRunspaceName(out rsId);

            if ((this.names != null) && (rsIndex < this.names.Length))
            {
                str = this.names[rsIndex];
            }
            return(str);
        }
Exemplo n.º 17
0
            internal override void StartOperation()
            {
                bool startedSuccessfully = true;

                Exception ex = null;

                try
                {
                    if (_queryRunspaces != null)
                    {
                        PSSession newSession = QueryForSession(_session);
                        if (newSession != null)
                        {
                            _session.Runspace.StateChanged -= StateCallBackHandler;
                            _oldSession = _session;
                            _session    = newSession;
                            _session.Runspace.StateChanged += StateCallBackHandler;
                            _session.Runspace.ConnectAsync();
                        }
                        else
                        {
                            startedSuccessfully = false;
                        }
                    }
                    else
                    {
                        _session.Runspace.ConnectAsync();
                    }
                }
                catch (PSInvalidOperationException e)
                {
                    ex = e;
                }
                catch (InvalidRunspacePoolStateException e)
                {
                    ex = e;
                }
                catch (RuntimeException e)
                {
                    ex = e;
                }

                if (ex != null)
                {
                    startedSuccessfully = false;
                    WriteConnectFailed(ex, _session);
                }

                if (!startedSuccessfully)
                {
                    // We are done at this point.  Notify throttle manager.
                    _session.Runspace.StateChanged -= StateCallBackHandler;
                    SendStartComplete();
                }
            }
Exemplo n.º 18
0
            internal override void StartOperation()
            {
                bool      flag      = true;
                Exception exception = null;

                try
                {
                    if (this._queryRunspaces == null)
                    {
                        this._session.Runspace.ConnectAsync();
                    }
                    else
                    {
                        PSSession pSSession = this.QueryForSession(this._session);
                        if (pSSession == null)
                        {
                            flag = false;
                        }
                        else
                        {
                            this._session.Runspace.StateChanged -= new EventHandler <RunspaceStateEventArgs>(this.StateCallBackHandler);
                            this._oldSession = this._session;
                            this._session    = pSSession;
                            this._session.Runspace.StateChanged += new EventHandler <RunspaceStateEventArgs>(this.StateCallBackHandler);
                            this._session.Runspace.ConnectAsync();
                        }
                    }
                }
                catch (PSInvalidOperationException pSInvalidOperationException1)
                {
                    PSInvalidOperationException pSInvalidOperationException = pSInvalidOperationException1;
                    exception = pSInvalidOperationException;
                }
                catch (InvalidRunspacePoolStateException invalidRunspacePoolStateException1)
                {
                    InvalidRunspacePoolStateException invalidRunspacePoolStateException = invalidRunspacePoolStateException1;
                    exception = invalidRunspacePoolStateException;
                }
                catch (RuntimeException runtimeException1)
                {
                    RuntimeException runtimeException = runtimeException1;
                    exception = runtimeException;
                }
                if (exception != null)
                {
                    flag = false;
                    this.WriteConnectFailed(exception, this._session);
                }
                if (!flag)
                {
                    this._session.Runspace.StateChanged -= new EventHandler <RunspaceStateEventArgs>(this.StateCallBackHandler);
                    this.SendStartComplete();
                }
            }
Exemplo n.º 19
0
        private List <PSSession> GetDisconnectedSessions(PSInvokeExpressionSyncJob job)
        {
            List <PSSession> list = new List <PSSession>();

            foreach (PowerShell shell in job.GetPowerShells())
            {
                string             cmdStr       = ((shell.Commands != null) && (shell.Commands.Commands.Count > 0)) ? shell.Commands.Commands[0].CommandText : string.Empty;
                ConnectCommandInfo info         = new ConnectCommandInfo(shell.InstanceId, cmdStr);
                RunspacePool       runspacePool = null;
                if (shell.RunspacePool != null)
                {
                    runspacePool = shell.RunspacePool;
                }
                else
                {
                    object       runspaceConnection = shell.GetRunspaceConnection();
                    RunspacePool pool2 = runspaceConnection as RunspacePool;
                    if (pool2 != null)
                    {
                        runspacePool = pool2;
                    }
                    else
                    {
                        RemoteRunspace runspace = runspaceConnection as RemoteRunspace;
                        if (runspace != null)
                        {
                            runspacePool = runspace.RunspacePool;
                        }
                    }
                }
                if (runspacePool != null)
                {
                    if (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected)
                    {
                        if (!base.InvokeAndDisconnect || (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened))
                        {
                            continue;
                        }
                        runspacePool.Disconnect();
                    }
                    string name = runspacePool.RemoteRunspacePoolInternal.Name;
                    if (string.IsNullOrEmpty(name))
                    {
                        int num;
                        name = PSSession.GenerateRunspaceName(out num);
                    }
                    RunspacePool   pool3          = new RunspacePool(true, runspacePool.RemoteRunspacePoolInternal.InstanceId, name, new ConnectCommandInfo[] { info }, runspacePool.RemoteRunspacePoolInternal.ConnectionInfo, base.Host, base.Context.TypeTable);
                    RemoteRunspace remoteRunspace = new RemoteRunspace(pool3);
                    list.Add(new PSSession(remoteRunspace));
                }
            }
            return(list);
        }
Exemplo n.º 20
0
        internal List <Job> GetJobsForRunspace(PSSession runspace)
        {
            List <Job> list = new List <Job>();

            foreach (Job job in base.ChildJobs)
            {
                PSRemotingChildJob item = job as PSRemotingChildJob;
                if ((job != null) && item.Runspace.InstanceId.Equals(runspace.InstanceId))
                {
                    list.Add(item);
                }
            }
            return(list);
        }
Exemplo n.º 21
0
 internal ConnectRunspaceOperation(
     PSSession session,
     ObjectStream stream,
     PSHost host,
     QueryRunspaces queryRunspaces,
     Collection <PSSession> retryList)
 {
     _session        = session;
     _writeStream    = stream;
     _host           = host;
     _queryRunspaces = queryRunspaces;
     _retryList      = retryList;
     _session.Runspace.StateChanged += StateCallBackHandler;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Registeres a remote session under the owning runspace in its respective computer name
        /// </summary>
        /// <param name="Runspace">The runspace that owns the session</param>
        /// <param name="ComputerName">The computer the session connects to</param>
        /// <param name="Session">The session object</param>
        public static void PSSessionSet(Guid Runspace, string ComputerName, PSSession Session)
        {
            if (!PSSessionCacheEnabled)
            {
                return;
            }

            if (!PSSessions.ContainsKey(Runspace))
            {
                PSSessions[Runspace] = new PSSessionContainer(Runspace);
            }

            PSSessions[Runspace].Set(ComputerName.ToLower(), Session);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Removes an expired session from the cache, an returns it, so it can be properly closed.
 /// </summary>
 /// <returns>Returns a session to disconnect</returns>
 public PSSession PurgeExpiredSession()
 {
     foreach (string key in ConnectionTimestamps.Keys)
     {
         if (ConnectionTimestamps[key] + ConnectionHost.PSSessionTimeout < DateTime.Now && Sessions[key] != null && Sessions[key].Availability != RunspaceAvailability.Busy)
         {
             PSSession session = Sessions[key];
             Sessions.Remove(key);
             ConnectionTimestamps.Remove(key);
             return(session);
         }
     }
     return(null);
 }
Exemplo n.º 24
0
        private Collection <PSSession> CollectDisconnectedSessions(ConnectPSSessionCommand.OverrideParameter overrideParam = 0)
        {
            Collection <PSSession> pSSessions = new Collection <PSSession>();

            if (base.ParameterSetName != "Session")
            {
                Dictionary <Guid, PSSession> matchingRunspaces = null;
                ConnectPSSessionCommand.OverrideParameter overrideParameter = overrideParam;
                switch (overrideParameter)
                {
                case ConnectPSSessionCommand.OverrideParameter.None:
                {
                    matchingRunspaces = base.GetMatchingRunspaces(false, true);
                    break;
                }

                case ConnectPSSessionCommand.OverrideParameter.Name:
                {
                    matchingRunspaces = base.GetMatchingRunspacesByName(false, true);
                    break;
                }

                case ConnectPSSessionCommand.OverrideParameter.InstanceId:
                {
                    matchingRunspaces = base.GetMatchingRunspacesByRunspaceId(false, true);
                    break;
                }
                }
                if (matchingRunspaces != null)
                {
                    foreach (PSSession value in matchingRunspaces.Values)
                    {
                        pSSessions.Add(value);
                    }
                }
            }
            else
            {
                if (this.remotePSSessionInfo != null)
                {
                    PSSession[] pSSessionArray = this.remotePSSessionInfo;
                    for (int i = 0; i < (int)pSSessionArray.Length; i++)
                    {
                        PSSession pSSession = pSSessionArray[i];
                        pSSessions.Add(pSSession);
                    }
                }
            }
            return(pSSessions);
        }
        private bool ValidateIdleTimeout(PSSession session)
        {
            int idleTimeout    = session.Runspace.ConnectionInfo.IdleTimeout;
            int maxIdleTimeout = session.Runspace.ConnectionInfo.MaxIdleTimeout;
            int num3           = 0xea60;

            if ((idleTimeout == -1) || ((idleTimeout <= maxIdleTimeout) && (idleTimeout >= num3)))
            {
                return(true);
            }
            ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.CannotDisconnectSessionWithInvalidIdleTimeout, new object[] { session.Name, idleTimeout / 0x3e8, maxIdleTimeout / 0x3e8, num3 / 0x3e8 })), "CannotDisconnectSessionWithInvalidIdleTimeout", ErrorCategory.InvalidArgument, session);

            base.WriteError(errorRecord);
            return(false);
        }
Exemplo n.º 26
0
 internal List <Job> GetJobsForRunspace(PSSession runspace)
 {
     using (PSRemotingJob.tracer.TraceMethod())
     {
         List <Job> jobList = new List <Job>();
         foreach (Job childJob in (IEnumerable <Job>) this.ChildJobs)
         {
             PSRemotingChildJob remotingChildJob = childJob as PSRemotingChildJob;
             if (childJob != null && remotingChildJob.Runspace.InstanceId.Equals(runspace.InstanceId))
             {
                 jobList.Add((Job)remotingChildJob);
             }
         }
         return(jobList);
     }
 }
Exemplo n.º 27
0
        protected override void EndProcessing()
        {
            PSSession session = null;

            using (var pwsh = PowerShell.Create())
            {
                pwsh.Runspace = session.Runspace;

                Collection <PSObject> results = pwsh
                                                .AddCommand("Get-ChildItem")
                                                .AddParameter("Path", "C:\\")
                                                .AddParameter("Force", true)
                                                .Invoke();

                WriteObject(results, enumerateCollection: true);
            }
        }
Exemplo n.º 28
0
        protected virtual void CreateHelpersForSpecifiedComputerNames()
        {
            base.ValidateComputerName(base.ResolvedComputerNames);
            RemoteRunspace remoteRunspace = null;
            string         str            = this.UseSSL.IsPresent ? "https" : "http";

            for (int i = 0; i < base.ResolvedComputerNames.Length; i++)
            {
                try
                {
                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo {
                        Scheme       = str,
                        ComputerName = base.ResolvedComputerNames[i],
                        Port         = this.Port,
                        AppName      = this.ApplicationName,
                        ShellUri     = this.ConfigurationName
                    };
                    if (this.CertificateThumbprint != null)
                    {
                        connectionInfo.CertificateThumbprint = this.CertificateThumbprint;
                    }
                    else
                    {
                        connectionInfo.Credential = this.Credential;
                    }
                    connectionInfo.AuthenticationMechanism = this.Authentication;
                    base.UpdateConnectionInfo(connectionInfo);
                    connectionInfo.EnableNetworkAccess = (bool)this.EnableNetworkAccess;
                    int    id   = PSSession.GenerateRunspaceId();
                    string name = ((this.DisconnectedSessionName != null) && (this.DisconnectedSessionName.Length > i)) ? this.DisconnectedSessionName[i] : PSSession.ComposeRunspaceName(id);
                    remoteRunspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, base.Host, this.SessionOption.ApplicationArguments, name, id);
                    remoteRunspace.Events.ReceivedEvents.PSEventReceived += new PSEventReceivedEventHandler(this.OnRunspacePSEventReceived);
                }
                catch (UriFormatException exception)
                {
                    ErrorRecord errorRecord = new ErrorRecord(exception, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, base.ResolvedComputerNames[i]);
                    base.WriteError(errorRecord);
                    continue;
                }
                Pipeline           pipeline = this.CreatePipeline(remoteRunspace);
                IThrottleOperation item     = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, this.invokeAndDisconnect);
                this.Operations.Add(item);
            }
        }
Exemplo n.º 29
0
 private void WriteRemoteObject(PSObject psObject, PSSession session)
 {
     if (psObject != null)
     {
         if (psObject.Properties[RemotingConstants.ComputerNameNoteProperty] == null)
         {
             psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, session.ComputerName));
         }
         if (psObject.Properties[RemotingConstants.RunspaceIdNoteProperty] == null)
         {
             psObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, session.InstanceId));
         }
         if (psObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null)
         {
             psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true));
         }
         base.WriteObject(psObject);
     }
 }
Exemplo n.º 30
0
        private bool ValidateIdleTimeout(PSSession session)
        {
            int idleTimeout    = session.Runspace.ConnectionInfo.IdleTimeout;
            int maxIdleTimeout = session.Runspace.ConnectionInfo.MaxIdleTimeout;
            int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout;

            if (idleTimeout != BaseTransportManager.UseServerDefaultIdleTimeout &&
                (idleTimeout > maxIdleTimeout || idleTimeout < minIdleTimeout))
            {
                string msg = StringUtil.Format(RemotingErrorIdStrings.CannotDisconnectSessionWithInvalidIdleTimeout,
                                               session.Name, idleTimeout / 1000, maxIdleTimeout / 1000, minIdleTimeout / 1000);
                ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(msg),
                                                          "CannotDisconnectSessionWithInvalidIdleTimeout", ErrorCategory.InvalidArgument, session);
                WriteError(errorRecord);

                return(false);
            }

            return(true);
        }
Exemplo n.º 31
0
		public static int Initialize(IDebugger debugger, IProgram program)
		{
			_theSession = new PSSession(debugger, program);
			return 0;
		}