public void AysncAddCommand(string command, string arg, IDictionary paramss, int pindex = 0)
 {
     if (ps != null)
     {
         ps.AddCommand(command);
         ps.AddArgument(arg);
         ps.AddParameters(paramss);
     }
 }
        public static Task <PSDataCollection <PSObject> > InvokeAsync(this Runspace runspace, string script, IDictionary scriptParameters = null, Action <PSDataStreams> psDataStreamAction = null)
        {
            if (script == null)
            {
                throw new ArgumentOutOfRangeException("script");
            }

            if (runspace == null)
            {
                throw new ArgumentOutOfRangeException("runspace");
            }

            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
            {
                ps.Runspace = runspace;
                ps.AddScript(script);

                if (scriptParameters != null && scriptParameters.Count > 0)
                {
                    ps.AddParameters(scriptParameters);
                }

                psDataStreamAction?.Invoke(ps.Streams);

                return(ps.InvokeAsync());
            }
        }
예제 #3
0
 private Collection <PSObject> InvokeCommand(string cmdLet, Dictionary <string, object> parameters)
 {
     powerShell.Commands.Clear();
     powerShell.AddCommand(cmdLet, false);
     if (parameters != null)
     {
         powerShell.AddParameters(parameters);
     }
     return(powerShell.Invoke());
 }
예제 #4
0
        public override Collection <PSObject> Run(bool debug)
        {
            Collection <PSObject> result = null;

            runspace.Open();
            for (int i = 0; i < cmdlets.Count; i++)
            {
                using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
                {
                    powershell.Runspace = runspace;

                    powershell.AddCommand(cmdlets[i].name);
                    if (cmdlets[i].parameters.Count > 0)
                    {
                        var paramDictionary = new Dictionary <string, object>();
                        foreach (CmdletParam cmdletparam in cmdlets[i].parameters)
                        {
                            paramDictionary.Add(cmdletparam.name, cmdletparam.value);
                        }
                        powershell.AddParameters(paramDictionary);
                    }

                    if (debug)
                    {
                        powershell.AddParameter("Debug");
                    }

                    PrintPSCommand(powershell);

                    result = powershell.Invoke();

                    if (debug)
                    {
                        Console.WriteLine(string.Join("", powershell.Streams.Debug));
                    }

                    if (powershell.Streams.Error.Count > 0)
                    {
                        runspace.Close();
                        var exceptions = new List <Exception>();
                        foreach (ErrorRecord error in powershell.Streams.Error)
                        {
                            exceptions.Add(new Exception(error.Exception.Message));
                        }

                        throw new AggregateException(exceptions);
                    }
                }
            }
            runspace.Close();

            return(result);
        }
예제 #5
0
        public Collection <PSObject> RunPipeline()
        {
            Collection <PSObject> result = null;

            runspace.Open();
            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
            {
                powershell.Runspace = runspace;
                for (int i = 0; i < cmdlets.Count; i++)
                {
                    powershell.AddCommand(cmdlets[i].name);
                    if (cmdlets[i].parameters.Count > 0)
                    {
                        Dictionary <string, object> paramDictionary = new Dictionary <string, object>();
                        foreach (CmdletParam cmdletparam in cmdlets[i].parameters)
                        {
                            paramDictionary.Add(cmdletparam.name, cmdletparam.value);
                        }
                        powershell.AddParameters(paramDictionary);
                    }
                }
                result = powershell.Invoke();

                if (powershell.Streams.Error.Count > 0)
                {
                    runspace.Close();
                    List <Exception> exceptions = new List <Exception>();
                    foreach (ErrorRecord error in powershell.Streams.Error)
                    {
                        exceptions.Add(new Exception(error.Exception.Message));
                    }

                    throw new AggregateException(exceptions);
                }
            }
            runspace.Close();

            return(result);
        }
예제 #6
0
        private void ConvertCommand(CommandAst commandAst, bool isTrustedInput)
        {
            // First need command name.
            var commandName = GetCommandName(commandAst.CommandElements[0], isTrustedInput);

            var command = new Command(commandName, isScript: false, useLocalScope: _createLocalScope);

            // Handle redirections, if any (there can really be just 0 or 1).
            if (commandAst.Redirections.Count > 0)
            {
                Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported");
                Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type");

                PipelineResultTypes toType = PipelineResultTypes.Output;
                PipelineResultTypes fromType;
                switch (commandAst.Redirections[0].FromStream)
                {
                case RedirectionStream.Error:
                    fromType = PipelineResultTypes.Error;
                    break;

                case RedirectionStream.Warning:
                    fromType = PipelineResultTypes.Warning;
                    break;

                case RedirectionStream.Verbose:
                    fromType = PipelineResultTypes.Verbose;
                    break;

                case RedirectionStream.Debug:
                    fromType = PipelineResultTypes.Debug;
                    break;

                case RedirectionStream.Information:
                    fromType = PipelineResultTypes.Information;
                    break;

                case RedirectionStream.All:
                    fromType = PipelineResultTypes.All;
                    break;

                default:
                    // Default to Error->Output to be compatible with V2.
                    fromType = PipelineResultTypes.Error;
                    break;
                }

                command.MergeMyResults(fromType, toType);
            }

            _powershell.AddCommand(command);

            // Now the parameters and arguments.
            foreach (var ast in commandAst.CommandElements.Skip(1))
            {
                var exprAst = ast as ExpressionAst;
                if (exprAst != null)
                {
                    VariableExpressionAst variableAst = null;

                    var usingExprAst = ast as UsingExpressionAst;
                    if (usingExprAst != null)
                    {
                        string usingAstKey = PsUtils.GetUsingExpressionKey(usingExprAst);
                        object usingValue  = _usingValueMap[usingAstKey];
                        variableAst = usingExprAst.SubExpression as VariableExpressionAst;
                        if (variableAst != null && variableAst.Splatted)
                        {
                            // Support the splatting of a dictionary
                            var parameters = usingValue as System.Collections.IDictionary;
                            if (parameters != null)
                            {
                                _powershell.AddParameters(parameters);
                            }
                            else
                            {
                                // Support the splatting of an array
                                var arguments = usingValue as System.Collections.IEnumerable;
                                if (arguments != null)
                                {
                                    foreach (object argument in arguments)
                                    {
                                        _powershell.AddArgument(argument);
                                    }
                                }
                                else
                                {
                                    // Splat the object directly.
                                    _powershell.AddArgument(usingValue);
                                }
                            }
                        }
                        else
                        {
                            _powershell.AddArgument(usingValue);
                        }

                        continue;
                    }

                    variableAst = ast as VariableExpressionAst;
                    if (variableAst != null && variableAst.Splatted)
                    {
                        GetSplattedVariable(variableAst);
                    }
                    else
                    {
                        var    constantExprAst = ast as ConstantExpressionAst;
                        object argument;
                        if (constantExprAst != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType)))
                        {
                            var commandArgumentText = constantExprAst.Extent.Text;
                            argument = constantExprAst.Value;
                            if (!commandArgumentText.Equals(constantExprAst.Value.ToString(), StringComparison.Ordinal))
                            {
                                // The wrapped number will actually return a PSObject which could end holding a reference to
                                // a typetable, making the object runspace specific.  We should find a better way to avoid
                                // any possibility of sharing problems, though this is unlikely to cause problems.
                                argument = ParserOps.WrappedNumber(argument, commandArgumentText);
                            }
                        }
                        else
                        {
                            if (!isTrustedInput)
                            {
                                try
                                {
                                    argument = GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell);
                                }
                                catch (System.Exception)
                                {
                                    throw new ScriptBlockToPowerShellNotSupportedException(
                                              "CantConvertWithDynamicExpression",
                                              null,
                                              AutomationExceptions.CantConvertWithDynamicExpression,
                                              exprAst.Extent.Text);
                                }
                            }
                            else
                            {
                                argument = GetExpressionValue(exprAst, isTrustedInput);
                            }
                        }

                        _powershell.AddArgument(argument);
                    }
                }
                else
                {
                    AddParameter((CommandParameterAst)ast, isTrustedInput);
                }
            }
        }
예제 #7
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);
        }