// In this function the activity action is performed
        private void PerformWork(ActivityActionData data)
        {
            bool      failed    = false;
            Exception exception = null;

            try
            {
                // setting up the streams
                data.command.Streams.Debug    = data.streams.DebugStream;
                data.command.Streams.Error    = data.streams.ErrorStream;
                data.command.Streams.Progress = data.streams.ProgressStream;
                data.command.Streams.Verbose  = data.streams.VerboseStream;
                data.command.Streams.Warning  = data.streams.WarningStream;


                // Custom WinRM Workflow Endpoint details
                // run CustomWorkflowEndpointSetup.ps1 in Powershell console as administrator, if you have not done.
                //
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
                connectionInfo.ShellUri = "http://schemas.microsoft.com/powershell/CustomeWorkflowEndpoint";

                // Create runspace pool on custom workflow endpoint where command will be invoked
                using (RunspacePool r = RunspaceFactory.CreateRunspacePool(1, 1, connectionInfo))
                {
                    try
                    {
                        r.Open();
                        data.command.RunspacePool = r;

                        // now executing the powershell command.
                        data.command.Invoke(data.streams.InputStream, data.streams.OutputStream, new PSInvocationSettings());
                    }
                    finally
                    {
                        r.Close();
                        r.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                // since work is getting performed on background thread so there should not be any exception.
                failed    = true;
                exception = e;
            }

            // Now since activity action has already been performed so now we need to resume the execution of the
            // workflow. This will be done by
            PSWorkflowJob job = _runtime.JobManager.GetJob(data.jobInstanceId);

            // Now resuming the job
            if (failed)
            {
                job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams, exception);
            }
            else
            {
                job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams);
            }
        }
Exemplo n.º 2
0
        private static Collection <PSObject> runPowershellCommands(PSCommand commandsToRun)
        {
            if (pool.RunspacePoolStateInfo.State != RunspacePoolState.Opened)
            {
                pool.Close();
                pool = RunspaceFactory.CreateRunspacePool(1, 5, connection);
                pool.Open();
            }
            PowerShell powershell = PowerShell.Create();

            powershell.Commands     = commandsToRun;
            powershell.RunspacePool = pool;
            Collection <PSObject> results = powershell.Invoke();

            powershell.Dispose();
            return(results);
        }
Exemplo n.º 3
0
        protected override void Dispose(bool disposing)
        {
            Stop();

            RunspacePool.Close();
            RunspacePool.Dispose();
            RunspacePool = null;
            base.Dispose(disposing);
        }
 public void Release()
 {
     if (null != _rsPool)
     {
         lock (this)
         {
             if (null != _rsPool)
             {
                 _rsPool.Close();
                 _rsPool.Dispose();
                 _rsPool = null;
             }
         }
     }
 }
Exemplo n.º 5
0
        internal static void CleanupObjs(PSCmdlet invokeAll, FunctionInfo proxyFunctionInfo, RunspacePool runspacePool, bool isFromPipelineStoppedException,
                                         bool isAsyncEnd = false, bool noFileLogging = false, bool quiet = false)
        {
            LogHelper.LogProgress("Completed", invokeAll, "Completed", quiet: quiet);
            LogHelper.Log(fileVerboseLogTypes, "In Cleanup", invokeAll, noFileLogging);
            if (!isFromPipelineStoppedException && proxyFunctionInfo != null)
            {
                ScriptBlock.Create(@"Remove-Item Function:" + proxyFunctionInfo.Name).Invoke();
            }

            if (!isAsyncEnd && runspacePool != null)
            {
                if (runspacePool.ConnectionInfo != null)
                {
                    //runspacePool.Disconnect();
                }
                runspacePool.Close();
                runspacePool.Dispose();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Helper method to check any error condition after a stop call
        /// and close the remote runspace/pool if the stop call failed due
        /// to network outage problems.
        /// </summary>
        /// <param name="ex">Exception.</param>
        private void CheckAndCloseRunspaceAfterStop(Exception ex)
        {
            PSRemotingTransportException transportException = ex as PSRemotingTransportException;

            if (transportException != null &&
                (transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_CONNECT ||
                 transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_COMPLETE ||
                 transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST))
            {
                object rsObject = shell.GetRunspaceConnection();
                if (rsObject is Runspace)
                {
                    Runspace runspace = (Runspace)rsObject;
                    if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
                    {
                        try
                        {
                            runspace.Close();
                        }
                        catch (PSRemotingTransportException)
                        { }
                    }
                }
                else if (rsObject is RunspacePool)
                {
                    RunspacePool runspacePool = (RunspacePool)rsObject;
                    if (runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened)
                    {
                        try
                        {
                            runspacePool.Close();
                        }
                        catch (PSRemotingTransportException)
                        { }
                    }
                }
            }
        }
Exemplo n.º 7
0
        private void CheckAndCloseRunspaceAfterStop(Exception ex)
        {
            PSRemotingTransportException exception = ex as PSRemotingTransportException;

            if ((exception != null) && ((exception.ErrorCode == -2144108526) || (exception.ErrorCode == -2144108250)))
            {
                object runspaceConnection = this.shell.GetRunspaceConnection();
                if (runspaceConnection is Runspace)
                {
                    Runspace runspace = (Runspace)runspaceConnection;
                    if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
                    {
                        try
                        {
                            runspace.Close();
                        }
                        catch (PSRemotingTransportException)
                        {
                        }
                    }
                }
                else if (runspaceConnection is RunspacePool)
                {
                    RunspacePool pool = (RunspacePool)runspaceConnection;
                    if (pool.RunspacePoolStateInfo.State == RunspacePoolState.Opened)
                    {
                        try
                        {
                            pool.Close();
                        }
                        catch (PSRemotingTransportException)
                        {
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// This sample shows how to construct a remote RunspacePool and run
        /// multiple commands concurrently using the runspaces of the pool.
        /// </summary>
        /// <param name="args">Parameter is not used.</param>
        public static void Main(string[] args)
        {
            // Create a WSManConnectionInfo object using the default constructor to
            // connexct to the "localhost". The WSManConnectionInfo object can also
            // specify connections to remote computers.
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo();

            // Create a remote runspace pool that uses the WSManConnectionInfo object.
            // The minimum runspaces value of 1 and maximum runspaces value of 2 allows
            // Windows PowerShell to open a maximum of 2 runspaces at the same time so
            // that two commands can be run concurrently.
            using (RunspacePool remoteRunspacePool =
                       RunspaceFactory.CreateRunspacePool(1, 2, connectionInfo))
            {
                // Call the Open() method to open a runspace and establish the connection.
                remoteRunspacePool.Open();

                // Call the Create() method to create a pipeline, call the AddCommand(string)
                // method to add the "get-process" command, and then call the BeginInvoke()
                // method to run the command asynchronously using the runspace pool.
                PowerShell gpsCommand = PowerShell.Create().AddCommand("get-process");
                gpsCommand.RunspacePool = remoteRunspacePool;
                IAsyncResult gpsCommandAsyncResult = gpsCommand.BeginInvoke();

                // The previous call does not block the current thread because it is
                // running asynchronously. Because the remote runspace pool can open two
                // runspaces, the second command can be run.
                PowerShell getServiceCommand = PowerShell.Create().AddCommand("get-service");
                getServiceCommand.RunspacePool = remoteRunspacePool;
                IAsyncResult getServiceCommandAsyncResult = getServiceCommand.BeginInvoke();

                // When you are ready to handle the output, wait for the command to complete
                // before extracting results. A call to the EndInvoke() method will block and return
                // the output.
                PSDataCollection <PSObject> gpsCommandOutput = gpsCommand.EndInvoke(gpsCommandAsyncResult);

                // Process the output as needed.
                if ((gpsCommandOutput != null) && (gpsCommandOutput.Count > 0))
                {
                    Console.WriteLine("The first output from running get-process command: ");
                    Console.WriteLine(
                        "Process Name: {0} Process Id: {1}",
                        gpsCommandOutput[0].Properties["ProcessName"].Value,
                        gpsCommandOutput[0].Properties["Id"].Value);
                    Console.WriteLine();
                }

                // Now process the output from second command. As discussed previously, wait
                // for the command to complete before extracting the results.
                PSDataCollection <PSObject> getServiceCommandOutput = getServiceCommand.EndInvoke(
                    getServiceCommandAsyncResult);

                // Process the output of the second command as needed.
                if ((getServiceCommandOutput != null) && (getServiceCommandOutput.Count > 0))
                {
                    Console.WriteLine("The first output from running get-service command: ");
                    Console.WriteLine(
                        "Service Name: {0} Description: {1} State: {2}",
                        getServiceCommandOutput[0].Properties["ServiceName"].Value,
                        getServiceCommandOutput[0].Properties["DisplayName"].Value,
                        getServiceCommandOutput[0].Properties["Status"].Value);
                }

                // Once done with running all the commands, close the remote runspace pool.
                // The Dispose() (called by using primitive) will call Close(), if it
                // is not already called.
                remoteRunspacePool.Close();
            }
        }
Exemplo n.º 9
0
 public void Stop()
 {
     StopServer = true;
     PowerShellPool.Close();
     Log("Server Stopped.");
 }
        protected override void BeginProcessing()
        {
            // Build the results
            ArrayList final = new ArrayList();
            int       c     = 0;
            int       count = InputObject.Count;

            if (MaxThreads < 20)
            {
                MaxThreads = 20;
            }
            using (RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(1, MaxThreads))
            {
                try
                {
                    runspacePool.Open();
                    ProgressRecord progressRecord = new ProgressRecord(1, "Action in progress...", "Processing...");

                    foreach (object obj in InputObject)
                    {
                        PowerShell powerShell = PowerShell.Create()
                                                .AddScript(ScriptBlock)
                                                .AddArgument(obj);

                        try
                        {
                            powerShell.AddParameters(ArgumentList);
                        }
                        catch (Exception)
                        {
                        }
                        powerShell.RunspacePool = runspacePool;

                        IAsyncResult psAsyncResult = powerShell.BeginInvoke();
                        c++;

                        int    pVal = (c / count) * 100;
                        string sVal = String.Format("{0:N0}", pVal);
                        int    perc = int.Parse(sVal);

                        string activity = c + " of " + count + " threads completed";
                        if (NoProgress.IsPresent == false)
                        {
                            progressRecord.PercentComplete   = perc;
                            progressRecord.Activity          = activity;
                            progressRecord.StatusDescription = perc + "% complete";
                            WriteProgress(progressRecord);
                        }

                        PSDataCollection <PSObject> psOutput = powerShell.EndInvoke(psAsyncResult);
                        final.Add(psOutput);
                        powerShell.Dispose();
                    } // End foreach

                    if (NoProgress.IsPresent == false)
                    {
                        progressRecord.PercentComplete   = 100;
                        progressRecord.StatusDescription = "100% complete";
                        WriteProgress(progressRecord);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                runspacePool.Close();
                runspacePool.Dispose();
            } // End using

            // Output to console
            WriteObject(final.ToArray(), true);
        } // End begin
Exemplo n.º 11
0
 public void closeRunspacePool()
 {
     runspacePool.Close();
     runspacePool.Dispose();
 }