public CimActivityImplementationContext(ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism? authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri)
		{
			if (activityImplementationContext != null)
			{
				base.PowerShellInstance = activityImplementationContext.PowerShellInstance;
				this.ResourceUri = resourceUri;
				this.ComputerName = computerName;
				base.PSCredential = credential;
				base.PSCertificateThumbprint = certificateThumbprint;
				base.PSAuthentication = authenticationMechanism;
				base.PSUseSsl = new bool?(useSsl);
				base.PSPort = new uint?(port);
				base.PSSessionOption = sessionOption;
				this.Session = session;
				this.SessionOptions = cimSessionOptions;
				if (moduleDefinition != null)
				{
					CimActivityImplementationContext._moduleScriptBlock = ScriptBlock.Create(moduleDefinition);
					this._moduleDefinition = moduleDefinition;
				}
				return;
			}
			else
			{
				throw new ArgumentNullException("activityImplementationContext");
			}
		}
		public DirectExecutionActivitiesCommandRuntime(PSDataCollection<PSObject> output, ActivityImplementationContext implementationContext, Type cmdletType)
		{
			if (output != null)
			{
				if (implementationContext != null)
				{
					if (cmdletType != null)
					{
						this._output = output;
						this._implementationContext = implementationContext;
						this._cmdletType = cmdletType;
						return;
					}
					else
					{
						throw new ArgumentNullException("cmdletType");
					}
				}
				else
				{
					throw new ArgumentNullException("implementationContext");
				}
			}
			else
			{
				throw new ArgumentNullException("output");
			}
		}
Example #3
0
		protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
		{
			ActivityImplementationContext activityImplementationContext = new ActivityImplementationContext();
			activityImplementationContext.PowerShellInstance = PowerShell.Create();
			ActivityImplementationContext activityImplementationContext1 = activityImplementationContext;
			return activityImplementationContext1;
		}
Example #4
0
        /// <summary>
        /// Creates and returns an empty powershell
        /// </summary>
        /// <param name="context">activity context</param>
        /// <returns>A new activity implementation context</returns>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            ActivityImplementationContext implementationContext = new ActivityImplementationContext
                                                                      {
                                                                          PowerShellInstance =
                                                                              System.Management.Automation.PowerShell.
                                                                              Create()
                                                                      };

            return implementationContext;
        }
Example #5
0
 /// <summary>
 /// Create an instance of the CIM activity implementation class
 /// </summary>
 /// <param name="activityImplementationContext"></param>
 /// <param name="computerName"></param>
 /// <param name="credential"></param>
 /// <param name="certificateThumbprint"></param>
 /// <param name="authenticationMechanism"></param>
 /// <param name="useSsl"></param>
 /// <param name="port"></param>
 /// <param name="sessionOption"></param>
 /// <param name="session"></param>
 /// <param name="cimSessionOptions"></param>
 /// <param name="moduleDefinition"></param>
 /// <param name="resourceUri"></param>
 public CimActivityImplementationContext(
     ActivityImplementationContext activityImplementationContext,
     string computerName,
     PSCredential credential,
     string certificateThumbprint,
     AuthenticationMechanism?authenticationMechanism,
     bool useSsl,
     uint port,
     PSSessionOption sessionOption,
     CimSession session,
     CimSessionOptions cimSessionOptions,
     string moduleDefinition,
     Uri resourceUri)
 {
     if (activityImplementationContext == null)
     {
         throw new ArgumentNullException("activityImplementationContext");
     }
     this.PowerShellInstance = activityImplementationContext.PowerShellInstance;
     ResourceUri             = resourceUri;
     ComputerName            = computerName;
     PSCredential            = credential;
     PSCertificateThumbprint = certificateThumbprint;
     PSAuthentication        = authenticationMechanism;
     PSUseSsl        = useSsl;
     PSPort          = port;
     PSSessionOption = sessionOption;
     Session         = session;
     SessionOptions  = cimSessionOptions;
     if (moduleDefinition != null)
     {
         // Creating a script block forces the string into the compiled script cache so we
         // don't need to reparse it at execution time. Locking the static _moduleDefinition is not
         // required since the operation is idempotent.
         _moduleScriptBlock = ScriptBlock.Create(moduleDefinition);
         _moduleDefinition  = moduleDefinition;
     }
 }
        /// <summary>
        /// Creates Powershell instance and adds the command to it
        /// </summary>
        /// <param name="context">The activity context to use</param>
        /// <param name="connection">The wsman connection to use</param>
        /// <param name="commands">The list of commands</param>
        private void CreatePowerShellInstance(NativeActivityContext context, WSManConnectionInfo connection,
                                              List <ActivityImplementationContext> commands)
        {
            // Create the PowerShell instance, and add the command to it.
            ActivityImplementationContext implementationContext = GetPowerShell(context);

#if true
            Runspace runspace;
            if (connection != null)
            {
                implementationContext.ConnectionInfo = connection;
                runspace = RunspaceFactory.CreateRunspace(connection);
                implementationContext.PowerShellInstance.Runspace = runspace;
            }
            else
            {
                // if PSComputerName is "" or $null than connection is NULL
                UpdateImplementationContextForLocalExecution(implementationContext, context);
            }
#endif
            // Add it to the queue of commands to execute.
            commands.Add(implementationContext);
        }
Example #7
0
        // InlineScript needs to handle these specially, since it might go through the PowerShell AddScript() API.
        // If the parameter "CommandName" is in use, we add the preference configuration to the command parameters,
        // otherwise, we add the preference configuration to the preference variable.
        // All other activities have this set automatically by the infrastructure via parameters.
        private void UpdatePreferenceVariables(ActivityImplementationContext implementationContext)
        {
            System.Management.Automation.PowerShell        session = implementationContext.PowerShellInstance;
            System.Management.Automation.Runspaces.Command command = null;

            if (!_commandSpecified)
            {
                // "CommandName" and "Parameters" are in use
                command = session.Commands.Commands[0];
            }

            if (implementationContext.Verbose != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Verbose", implementationContext.Verbose);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Verbose.Value)
                    {
                        preference = ActionPreference.Continue;
                    }

                    implementationContext.PSActivityEnvironment.Variables["VerbosePreference"] = preference;
                }
            }

            if (implementationContext.Debug != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Debug", implementationContext.Debug);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Debug.Value)
                    {
                        preference = ActionPreference.Continue;
                    }

                    implementationContext.PSActivityEnvironment.Variables["DebugPreference"] = preference;
                }
            }

            if (implementationContext.WhatIf != null && command != null)
            {
                command.Parameters.Add("WhatIf", implementationContext.WhatIf);
            }

            if (implementationContext.ErrorAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("ErrorAction", implementationContext.ErrorAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["ErrorActionPreference"] = implementationContext.ErrorAction;
                }
            }

            if (implementationContext.WarningAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("WarningAction", implementationContext.WarningAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["WarningPreference"] = implementationContext.WarningAction;
                }
            }

            if (implementationContext.InformationAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("InformationAction", implementationContext.InformationAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["InformationPreference"] = implementationContext.InformationAction;
                }
            }
        }
Example #8
0
        /// <summary>
        /// Adds the PSActivity variable to the active runspace, which is of type InlineScriptContext.
        /// </summary>
        /// <param name="implementationContext">The ActivityImplementationContext returned by the call to GetCommand.</param>
        protected override void PrepareSession(ActivityImplementationContext implementationContext)
        {
            if (implementationContext.PSActivityEnvironment == null)
            {
                implementationContext.PSActivityEnvironment = new PSActivityEnvironment();
            }

            // Update the preference variables
            UpdatePreferenceVariables(implementationContext);
            System.Management.Automation.PowerShell session = implementationContext.PowerShellInstance;

            implementationContext.PSActivityEnvironment.Variables["UserName"] = System.Environment.UserName;

            string computerName = null;

            if (implementationContext.ConnectionInfo != null)
            {
                computerName = implementationContext.ConnectionInfo.ComputerName;
            }
            if (string.IsNullOrEmpty(computerName))
            {
                computerName = "localhost";
            }

            implementationContext.PSActivityEnvironment.Variables["ComputerName"]   = computerName;
            implementationContext.PSActivityEnvironment.Variables["PSComputerName"] = computerName;

            string workflowCommandName = null;

            Dictionary <string, object> activityVariables = (Dictionary <string, object>)implementationContext.WorkflowContext;

            if (activityVariables != null && activityVariables.ContainsKey("ParameterDefaults"))
            {
                HostParameterDefaults defaults = activityVariables["ParameterDefaults"] as HostParameterDefaults;
                if (defaults != null)
                {
                    workflowCommandName = defaults.Parameters["WorkflowCommandName"] as string;
                }
            }

            if (string.IsNullOrEmpty(workflowCommandName))
            {
                workflowCommandName = "unknown";
            }

            implementationContext.PSActivityEnvironment.Variables["CommandName"] = workflowCommandName;

            // Populate the default variables
            InlineScriptContext inlineScriptContext = new InlineScriptContext(this);

            // Populate the activity variables
            foreach (KeyValuePair <string, object> entry in activityVariables)
            {
                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    System.Diagnostics.Debug.Assert(entry.Value is HostParameterDefaults, "ParameterDefaults does not contain a HostParameterDefaults object");
                    inlineScriptContext.Variables[entry.Key] = ((HostParameterDefaults)entry.Value).Parameters;
                    continue;
                }
                inlineScriptContext.Variables[entry.Key] = entry.Value;
            }

            // Set the PowerShell session variables...
            foreach (KeyValuePair <string, object> entry in activityVariables)
            {
                var value = entry.Value;

                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                implementationContext.PSActivityEnvironment.Variables[entry.Key] = value;
            }
        }
Example #9
0
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            ValidateParameters();
            System.Management.Automation.PowerShell invoker    = null;
            HashSet <string>            allWorkflowVarNames    = new HashSet <string>(StaticPotentialUsingVariableSet, StringComparer.OrdinalIgnoreCase);
            Dictionary <string, object> defaults               = this.ParameterDefaults.Get(context);
            Dictionary <string, object> activityVariables      = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            Dictionary <string, object> activityUsingVariables = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            string[] streams =
            {
                "Result", "PSError", "PSWarning", "PSVerbose", "PSDebug", "PSProgress", "PSInformation"
            };

            // First, set the variables from the user's variables
            foreach (System.ComponentModel.PropertyDescriptor property in context.DataContext.GetProperties())
            {
                if (String.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                // Add all user-defined variables/parameters in the same scope of the InlineScript activity
                if (!allWorkflowVarNames.Contains(property.Name))
                {
                    allWorkflowVarNames.Add(property.Name);
                }

                Object value = property.GetValue(context.DataContext);
                if (value != null)
                {
                    object tempValue = value;

                    PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>;

                    if (collectionObject != null && collectionObject.Count == 1)
                    {
                        tempValue = collectionObject[0];
                    }

                    activityVariables[property.Name] = tempValue;
                }
            }

            // Then, set anything we received from parameters
            foreach (PSActivityArgumentInfo currentArgument in GetActivityArguments())
            {
                string @default = currentArgument.Name;
                if (streams.Any(item => string.Equals(item, @default, StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                object argumentValue = currentArgument.Value.Get(context);
                if (argumentValue != null && !activityVariables.ContainsKey(currentArgument.Name))
                {
                    activityVariables[currentArgument.Name] = argumentValue;
                }
            }

            // Then, set the variables from the host defaults
            if (defaults != null)
            {
                foreach (string hostDefault in defaults.Keys)
                {
                    string @default = hostDefault;
                    if (streams.Any(item => string.Equals(item, @default, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    object propertyValue = defaults[hostDefault];
                    if (propertyValue != null && !activityVariables.ContainsKey(hostDefault))
                    {
                        activityVariables[hostDefault] = propertyValue;
                    }
                }
            }

            if (_commandSpecified)
            {
                string script = string.IsNullOrEmpty(Command) ? string.Empty : Command;
                Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity ID={0}: Inline Script: '{1}'.", context.ActivityInstanceId, script));

                if (IsBlocked(script))
                {
                    throw new PSInvalidOperationException(String.Format(CultureInfo.InvariantCulture, ActivityResources.CannotLaunchFormat, script));
                }

                string[] targetNodes = null;
                if (this.PSComputerName.Expression != null)
                {
                    targetNodes = this.PSComputerName.Get(context);
                }
                else
                {
                    if (defaults != null && defaults.ContainsKey("PSComputerName"))
                    {
                        targetNodes = this.ParameterDefaults.Get(context)["PSComputerName"] as string[];
                    }
                }

                // See if this command will be run in process.
                if ((targetNodes == null || targetNodes.Length == 0) && GetRunInProc(context))
                {
                    if (_compiledScriptForInProc == null || _ci == null)
                    {
                        lock (Syncroot)
                        {
                            if (_compiledScriptForInProc == null)
                            {
                                if (_scriptWithoutUsing == null)
                                {
                                    _scriptWithoutUsing = RemoveUsingPrefix(script, allWorkflowVarNames, out _usingVariables);
                                }
                                _compiledScriptForInProc = ScriptBlock.Create(_scriptWithoutUsing);
                            }

                            // Invoke using the CommandInfo for Invoke-Command directly, rather than going through
                            // the command discovery since this is much faster.
                            if (_ci == null)
                            {
                                _ci = new CmdletInfo("Invoke-Command", typeof(Microsoft.PowerShell.Commands.InvokeCommandCommand));
                            }
                        }
                    }

                    SetAvailableUsingVariables(activityVariables, activityUsingVariables);
                    Tracer.WriteMessage("PowerShell activity: executing InlineScript locally with ScriptBlock.");
                    invoker = System.Management.Automation.PowerShell.Create();
                    invoker.AddCommand(_ci).AddParameter("NoNewScope").AddParameter("ScriptBlock", _compiledScriptForInProc);
                }
                else
                {
                    // Try to convert the ScriptBlock to a powershell instance
                    if (_compiledScriptForOutProc == null)
                    {
                        lock (Syncroot)
                        {
                            if (_compiledScriptForOutProc == null)
                            {
                                _compiledScriptForOutProc = ScriptBlock.Create(script);
                            }
                        }
                    }

                    try
                    {
                        // we trust the code inside inlinescript, set isTrusted as True.
                        invoker = _compiledScriptForOutProc.GetPowerShell(activityVariables, out activityUsingVariables, true);
                        Tracer.WriteMessage("PowerShell activity: executing InlineScript with ScriptBlock to powershell conversion.");
                    }
                    catch (Exception)
                    {
                        invoker = null;
                    }

                    if (invoker == null)
                    {
                        // Since scriptblocks aren't serialized with fidelity in the remote case, we need to
                        // use AddScript instead.
                        if (_scriptWithoutUsing == null)
                        {
                            lock (Syncroot)
                            {
                                if (_scriptWithoutUsing == null)
                                {
                                    _scriptWithoutUsing = RemoveUsingPrefix(script, allWorkflowVarNames, out _usingVariables);
                                }
                            }
                        }

                        SetAvailableUsingVariables(activityVariables, activityUsingVariables);
                        Tracer.WriteMessage("PowerShell activity: executing InlineScript by using AddScript.");
                        invoker = System.Management.Automation.PowerShell.Create();
                        invoker.AddScript(_scriptWithoutUsing);
                    }
                }
            }
            else
            {
                string commandName = CommandName.Get(context);
                if (String.IsNullOrEmpty(commandName))
                {
                    throw new ArgumentException(ActivityResources.CommandNameRequired);
                }

                Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity ID={0}: Invoking command '{1}'.", context.ActivityInstanceId, commandName));
                invoker = System.Management.Automation.PowerShell.Create();
                invoker.AddCommand(commandName);

                System.Collections.Hashtable parameters = Parameters.Get(context);

                if (parameters != null && parameters.Count > 0)
                {
                    foreach (var key in parameters.Keys)
                    {
                        Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity: Adding parameter '-{0} {1}'.",
                                                          key, parameters[key]));
                    }
                    invoker.AddParameters(parameters);
                }
            }

            var implementationContext = new ActivityImplementationContext
            {
                PowerShellInstance = invoker,
                WorkflowContext    = activityUsingVariables
            };

            return(implementationContext);
        }
Example #10
0
		private static void UpdatePreferenceVariables(ActivityImplementationContext implementationContext)
		{
			Command item = implementationContext.PowerShellInstance.Commands.Commands[0];
			bool? verbose = implementationContext.Verbose;
			if (verbose.HasValue)
			{
				item.Parameters.Add("Verbose", implementationContext.Verbose);
			}
			bool? debug = implementationContext.Debug;
			if (debug.HasValue)
			{
				item.Parameters.Add("Debug", implementationContext.Debug);
			}
			bool? whatIf = implementationContext.WhatIf;
			if (whatIf.HasValue)
			{
				item.Parameters.Add("WhatIf", implementationContext.WhatIf);
			}
			ActionPreference? errorAction = implementationContext.ErrorAction;
			if (errorAction.HasValue)
			{
				item.Parameters.Add("ErrorAction", implementationContext.ErrorAction);
			}
			ActionPreference? warningAction = implementationContext.WarningAction;
			if (warningAction.HasValue)
			{
				item.Parameters.Add("WarningAction", implementationContext.WarningAction);
			}
		}
Example #11
0
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            ValidateParameters();
            System.Management.Automation.PowerShell invoker = null;
            HashSet<string> allWorkflowVarNames = new HashSet<string>(StaticPotentialUsingVariableSet, StringComparer.OrdinalIgnoreCase);
            Dictionary<string, object> defaults = this.ParameterDefaults.Get(context);
            Dictionary<string, object> activityVariables = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            Dictionary<string, object> activityUsingVariables = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

            string[] streams =
            {
                "Result", "PSError", "PSWarning", "PSVerbose", "PSDebug", "PSProgress", "PSInformation"
            };

            // First, set the variables from the user's variables
            foreach (System.ComponentModel.PropertyDescriptor property in context.DataContext.GetProperties())
            {
                if (String.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                    continue;

                // Add all user-defined variables/parameters in the same scope of the InlineScript activity
                if (!allWorkflowVarNames.Contains(property.Name))
                {
                    allWorkflowVarNames.Add(property.Name);
                }

                Object value = property.GetValue(context.DataContext);
                if (value != null)
                {
                    object tempValue = value;

                    PSDataCollection<PSObject> collectionObject = value as PSDataCollection<PSObject>;

                    if (collectionObject != null && collectionObject.Count == 1)
                    {
                        tempValue = collectionObject[0];
                    }

                    activityVariables[property.Name] = tempValue;
                }               
            }

            // Then, set anything we received from parameters
            foreach (PSActivityArgumentInfo currentArgument in GetActivityArguments())
            {
                string @default = currentArgument.Name;
                if (streams.Any(item => string.Equals(item, @default, StringComparison.OrdinalIgnoreCase)))
                    continue;

                object argumentValue = currentArgument.Value.Get(context);
                if (argumentValue != null && !activityVariables.ContainsKey(currentArgument.Name))
                {
                    activityVariables[currentArgument.Name] = argumentValue;
                }
            }

            // Then, set the variables from the host defaults
            if (defaults != null)
            {
                foreach (string hostDefault in defaults.Keys)
                {
                     string @default = hostDefault;
                    if (streams.Any(item => string.Equals(item, @default, StringComparison.OrdinalIgnoreCase)))
                        continue;

                    object propertyValue = defaults[hostDefault];
                    if (propertyValue != null && !activityVariables.ContainsKey(hostDefault))
                    {
                        activityVariables[hostDefault] = propertyValue;
                    }
                }
            }

            if (_commandSpecified)
            {
                string script = string.IsNullOrEmpty(Command) ? string.Empty : Command;
                Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity ID={0}: Inline Script: '{1}'.", context.ActivityInstanceId, script));

                if (IsBlocked(script))
                {
                    throw new PSInvalidOperationException(String.Format(CultureInfo.InvariantCulture, ActivityResources.CannotLaunchFormat, script));
                }

                string[] targetNodes = null;
                if (this.PSComputerName.Expression != null)
                {
                    targetNodes = this.PSComputerName.Get(context);
                }
                else
                {
                    if (defaults != null && defaults.ContainsKey("PSComputerName"))
                    {
                        targetNodes = this.ParameterDefaults.Get(context)["PSComputerName"] as string[];
                    }
                }

                // See if this command will be run in process.
                if ((targetNodes == null || targetNodes.Length == 0) && GetRunInProc(context))
                {
                    if (_compiledScriptForInProc == null || _ci == null)
                    {
                        lock (Syncroot)
                        {
                            if (_compiledScriptForInProc == null)
                            {
                                if (_scriptWithoutUsing == null)
                                {
                                    _scriptWithoutUsing = RemoveUsingPrefix(script, allWorkflowVarNames, out _usingVariables);
                                }
                                _compiledScriptForInProc = ScriptBlock.Create(_scriptWithoutUsing);
                            }

                            // Invoke using the CommandInfo for Invoke-Command directly, rather than going through
                            // the command discovery since this is much faster.
                            if (_ci == null)
                            {
                                _ci = new CmdletInfo("Invoke-Command", typeof(Microsoft.PowerShell.Commands.InvokeCommandCommand));
                            }
                        }
                    }

                    SetAvailableUsingVariables(activityVariables, activityUsingVariables);
                    Tracer.WriteMessage("PowerShell activity: executing InlineScript locally with ScriptBlock.");
                    invoker = System.Management.Automation.PowerShell.Create();
                    invoker.AddCommand(_ci).AddParameter("NoNewScope").AddParameter("ScriptBlock", _compiledScriptForInProc);
                }
                else
                {
                    // Try to convert the ScriptBlock to a powershell instance
                    if (_compiledScriptForOutProc == null)
                    {
                        lock (Syncroot)
                        {
                            if (_compiledScriptForOutProc == null)
                            {
                                _compiledScriptForOutProc = ScriptBlock.Create(script);
                            }
                        }
                    }

                    try
                    {
                        // we trust the code inside inlinescript, set isTrusted as True.
                        invoker = _compiledScriptForOutProc.GetPowerShell(activityVariables, out activityUsingVariables, true);
                        Tracer.WriteMessage("PowerShell activity: executing InlineScript with ScriptBlock to powershell conversion.");
                    }
                    catch (Exception)
                    {
                        invoker = null;
                    }

                    if (invoker == null)
                    {
                        // Since scriptblocks aren't serialized with fidelity in the remote case, we need to
                        // use AddScript instead.
                        if (_scriptWithoutUsing == null)
                        {
                            lock (Syncroot)
                            {
                                if (_scriptWithoutUsing == null)
                                {
                                    _scriptWithoutUsing = RemoveUsingPrefix(script, allWorkflowVarNames, out _usingVariables);
                                }
                            }
                        }

                        SetAvailableUsingVariables(activityVariables, activityUsingVariables);
                        Tracer.WriteMessage("PowerShell activity: executing InlineScript by using AddScript.");
                        invoker = System.Management.Automation.PowerShell.Create();
                        invoker.AddScript(_scriptWithoutUsing);
                    }
                }
            }
            else
            {
                string commandName = CommandName.Get(context);
                if (String.IsNullOrEmpty(commandName))
                {
                    throw new ArgumentException(ActivityResources.CommandNameRequired);
                }

                Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity ID={0}: Invoking command '{1}'.", context.ActivityInstanceId, commandName));
                invoker = System.Management.Automation.PowerShell.Create();
                invoker.AddCommand(commandName);

                System.Collections.Hashtable parameters = Parameters.Get(context);

                if (parameters != null && parameters.Count > 0)
                {
                    foreach (var key in parameters.Keys)
                    {
                        Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity: Adding parameter '-{0} {1}'.",
                            key, parameters[key]));
                    }
                    invoker.AddParameters(parameters);
                }
            }

            var implementationContext = new ActivityImplementationContext
                                            {
                                                PowerShellInstance = invoker,
                                                WorkflowContext = activityUsingVariables
                                            };

            return implementationContext;
        }
Example #12
0
        // InlineScript needs to handle these specially, since it might go through the PowerShell AddScript() API.
        // If the parameter "CommandName" is in use, we add the preference configuration to the command parameters,
        // otherwise, we add the preference configuration to the preference variable.
        // All other activities have this set automatically by the infrastructure via parameters.
        private void UpdatePreferenceVariables(ActivityImplementationContext implementationContext)
        {
            System.Management.Automation.PowerShell session = implementationContext.PowerShellInstance;
            System.Management.Automation.Runspaces.Command command = null;

            if (!_commandSpecified)
            {
                // "CommandName" and "Parameters" are in use
                command = session.Commands.Commands[0];
            }

            if (implementationContext.Verbose != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Verbose", implementationContext.Verbose);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Verbose.Value)
                        preference = ActionPreference.Continue;

                    implementationContext.PSActivityEnvironment.Variables["VerbosePreference"] = preference;
                }
            }

            if (implementationContext.Debug != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Debug", implementationContext.Debug);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Debug.Value)
                        preference = ActionPreference.Continue;

                    implementationContext.PSActivityEnvironment.Variables["DebugPreference"] = preference;
                }
            }

            if (implementationContext.WhatIf != null && command != null)
            {
                command.Parameters.Add("WhatIf", implementationContext.WhatIf);
            }

            if (implementationContext.ErrorAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("ErrorAction", implementationContext.ErrorAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["ErrorActionPreference"] = implementationContext.ErrorAction;
                }
            }

            if (implementationContext.WarningAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("WarningAction", implementationContext.WarningAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["WarningPreference"] = implementationContext.WarningAction;
                }
            }

            if (implementationContext.InformationAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("InformationAction", implementationContext.InformationAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["InformationPreference"] = implementationContext.InformationAction;
                }
            }

        }
 /// <summary>
 /// Create an instance of the CIM activity implementation class
 /// </summary>
 /// <param name="activityImplementationContext"></param>
 /// <param name="computerName"></param>
 /// <param name="credential"></param>
 /// <param name="certificateThumbprint"></param>
 /// <param name="authenticationMechanism"></param>
 /// <param name="useSsl"></param>
 /// <param name="port"></param>
 /// <param name="sessionOption"></param>
 /// <param name="session"></param>
 /// <param name="cimSessionOptions"></param>
 /// <param name="moduleDefinition"></param>
 /// <param name="resourceUri"></param>
 public CimActivityImplementationContext(
     ActivityImplementationContext activityImplementationContext,
     string computerName, 
     PSCredential credential, 
     string certificateThumbprint, 
     AuthenticationMechanism? authenticationMechanism, 
     bool useSsl, 
     uint port, 
     PSSessionOption sessionOption, 
     CimSession session, 
     CimSessionOptions cimSessionOptions, 
     string moduleDefinition,
     Uri resourceUri)
 {
     if (activityImplementationContext == null)
     {
         throw new ArgumentNullException("activityImplementationContext");
     }
     this.PowerShellInstance = activityImplementationContext.PowerShellInstance;
     ResourceUri = resourceUri;
     ComputerName = computerName;
     PSCredential = credential;
     PSCertificateThumbprint = certificateThumbprint;
     PSAuthentication = authenticationMechanism;
     PSUseSsl = useSsl;
     PSPort = port;
     PSSessionOption = sessionOption;
     Session = session;
     SessionOptions = cimSessionOptions;
     if (moduleDefinition != null)
     {
         // Creating a script block forces the string into the compiled script cache so we
         // don't need to reparse it at execution time. Locking the static _moduleDefinition is not
         // required since the operation is idempotent.
         _moduleScriptBlock = ScriptBlock.Create(moduleDefinition);
         _moduleDefinition = moduleDefinition;
     }
 }
 internal RunCommandsArguments(ActivityParameters activityParameters, PSDataCollection <PSObject> output, PSDataCollection <PSObject> input, PSActivityContext psActivityContext, PSWorkflowHost workflowHost, bool runInProc, Dictionary <string, object> parameterDefaults, Type activityType, PrepareSessionDelegate prepareSession, object activityObject, ActivityImplementationContext implementationContext)
 {
     this.ActivityParameters = activityParameters;
     this.Output             = output;
     this.Input                 = input;
     this.PSActivityContext     = psActivityContext;
     this.ParameterDefaults     = parameterDefaults;
     this.ActivityType          = activityType;
     this.Delegate              = prepareSession;
     this.ActivityObject        = activityObject;
     this.WorkflowHost          = workflowHost;
     this.ImplementationContext = implementationContext;
     this.CommandExecutionType  = RunCommandsArguments.DetermineCommandExecutionType(implementationContext.ConnectionInfo, runInProc, activityType, psActivityContext);
 }
Example #15
0
		private static void PopulatePSComputerName(ActivityImplementationContext implementationContext, NativeActivityContext context, PSActivityArgumentInfo field, int index)
		{
			PropertyInfo property = implementationContext.GetType().GetProperty(field.Name);
			string[] strArrays = (string[])field.Value.Get(context);
			string[] strArrays1 = new string[1];
			strArrays1[0] = strArrays[index];
			property.SetValue(implementationContext, strArrays1, null);
		}
Example #16
0
		private void PopulateActivityImplementationContext(ActivityImplementationContext implementationContext, NativeActivityContext context, int index)
		{
			foreach (PSActivityArgumentInfo activityArgument in this.GetActivityArguments())
			{
				PropertyInfo property = implementationContext.GetType().GetProperty(activityArgument.Name);
				if (property != null)
				{
					if (!string.Equals(activityArgument.Name, "PSComputerName", StringComparison.OrdinalIgnoreCase) || index == -1)
					{
						property.SetValue(implementationContext, activityArgument.Value.Get(context), null);
					}
					else
					{
						PSActivity.PopulatePSComputerName(implementationContext, context, activityArgument, index);
					}
				}
				else
				{
					throw new Exception(string.Concat("Could not find corresponding task context field for activity argument: ", activityArgument.Name));
				}
			}
		}
Example #17
0
		private static void InitializeCmdletInstanceParameters(Command command, PSObject wrappedCmdlet, bool isGenericCim, PSActivityContext psActivityContext, CimSessionOptions cimSessionOptions, ActivityImplementationContext implementationContext)
		{
			PSActivity.PSActivity variable = new PSActivity.PSActivity();
			variable.cimSessionOptions = cimSessionOptions;
			bool flag = false;
			foreach (CommandParameter parameter in command.Parameters)
			{
				if (PSActivity._commonCommandParameters.Contains(parameter.Name))
				{
					continue;
				}
				if (parameter.Name.Equals("CimSession"))
				{
					flag = true;
				}
				if (wrappedCmdlet.Properties[parameter.Name] == null)
				{
					wrappedCmdlet.Properties.Add(new PSNoteProperty(parameter.Name, parameter.Value));
				}
				else
				{
					wrappedCmdlet.Properties[parameter.Name].Value = parameter.Value;
				}
			}
			string[] item = null;
			variable.cimActivityImplementationContext = implementationContext as CimActivityImplementationContext;
			if (variable.cimActivityImplementationContext == null || string.IsNullOrEmpty(variable.cimActivityImplementationContext.ComputerName))
			{
				if (psActivityContext.ParameterDefaults.ContainsKey("PSComputerName"))
				{
					item = psActivityContext.ParameterDefaults["PSComputerName"] as string[];
				}
			}
			else
			{
				string[] computerName = new string[1];
				computerName[0] = variable.cimActivityImplementationContext.ComputerName;
				item = computerName;
			}
			if (item != null && (int)item.Length > 0)
			{
				if (!isGenericCim || wrappedCmdlet.Properties["CimSession"] == null)
				{
					if (wrappedCmdlet.Properties["ComputerName"] == null)
					{
						wrappedCmdlet.Properties.Add(new PSNoteProperty("ComputerName", item));
					}
				}
				else
				{
					if (!flag)
					{
						if (variable.cimActivityImplementationContext != null)
						{
							bool value = false;
							bool? pSUseSsl = variable.cimActivityImplementationContext.PSUseSsl;
							if (pSUseSsl.HasValue)
							{
								bool? nullable = variable.cimActivityImplementationContext.PSUseSsl;
								value = nullable.Value;
							}
							uint num = 0;
							uint? pSPort = variable.cimActivityImplementationContext.PSPort;
							if (pSPort.HasValue)
							{
								uint? pSPort1 = variable.cimActivityImplementationContext.PSPort;
								num = pSPort1.Value;
							}
							AuthenticationMechanism authenticationMechanism = AuthenticationMechanism.Default;
							AuthenticationMechanism? pSAuthentication = variable.cimActivityImplementationContext.PSAuthentication;
							if (pSAuthentication.HasValue)
							{
								AuthenticationMechanism? pSAuthentication1 = variable.cimActivityImplementationContext.PSAuthentication;
								authenticationMechanism = pSAuthentication1.Value;
							}
							List<CimSession> cimSessions = item.ToList<string>().ConvertAll<CimSession>((string computer) => CimConnectionManager.GetGlobalCimConnectionManager().GetSession(computer, LambdaVar9.PSCredential, LambdaVar9.PSCertificateThumbprint, authenticationMechanism, cimSessionOptions, value, num, LambdaVar9.PSSessionOption));
							wrappedCmdlet.Properties["CimSession"].Value = cimSessions.ToArray<CimSession>();
							variable.cimActivityImplementationContext.Session = cimSessions[0];
							return;
						}
						else
						{
							throw new ArgumentException(Resources.InvalidImplementationContext);
						}
					}
				}
			}
		}
Example #18
0
		private static void InitializeActivityEnvironmentAndAddRequiredModules(ActivityImplementationContext implementationContext, ActivityParameters activityParameters)
		{
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				if (implementationContext.PSActivityEnvironment == null)
				{
					implementationContext.PSActivityEnvironment = new PSActivityEnvironment();
				}
				PSActivityEnvironment pSActivityEnvironment = implementationContext.PSActivityEnvironment;
				string[] pSRequiredModules = activityParameters.PSRequiredModules;
				string[] strArrays = pSRequiredModules;
				if (pSRequiredModules == null)
				{
					strArrays = new string[0];
				}
				string[] strArrays1 = strArrays;
				for (int i = 0; i < (int)strArrays1.Length; i++)
				{
					string str = strArrays1[i];
					traceSource.WriteMessage(string.Concat("Adding dependent module to policy: ", str));
					pSActivityEnvironment.Modules.Add(str);
				}
			}
		}
Example #19
0
		private static bool HandleFailure(int attempts, uint? retryCount, uint? retryInterval, ActivityImplementationContext implementationContext, string errorId, Exception e, PSActivityContext psActivityContext)
		{
			bool flag = false;
			if ((long)attempts <= (ulong)retryCount.GetValueOrDefault(0))
			{
				if (e != null)
				{
					PSActivity.WriteError(e, errorId, ErrorCategory.InvalidResult, implementationContext.PowerShellInstance.Runspace.ConnectionInfo, psActivityContext);
				}
				if (!psActivityContext.IsCanceled)
				{
					flag = true;
				}
				for (int i = 0; (long)i < (ulong)retryInterval.GetValueOrDefault(1) && !PSActivity.CheckForCancel(psActivityContext); i++)
				{
					Thread.Sleep(0x3e8);
				}
			}
			else
			{
				if (implementationContext.PSComputerName == null || (int)implementationContext.PSComputerName.Length <= 1)
				{
					if (e != null)
					{
						lock (psActivityContext.exceptions)
						{
							psActivityContext.exceptions.Add(e);
						}
					}
				}
				else
				{
					if (e != null)
					{
						PSActivity.WriteError(e, errorId, ErrorCategory.InvalidResult, implementationContext.PowerShellInstance.Runspace.ConnectionInfo, psActivityContext);
					}
				}
			}
			return flag;
		}
Example #20
0
        /// <summary>
        /// Adds the PSActivity variable to the active runspace, which is of type InlineScriptContext.
        /// </summary>
        /// <param name="implementationContext">The ActivityImplementationContext returned by the call to GetCommand.</param>
        protected override void PrepareSession(ActivityImplementationContext implementationContext)
        {
            if (implementationContext.PSActivityEnvironment == null)
            {
                implementationContext.PSActivityEnvironment = new PSActivityEnvironment();
            }

            // Update the preference variables
            UpdatePreferenceVariables(implementationContext);
            System.Management.Automation.PowerShell session = implementationContext.PowerShellInstance;

            implementationContext.PSActivityEnvironment.Variables["UserName"] = System.Environment.UserName;

            string computerName = null;
            if (implementationContext.ConnectionInfo != null)
            {
                computerName = implementationContext.ConnectionInfo.ComputerName;
            }
            if (string.IsNullOrEmpty(computerName))
            {
                computerName = "localhost";
            }

            implementationContext.PSActivityEnvironment.Variables["ComputerName"] = computerName;
            implementationContext.PSActivityEnvironment.Variables["PSComputerName"] = computerName;

            string workflowCommandName = null;

            Dictionary<string, object> activityVariables = (Dictionary<string, object>)implementationContext.WorkflowContext;
            if (activityVariables != null && activityVariables.ContainsKey("ParameterDefaults"))
            {
                HostParameterDefaults defaults = activityVariables["ParameterDefaults"] as HostParameterDefaults;
                if (defaults != null)
                {
                    workflowCommandName = defaults.Parameters["WorkflowCommandName"] as string;
                }
            }

            if (string.IsNullOrEmpty(workflowCommandName))
            {
                workflowCommandName = "unknown";
            }

            implementationContext.PSActivityEnvironment.Variables["CommandName"] = workflowCommandName;

            // Populate the default variables
            InlineScriptContext inlineScriptContext = new InlineScriptContext(this);

            // Populate the activity variables
            foreach (KeyValuePair<string, object> entry in activityVariables)
            {
                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    System.Diagnostics.Debug.Assert(entry.Value is HostParameterDefaults, "ParameterDefaults does not contain a HostParameterDefaults object");
                    inlineScriptContext.Variables[entry.Key] = ((HostParameterDefaults)entry.Value).Parameters;
                    continue;
                }
                inlineScriptContext.Variables[entry.Key] = entry.Value;
            }

            // Set the PowerShell session variables...            
            foreach (KeyValuePair<string, object> entry in activityVariables)
            {
                var value = entry.Value;

                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                    continue;
                implementationContext.PSActivityEnvironment.Variables[entry.Key] = value;
            }
        }
Example #21
0
		private void PopulateRunspaceFromContext(ActivityImplementationContext implementationContext, PSActivityContext activityContext, NativeActivityContext context)
		{
			if (implementationContext.PowerShellInstance != null)
			{
				PropertyDescriptorCollection properties = context.DataContext.GetProperties();
				foreach (PropertyDescriptor property in properties)
				{
					string name = property.Name;
					object value = property.GetValue(context.DataContext);
					if (value == null)
					{
						continue;
					}
					object item = value;
					PSDataCollection<PSObject> pSObjects = value as PSDataCollection<PSObject>;
					if (pSObjects != null && pSObjects.Count == 1)
					{
						item = pSObjects[0];
					}
					activityContext.UserVariables.Add(name, item);
				}
			}
		}
Example #22
0
        protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context)
        {
            string empty;
            string str;
            string empty1;
            string str1;

            typeof(GenericCimCmdletActivity).IsAssignableFrom(base.GetType());
            string[]     strArrays       = this.PSComputerName.Get(context);
            CimSession[] cimSessionArray = this.CimSession.Get(context);
            Uri          uri             = null;

            if (this.ResourceUri != null)
            {
                uri = this.ResourceUri.Get(context);
            }
            List <ActivityImplementationContext> activityImplementationContexts = new List <ActivityImplementationContext>();

            if (strArrays == null || (int)strArrays.Length <= 0)
            {
                ActivityImplementationContext    powerShell = this.GetPowerShell(context);
                CimActivityImplementationContext cimActivityImplementationContext = new CimActivityImplementationContext(powerShell, null, null, null, new AuthenticationMechanism?(AuthenticationMechanism.Default), false, 0, null, null, null, this.ModuleDefinition, uri);
                activityImplementationContexts.Add(cimActivityImplementationContext);
            }
            else
            {
                WSManSessionOptions wSManSessionOption = new WSManSessionOptions();
                uint?nullable = base.PSActionRunningTimeoutSec.Get(context);
                if (nullable.HasValue)
                {
                    wSManSessionOption.Timeout = TimeSpan.FromSeconds((double)((float)nullable.Value));
                }
                bool?nullable1 = this.PSUseSsl.Get(context);
                bool value     = false;
                if (nullable1.HasValue)
                {
                    wSManSessionOption.UseSsl = nullable1.Value;
                    value = nullable1.Value;
                }
                uint?nullable2 = this.PSPort.Get(context);
                uint num       = 0;
                if (nullable2.HasValue)
                {
                    wSManSessionOption.DestinationPort = nullable2.Value;
                    num = nullable2.Value;
                }
                PSSessionOption pSSessionOption = this.PSSessionOption.Get(context);
                if (pSSessionOption != null)
                {
                    wSManSessionOption.NoEncryption        = pSSessionOption.NoEncryption;
                    wSManSessionOption.CertCACheck         = pSSessionOption.SkipCACheck;
                    wSManSessionOption.CertCNCheck         = pSSessionOption.SkipCNCheck;
                    wSManSessionOption.CertRevocationCheck = pSSessionOption.SkipRevocationCheck;
                    if (pSSessionOption.UseUTF16)
                    {
                        wSManSessionOption.PacketEncoding = PacketEncoding.Utf16;
                    }
                    if (pSSessionOption.Culture != null)
                    {
                        wSManSessionOption.Culture = pSSessionOption.Culture;
                    }
                    if (pSSessionOption.UICulture != null)
                    {
                        wSManSessionOption.UICulture = pSSessionOption.UICulture;
                    }
                    if (pSSessionOption.ProxyCredential != null)
                    {
                        char[] chrArray = new char[1];
                        chrArray[0] = '\\';
                        string[] strArrays1 = pSSessionOption.ProxyCredential.UserName.Split(chrArray);
                        if ((int)strArrays1.Length >= 2)
                        {
                            empty = strArrays1[0];
                            str   = strArrays1[1];
                        }
                        else
                        {
                            empty = string.Empty;
                            str   = strArrays1[0];
                        }
                        wSManSessionOption.AddProxyCredentials(new CimCredential(PSGeneratedCIMActivity.ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(pSSessionOption.ProxyAuthentication), empty, str, pSSessionOption.ProxyCredential.Password));
                    }
                    ProxyAccessType proxyAccessType = pSSessionOption.ProxyAccessType;
                    if (proxyAccessType == ProxyAccessType.IEConfig)
                    {
                        wSManSessionOption.ProxyType = ProxyType.InternetExplorer;
                        goto Label0;
                    }
                    else if (proxyAccessType == ProxyAccessType.WinHttpConfig)
                    {
                        wSManSessionOption.ProxyType = ProxyType.WinHttp;
                        goto Label0;
                    }
                    else if (proxyAccessType == (ProxyAccessType.IEConfig | ProxyAccessType.WinHttpConfig))
                    {
                        goto Label0;
                    }
                    else if (proxyAccessType == ProxyAccessType.AutoDetect)
                    {
                        wSManSessionOption.ProxyType = ProxyType.Auto;
                        goto Label0;
                    }
                }
Label0:
                PSCredential pSCredential = this.PSCredential.Get(context);
                string str2 = this.PSCertificateThumbprint.Get(context);
                if (pSCredential == null || str2 == null)
                {
                    PasswordAuthenticationMechanism cimPasswordAuthenticationMechanism = PasswordAuthenticationMechanism.Default;
                    AuthenticationMechanism?        nullable3 = this.PSAuthentication.Get(context);
                    if (nullable3.HasValue)
                    {
                        cimPasswordAuthenticationMechanism = PSGeneratedCIMActivity.ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(nullable3.Value);
                    }
                    if (str2 != null)
                    {
                        wSManSessionOption.AddDestinationCredentials(new CimCredential(CertificateAuthenticationMechanism.Default, str2));
                    }
                    if (pSCredential != null)
                    {
                        char[] chrArray1 = new char[1];
                        chrArray1[0] = '\\';
                        string[] strArrays2 = pSCredential.UserName.Split(chrArray1);
                        if ((int)strArrays2.Length >= 2)
                        {
                            empty1 = strArrays2[0];
                            str1   = strArrays2[1];
                        }
                        else
                        {
                            empty1 = string.Empty;
                            str1   = strArrays2[0];
                        }
                        wSManSessionOption.AddDestinationCredentials(new CimCredential(cimPasswordAuthenticationMechanism, empty1, str1, pSCredential.Password));
                    }
                    if (cimSessionArray == null || (int)cimSessionArray.Length <= 0)
                    {
                        string[] strArrays3 = strArrays;
                        for (int i = 0; i < (int)strArrays3.Length; i++)
                        {
                            string str3 = strArrays3[i];
                            ActivityImplementationContext    activityImplementationContext     = this.GetPowerShell(context);
                            CimActivityImplementationContext cimActivityImplementationContext1 = new CimActivityImplementationContext(activityImplementationContext, str3, pSCredential, str2, nullable3, value, num, pSSessionOption, null, wSManSessionOption, this.ModuleDefinition, uri);
                            activityImplementationContexts.Add(cimActivityImplementationContext1);
                        }
                    }
                    else
                    {
                        CimSession[] cimSessionArray1 = cimSessionArray;
                        for (int j = 0; j < (int)cimSessionArray1.Length; j++)
                        {
                            CimSession cimSession = cimSessionArray1[j];
                            ActivityImplementationContext    powerShell1 = this.GetPowerShell(context);
                            CimActivityImplementationContext cimActivityImplementationContext2 = new CimActivityImplementationContext(powerShell1, cimSession.ComputerName, pSCredential, str2, nullable3, value, num, pSSessionOption, cimSession, wSManSessionOption, this.ModuleDefinition, uri);
                            activityImplementationContexts.Add(cimActivityImplementationContext2);
                        }
                    }
                }
                else
                {
                    throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithPSCertificateThumbPrint);
                }
            }
            return(activityImplementationContexts);
        }
Example #23
0
        protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context)
        {
            bool needRunspace = !typeof(GenericCimCmdletActivity).IsAssignableFrom(this.GetType());

            string[]     computernames = PSComputerName.Get(context);
            CimSession[] sessions      = this.CimSession.Get(context);
            Uri          resourceUri   = null;

            if (ResourceUri != null)
            {
                resourceUri = ResourceUri.Get(context);
            }

            List <ActivityImplementationContext> commands = new List <ActivityImplementationContext>();

            // Configure the remote connectivity options...
            if (computernames != null && computernames.Length > 0)
            {
                WSManSessionOptions sessionOptions = new WSManSessionOptions();

                // Set a timeout on the connection...
                uint?timeout = PSActionRunningTimeoutSec.Get(context);
                if (timeout.HasValue)
                {
                    sessionOptions.Timeout = TimeSpan.FromSeconds((double)(timeout.Value));
                }

                // See if we should use SSL or not...
                bool?useSsl = PSUseSsl.Get(context);
                bool sessionOptionUseSsl = false;

                if (useSsl.HasValue)
                {
                    sessionOptions.UseSsl = useSsl.Value;
                    sessionOptionUseSsl   = useSsl.Value;
                }

                // Set the port to use
                uint?port = PSPort.Get(context);
                uint sessionOptionPort = 0;

                if (port.HasValue)
                {
                    sessionOptions.DestinationPort = port.Value;
                    sessionOptionPort = port.Value;
                }

                // Map over options from PSSessionConfig to WSManSessionOptions
                PSSessionOption pso = PSSessionOption.Get(context);
                if (pso != null)
                {
                    sessionOptions.NoEncryption        = pso.NoEncryption;
                    sessionOptions.CertCACheck         = pso.SkipCACheck;
                    sessionOptions.CertCNCheck         = pso.SkipCNCheck;
                    sessionOptions.CertRevocationCheck = pso.SkipRevocationCheck;

                    if (pso.UseUTF16)
                    {
                        sessionOptions.PacketEncoding = PacketEncoding.Utf16;
                    }

                    if (pso.Culture != null)
                    {
                        sessionOptions.Culture = pso.Culture;
                    }

                    if (pso.UICulture != null)
                    {
                        sessionOptions.UICulture = pso.UICulture;
                    }

                    if (pso.ProxyCredential != null)
                    {
                        string[] parts = pso.ProxyCredential.UserName.Split('\\');
                        string   domain, userid;
                        if (parts.Length < 2)
                        {
                            domain = string.Empty;
                            userid = parts[0];
                        }
                        else
                        {
                            domain = parts[0];
                            userid = parts[1];
                        }

                        sessionOptions.AddProxyCredentials(
                            new CimCredential(ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(pso.ProxyAuthentication),
                                              domain, userid, pso.ProxyCredential.Password));
                    }

                    switch (pso.ProxyAccessType)
                    {
                    case ProxyAccessType.WinHttpConfig:
                        sessionOptions.ProxyType = ProxyType.WinHttp;
                        break;

                    case ProxyAccessType.AutoDetect:
                        sessionOptions.ProxyType = ProxyType.Auto;
                        break;

                    case ProxyAccessType.IEConfig:
                        sessionOptions.ProxyType = ProxyType.InternetExplorer;
                        break;
                    }
                }

                PSCredential pscreds = PSCredential.Get(context);
                string       certificateThumbprint = PSCertificateThumbprint.Get(context);

                if (pscreds != null && certificateThumbprint != null)
                {
                    throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithPSCertificateThumbPrint);
                }

                PasswordAuthenticationMechanism passwordAuthenticationMechanism = PasswordAuthenticationMechanism.Default;
                AuthenticationMechanism?        authenticationMechanism         = PSAuthentication.Get(context);

                if (authenticationMechanism.HasValue)
                {
                    passwordAuthenticationMechanism = ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(authenticationMechanism.Value);
                }


                if (certificateThumbprint != null)
                {
                    sessionOptions.AddDestinationCredentials(new CimCredential(CertificateAuthenticationMechanism.Default, certificateThumbprint));
                }

                if (pscreds != null)
                {
                    string[] parts = pscreds.UserName.Split('\\');
                    string   domain, userid;
                    if (parts.Length < 2)
                    {
                        domain = string.Empty;
                        userid = parts[0];
                    }
                    else
                    {
                        domain = parts[0];
                        userid = parts[1];
                    }

                    sessionOptions.AddDestinationCredentials(new CimCredential(passwordAuthenticationMechanism, domain, userid, pscreds.Password));
                }

                // Create the PowerShell instance, and add the script to it.
                if (sessions != null && sessions.Length > 0)
                {
                    foreach (CimSession session in sessions)
                    {
                        ActivityImplementationContext configuredCommand = GetPowerShell(context);

                        CimActivityImplementationContext activityImplementationContext =
                            new CimActivityImplementationContext(
                                configuredCommand,
                                session.ComputerName,
                                pscreds,
                                certificateThumbprint,
                                authenticationMechanism,
                                sessionOptionUseSsl,
                                sessionOptionPort,
                                pso,
                                session,
                                sessionOptions,
                                ModuleDefinition,
                                resourceUri);

                        commands.Add(activityImplementationContext);
                        //if (needRunspace)
                        //    GetRunspaceForCimCmdlet(context, activityImplementationContext);
                    }
                }
                else if (this.PSCommandName.Equals("CimCmdlets\\New-CimSession", StringComparison.OrdinalIgnoreCase))
                {
                    // NewCimSession activity is a special one as it creates the required sessions based on number of computers specified in one go.

                    ActivityImplementationContext baseContext = GetPowerShell(context);

                    CimActivityImplementationContext activityImplementationContext =
                        new CimActivityImplementationContext(baseContext,
                                                             null,     // ComputerName
                                                             pscreds,
                                                             certificateThumbprint,
                                                             authenticationMechanism,
                                                             sessionOptionUseSsl,
                                                             sessionOptionPort,
                                                             pso,
                                                             null,    // session
                                                             sessionOptions,
                                                             ModuleDefinition,
                                                             resourceUri);

                    commands.Add(activityImplementationContext);
                }
                else
                {
                    foreach (string computer in computernames)
                    {
                        ActivityImplementationContext baseContext = GetPowerShell(context);

                        CimActivityImplementationContext activityImplementationContext =
                            new CimActivityImplementationContext(baseContext,
                                                                 computer,
                                                                 pscreds,
                                                                 certificateThumbprint,
                                                                 authenticationMechanism,
                                                                 sessionOptionUseSsl,
                                                                 sessionOptionPort,
                                                                 pso,
                                                                 null, // session
                                                                 sessionOptions,
                                                                 ModuleDefinition,
                                                                 resourceUri);

                        commands.Add(activityImplementationContext);
                    }
                }
            }
            // Configure the local invocation options
            else
            {
                // Create the PowerShell instance, and add the script to it.
                ActivityImplementationContext    baseContext = GetPowerShell(context);
                CimActivityImplementationContext activityImplementationContext =
                    new CimActivityImplementationContext(baseContext,
                                                         null,  // ComputerName
                                                         null,  // Credential
                                                         null,  // CertificateThumbprint
                                                         AuthenticationMechanism.Default,
                                                         false, // UseSsl
                                                         0,     // Port
                                                         null,  // PSSessionOption
                                                         null,  // Session
                                                         null,  // CimSessionOptions
                                                         ModuleDefinition,
                                                         resourceUri);

                commands.Add(activityImplementationContext);
            }

            return(commands);
        }
Example #24
0
		protected virtual void PrepareSession(ActivityImplementationContext implementationContext)
		{
		}
Example #25
0
		internal RunCommandsArguments(ActivityParameters activityParameters, PSDataCollection<PSObject> output, PSDataCollection<PSObject> input, PSActivityContext psActivityContext, PSWorkflowHost workflowHost, bool runInProc, Dictionary<string, object> parameterDefaults, Type activityType, PrepareSessionDelegate prepareSession, object activityObject, ActivityImplementationContext implementationContext)
		{
			this.ActivityParameters = activityParameters;
			this.Output = output;
			this.Input = input;
			this.PSActivityContext = psActivityContext;
			this.ParameterDefaults = parameterDefaults;
			this.ActivityType = activityType;
			this.Delegate = prepareSession;
			this.ActivityObject = activityObject;
			this.WorkflowHost = workflowHost;
			this.ImplementationContext = implementationContext;
			this.CommandExecutionType = RunCommandsArguments.DetermineCommandExecutionType(implementationContext.ConnectionInfo, runInProc, activityType, psActivityContext);
		}
Example #26
0
		private static void RunDirectExecutionActivity(System.Management.Automation.PowerShell commandToRun, PSDataCollection<PSObject> input, PSDataCollection<PSObject> output, PSActivityContext psActivityContext, ActivityImplementationContext implementationContext)
		{
			PSDataCollection<PSObject> pSObjects;
			Type type;
			CimSessionOptions sessionOptions;
			Command item = commandToRun.Commands.Commands[0];
			string commandText = item.CommandText;
			Cmdlet invokeWmiMethod = null;
			bool flag = false;
			if (!string.Equals(commandText, "Get-WMIObject", StringComparison.OrdinalIgnoreCase))
			{
				if (string.Equals(commandText, "Invoke-WMIMethod", StringComparison.OrdinalIgnoreCase))
				{
					invokeWmiMethod = new InvokeWmiMethod();
					flag = true;
				}
			}
			else
			{
				invokeWmiMethod = new GetWmiObjectCommand();
			}
			if (!PSActivity.CheckForCancel(psActivityContext))
			{
				if (output != null)
				{
					pSObjects = output;
				}
				else
				{
					pSObjects = new PSDataCollection<PSObject>();
				}
				ActivityImplementationContext activityImplementationContext = implementationContext;
				if (invokeWmiMethod != null)
				{
					type = invokeWmiMethod.GetType();
				}
				else
				{
					type = psActivityContext.TypeImplementingCmdlet;
				}
				DirectExecutionActivitiesCommandRuntime directExecutionActivitiesCommandRuntime = new DirectExecutionActivitiesCommandRuntime(pSObjects, activityImplementationContext, type);
				directExecutionActivitiesCommandRuntime.Error = commandToRun.Streams.Error;
				directExecutionActivitiesCommandRuntime.Warning = commandToRun.Streams.Warning;
				directExecutionActivitiesCommandRuntime.Progress = commandToRun.Streams.Progress;
				directExecutionActivitiesCommandRuntime.Verbose = commandToRun.Streams.Verbose;
				directExecutionActivitiesCommandRuntime.Debug = commandToRun.Streams.Debug;
				if (invokeWmiMethod == null)
				{
					CimActivityImplementationContext cimActivityImplementationContext = implementationContext as CimActivityImplementationContext;
					if (cimActivityImplementationContext != null)
					{
						sessionOptions = cimActivityImplementationContext.SessionOptions;
					}
					else
					{
						sessionOptions = null;
					}
					CimSessionOptions cimSessionOption = sessionOptions;
					if (psActivityContext.TypeImplementingCmdlet != null)
					{
						if (input == null || input.Count <= 0 && !input.IsOpen)
						{
							CimBaseCommand cimBaseCommand = (CimBaseCommand)Activator.CreateInstance(psActivityContext.TypeImplementingCmdlet);
							using (cimBaseCommand)
							{
								cimBaseCommand.CommandRuntime = directExecutionActivitiesCommandRuntime;
								PSObject pSObject = PSObject.AsPSObject(cimBaseCommand);
								PSActivity.InitializeCmdletInstanceParameters(item, pSObject, true, psActivityContext, cimSessionOption, implementationContext);
								cimBaseCommand.Invoke().GetEnumerator().MoveNext();
							}
						}
						else
						{
							if (psActivityContext.TypeImplementingCmdlet.GetProperty("InputObject") != null)
							{
								foreach (PSObject pSObject1 in input)
								{
									try
									{
										CimBaseCommand cimBaseCommand1 = (CimBaseCommand)Activator.CreateInstance(psActivityContext.TypeImplementingCmdlet);
										using (cimBaseCommand1)
										{
											cimBaseCommand1.CommandRuntime = directExecutionActivitiesCommandRuntime;
											CimInstance cimInstance = LanguagePrimitives.ConvertTo<CimInstance>(pSObject1);
											PSObject pSObject2 = PSObject.AsPSObject(cimBaseCommand1);
											PSActivity.InitializeCmdletInstanceParameters(item, pSObject2, true, psActivityContext, cimSessionOption, implementationContext);
											PSPropertyInfo pSPropertyInfo = pSObject2.Properties["InputObject"];
											pSPropertyInfo.Value = cimInstance;
											cimBaseCommand1.Invoke().GetEnumerator().MoveNext();
										}
									}
									catch (PSInvalidCastException pSInvalidCastException1)
									{
										PSInvalidCastException pSInvalidCastException = pSInvalidCastException1;
										if (pSInvalidCastException.ErrorRecord != null)
										{
											directExecutionActivitiesCommandRuntime.Error.Add(pSInvalidCastException.ErrorRecord);
										}
									}
									if (!PSActivity.CheckForCancel(psActivityContext))
									{
										continue;
									}
									return;
								}
							}
							else
							{
								object[] objArray = new object[1];
								objArray[0] = commandText;
								throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, Resources.CmdletDoesNotImplementInputObjectProperty, objArray));
							}
						}
					}
					else
					{
						throw new InvalidOperationException(commandText);
					}
				}
				else
				{
					invokeWmiMethod.CommandRuntime = directExecutionActivitiesCommandRuntime;
					PSObject pSObject3 = PSObject.AsPSObject(invokeWmiMethod);
					PSActivity.InitializeCmdletInstanceParameters(item, pSObject3, false, psActivityContext, null, implementationContext);
					if (!flag || input == null || input.Count <= 0 && !input.IsOpen)
					{
						invokeWmiMethod.Invoke().GetEnumerator().MoveNext();
						return;
					}
					else
					{
						InvokeWmiMethod invokeWmiMethod1 = invokeWmiMethod as InvokeWmiMethod;
						foreach (PSObject pSObject4 in input)
						{
							try
							{
								ManagementObject managementObject = LanguagePrimitives.ConvertTo<ManagementObject>(pSObject4);
								invokeWmiMethod1.InputObject = managementObject;
								invokeWmiMethod1.Invoke().GetEnumerator().MoveNext();
							}
							catch (PSInvalidCastException pSInvalidCastException3)
							{
								PSInvalidCastException pSInvalidCastException2 = pSInvalidCastException3;
								if (pSInvalidCastException2.ErrorRecord != null)
								{
									directExecutionActivitiesCommandRuntime.Error.Add(pSInvalidCastException2.ErrorRecord);
								}
							}
							if (!PSActivity.CheckForCancel(psActivityContext))
							{
								continue;
							}
							return;
						}
					}
				}
				return;
			}
			else
			{
				return;
			}
		}
 public DirectExecutionActivitiesCommandRuntime(PSDataCollection <PSObject> output, ActivityImplementationContext implementationContext, Type cmdletType)
 {
     if (output != null)
     {
         if (implementationContext != null)
         {
             if (cmdletType != null)
             {
                 this._output = output;
                 this._implementationContext = implementationContext;
                 this._cmdletType            = cmdletType;
                 return;
             }
             else
             {
                 throw new ArgumentNullException("cmdletType");
             }
         }
         else
         {
             throw new ArgumentNullException("implementationContext");
         }
     }
     else
     {
         throw new ArgumentNullException("output");
     }
 }
Example #28
0
		protected internal void UpdateImplementationContextForLocalExecution(ActivityImplementationContext implementationContext, ActivityContext context)
		{
		}
Example #29
0
        public void Cancel()
        {
            ActivityImplementationContext activityImplementationContext = null;
            IAsyncResult asyncResult = null;

            if (this.WorkflowHost != null)
            {
                if (this.commandQueue != null)
                {
                    while (!this.commandQueue.IsEmpty)
                    {
                        bool flag = this.commandQueue.TryDequeue(out activityImplementationContext);
                        if (!flag)
                        {
                            continue;
                        }
                        PowerShell powerShellInstance = activityImplementationContext.PowerShellInstance;
                        object[]   objArray           = new object[1];
                        objArray[0] = powerShellInstance;
                        this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "PowerShell activity: Cancelling pending command {0}.", objArray));
                        powerShellInstance.Dispose();
                    }
                }
                PSResumableActivityHostController pSActivityHostController = this.WorkflowHost.PSActivityHostController as PSResumableActivityHostController;
                if (pSActivityHostController == null)
                {
                    PSOutOfProcessActivityController pSOutOfProcessActivityController = this.WorkflowHost.PSActivityHostController as PSOutOfProcessActivityController;
                    if (pSOutOfProcessActivityController != null)
                    {
                        while (this.AsyncResults.Count > 0)
                        {
                            this.AsyncResults.TryDequeue(out asyncResult);
                            pSOutOfProcessActivityController.CancelInvokePowerShell(asyncResult);
                        }
                    }
                }
                else
                {
                    pSActivityHostController.StopAllResumablePSCommands(this.JobInstanceId);
                }
                while (this.runningCommands.Count > 0)
                {
                    PowerShell powerShell = null;
                    lock (this.runningCommands)
                    {
                        Dictionary <PowerShell, RetryCount> .KeyCollection.Enumerator enumerator = this.runningCommands.Keys.GetEnumerator();
                        try
                        {
                            if (enumerator.MoveNext())
                            {
                                PowerShell current = enumerator.Current;
                                powerShell = current;
                            }
                        }
                        finally
                        {
                            enumerator.Dispose();
                        }
                        if (powerShell == null)
                        {
                            break;
                        }
                    }
                    if (powerShell.InvocationStateInfo.State == PSInvocationState.Running)
                    {
                        object[] objArray1 = new object[1];
                        objArray1[0] = powerShell;
                        this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "PowerShell activity: Stopping command {0}.", objArray1));
                        try
                        {
                            powerShell.Stop();
                        }
                        catch (NullReferenceException nullReferenceException)
                        {
                        }
                        catch (InvalidOperationException invalidOperationException)
                        {
                        }
                    }
                    if (powerShell.InvocationStateInfo.State != PSInvocationState.Completed || powerShell.HadErrors)
                    {
                        this.Failed = true;
                    }
                    int num = RunCommandsArguments.DetermineCommandExecutionType(powerShell.Runspace.ConnectionInfo as WSManConnectionInfo, this.RunInProc, this.ActivityType, this);
                    if (num != 1)
                    {
                        PSActivity.CloseRunspaceAndDisposeCommand(powerShell, this.WorkflowHost, this, num);
                    }
                    this.runningCommands.Remove(powerShell);
                }
                return;
            }
            else
            {
                throw new InvalidOperationException("WorkflowHost");
            }
        }
Example #30
0
		private static void UpdatePowerShell(ActivityImplementationContext implementationContext, PSActivityContext psActivityContext, Type ActivityType, PrepareSessionDelegate PrepareSession, object activityObject)
		{
			try
			{
				PrepareSession(implementationContext);
				PowerShell powerShellInstance = implementationContext.PowerShellInstance;
				if (implementationContext.PSError != null)
				{
					powerShellInstance.Streams.Error = implementationContext.PSError;
				}
				if (implementationContext.PSProgress != null)
				{
					powerShellInstance.Streams.Progress = implementationContext.PSProgress;
				}
				if (implementationContext.PSVerbose != null)
				{
					powerShellInstance.Streams.Verbose = implementationContext.PSVerbose;
				}
				if (implementationContext.PSDebug != null)
				{
					powerShellInstance.Streams.Debug = implementationContext.PSDebug;
				}
				if (implementationContext.PSWarning != null)
				{
					powerShellInstance.Streams.Warning = implementationContext.PSWarning;
				}
				PSActivity pSActivity = activityObject as PSActivity;
				if (pSActivity.UpdatePreferenceVariable)
				{
					PSActivity.UpdatePreferenceVariables(implementationContext);
				}
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				lock (psActivityContext.exceptions)
				{
					psActivityContext.exceptions.Add(exception);
				}
			}
		}