Inheritance: MonoBehaviour
        public void ScriptBlockIsImmutable(InlineScriptSource[] oldInlineScriptSources, InlineScriptSource newInlineScriptSource)
        {
            var old = new ScriptBlock(oldInlineScriptSources);
            var @new = old.AppendScript(newInlineScriptSource);

            Assert.NotSame(@new, old);
        }
        public void ScriptBlockAppendsScript(InlineScriptSource[] oldInlineScriptSources, InlineScriptSource newInlineScriptSource)
        {
            var sut = new ScriptBlock(oldInlineScriptSources)
                .AppendScript(newInlineScriptSource);

            var expected = oldInlineScriptSources.Concat(new[] {newInlineScriptSource});

            Assert.Equal(expected, sut.Scripts);
        }
        public void ScriptRunnerCorrectlyConvertsMultipleScripts([Frozen] IScriptEngine engine, ScriptRunner sut, InlineScriptSource[] sources)
        {
            var scriptBlock = new ScriptBlock(sources);

            var expected = sources.Select(s => new Script(s.Name, s.ScriptText));

            sut.RunScripts(scriptBlock);

            Mock.Get(engine).Verify(x => x.Execute(It.Is<IEnumerable<Script>>(actual => actual.EnumerableEquals(expected))));
        }
        public void RunScripts(ScriptBlock scriptBlock)
        {
            _scripts.Clear();

            foreach (var scriptSource in scriptBlock.Scripts)
            {
                scriptSource.Accept(this);
            }

            _scriptEngine.Execute(_scripts);
        }
Example #5
0
        /// <summary>
        /// Processes the process phase of the cmdlet
        /// </summary>
        protected override void ProcessRecord()
        {
            #region Perform Transforms
            if ((!_fromStopFunction) && (Target != null))
            {
                Target = ResolveTarget(Target);
            }

            if (!_fromStopFunction)
            {
                if (Exception != null)
                {
                    Exception = ResolveException(Exception);
                }
                else if (ErrorRecord != null)
                {
                    Exception tempException = null;
                    for (int n = 0; n < ErrorRecord.Length; n++)
                    {
                        // If both Exception and ErrorRecord are specified, override the first error record's exception.
                        if ((n == 0) && (Exception != null))
                        {
                            tempException = Exception;
                        }
                        else
                        {
                            tempException = ResolveException(ErrorRecord[n].Exception);
                        }
                        if (tempException != ErrorRecord[n].Exception)
                        {
                            ErrorRecord[n] = new ErrorRecord(tempException, ErrorRecord[n].FullyQualifiedErrorId, ErrorRecord[n].CategoryInfo.Category, ErrorRecord[n].TargetObject);
                        }
                    }
                }
            }

            if (Level != MessageLevel.Warning)
            {
                Level = ResolveLevel(Level);
            }
            #endregion Perform Transforms

            #region Exception Integration

            /*
             *  While conclusive error handling must happen after message handling,
             *  in order to integrate the exception message into the actual message,
             *  it becomes necessary to first integrate the exception and error record parameters into a uniform view
             *
             *  Note: Stop-PSFFunction never specifies this parameter, thus it is not necessary to check,
             *  whether this function was called from Stop-PSFFunction.
             */
            if ((ErrorRecord == null) && (Exception != null))
            {
                ErrorRecord    = new ErrorRecord[1];
                ErrorRecord[0] = new ErrorRecord(Exception, String.Format("{0}_{1}", ModuleName, FunctionName), ErrorCategory.NotSpecified, Target);
            }
            #endregion Exception Integration

            #region Error handling
            if (ErrorRecord != null)
            {
                if (!_fromStopFunction)
                {
                    if (EnableException)
                    {
                        foreach (ErrorRecord record in ErrorRecord)
                        {
                            WriteError(record);
                        }
                    }
                }

                LogHost.WriteErrorEntry(ErrorRecord, FunctionName, ModuleName, _Tags, _timestamp, _MessageSystem, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId, Environment.MachineName);
            }
            #endregion Error handling

            LogEntryType channels = LogEntryType.None;

            #region Warning handling
            if (Level == MessageLevel.Warning)
            {
                if (!_silent)
                {
                    if (!String.IsNullOrEmpty(Once))
                    {
                        string onceName = String.Format("MessageOnce.{0}.{1}", FunctionName, Once).ToLower();
                        if (!(Configuration.ConfigurationHost.Configurations.ContainsKey(onceName) && (bool)Configuration.ConfigurationHost.Configurations[onceName].Value))
                        {
                            WriteWarning(_MessageStreams);
                            channels = channels | LogEntryType.Warning;

                            Configuration.Config cfg = new Configuration.Config();
                            cfg.Module      = "messageonce";
                            cfg.Name        = String.Format("{0}.{1}", FunctionName, Once).ToLower();
                            cfg.Hidden      = true;
                            cfg.Description = "Locking setting that disables further display of the specified message";
                            cfg.Value       = true;

                            Configuration.ConfigurationHost.Configurations[onceName] = cfg;
                        }
                    }
                    else
                    {
                        WriteWarning(_MessageStreams);
                        channels = channels | LogEntryType.Warning;
                    }
                }
                WriteDebug(_MessageStreams);
                channels = channels | LogEntryType.Debug;
            }
            #endregion Warning handling

            #region Message handling
            if (!_silent)
            {
                if ((MessageHost.MaximumInformation >= (int)Level) && (MessageHost.MinimumInformation <= (int)Level))
                {
                    if (!String.IsNullOrEmpty(Once))
                    {
                        string onceName = String.Format("MessageOnce.{0}.{1}", FunctionName, Once).ToLower();
                        if (!(Configuration.ConfigurationHost.Configurations.ContainsKey(onceName) && (bool)Configuration.ConfigurationHost.Configurations[onceName].Value))
                        {
                            InvokeCommand.InvokeScript(false, ScriptBlock.Create(_writeHostScript), null, _MessageHost);
                            channels = channels | LogEntryType.Information;

                            Configuration.Config cfg = new Configuration.Config();
                            cfg.Module      = "messageonce";
                            cfg.Name        = String.Format("{0}.{1}", FunctionName, Once).ToLower();
                            cfg.Hidden      = true;
                            cfg.Description = "Locking setting that disables further display of the specified message";
                            cfg.Value       = true;

                            Configuration.ConfigurationHost.Configurations[onceName] = cfg;
                        }
                    }
                    else
                    {
                        //InvokeCommand.InvokeScript(_writeHostScript, _MessageHost);
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(_writeHostScript), null, _MessageHost);
                        channels = channels | LogEntryType.Information;
                    }
                }
            }

            if ((MessageHost.MaximumVerbose >= (int)Level) && (MessageHost.MinimumVerbose <= (int)Level))
            {
                if ((_callStack.Count() > 1) && _callStack.ElementAt(_callStack.Count() - 2).InvocationInfo.BoundParameters.ContainsKey("Verbose"))
                {
                    InvokeCommand.InvokeScript(@"$VerbosePreference = 'Continue'");
                }
                //SessionState.PSVariable.Set("VerbosePreference", ActionPreference.Continue);

                WriteVerbose(_MessageStreams);
                channels = channels | LogEntryType.Verbose;
            }

            if ((MessageHost.MaximumDebug >= (int)Level) && (MessageHost.MinimumDebug <= (int)Level))
            {
                bool restoreInquire = false;
                if (_isDebug)
                {
                    if (Breakpoint.ToBool())
                    {
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Inquire'"), null, null);
                    }
                    else
                    {
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Continue'"), null, null);
                        restoreInquire = true;
                    }
                    WriteDebug(String.Format("{0} | {1}", Line, _MessageStreams));
                    channels = channels | LogEntryType.Debug;
                }
                else
                {
                    WriteDebug(_MessageStreams);
                    channels = channels | LogEntryType.Debug;
                }

                if (restoreInquire)
                {
                    InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Inquire'"), null, null);
                }
            }
            #endregion Message handling

            #region Logging
            LogEntry entry = LogHost.WriteLogEntry(_MessageSystem, channels, _timestamp, FunctionName, ModuleName, _Tags, Level, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId, Environment.MachineName, File, Line, _callStack, String.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName), Target);
            #endregion Logging

            foreach (MessageEventSubscription subscription in MessageHost.Events.Values)
            {
                if (subscription.Applies(entry))
                {
                    try { InvokeCommand.InvokeScript(subscription.ScriptBlock.ToString(), entry); }
                    catch (Exception e) { WriteError(new ErrorRecord(e, "", ErrorCategory.NotSpecified, entry)); }
                }
            }
        }
Example #6
0
 public static IEnumerable <T> RunScript <T>(this EngineIntrinsics engineIntrinsics, ScriptBlock block)
 => PsHelpers.RunScript <T>(engineIntrinsics.InvokeCommand, block.ToString());
Example #7
0
 public static IEnumerable <T> RunScript <T>(this PSCmdlet cmdlet, ScriptBlock block)
 => PsHelpers.RunScript <T>(cmdlet.InvokeCommand, block.ToString());
Example #8
0
 /// <summary>
 /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
 /// </summary>
 /// 
 /// <param name="name">
 /// The name of the configuration.
 /// </param>
 /// 
 /// <param name="configuration">
 /// The ScriptBlock for the configuration
 /// </param>
 /// 
 /// <param name="options">
 /// The options to set on the function. Note, Constant can only be set at creation time.
 /// </param>
 /// 
 /// <param name="context">
 /// The execution context for the configuration.
 /// </param>
 /// 
 /// <param name="helpFile">
 /// The help file for the configuration.
 /// </param>
 /// 
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="configuration"/> is null.
 /// </exception>
 /// 
 internal ConfigurationInfo(string name, ScriptBlock configuration, ScopedItemOptions options, ExecutionContext context, string helpFile)
     : this(name, configuration, options, context, helpFile, false)
 {
 }
Example #9
0
 /// <summary>
 /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
 /// </summary>
 /// 
 /// <param name="name">
 /// The name of the configuration.
 /// </param>
 /// 
 /// <param name="configuration">
 /// The ScriptBlock for the configuration
 /// </param>
 /// 
 /// <param name="context">
 /// The ExecutionContext for the configuration.
 /// </param>
 /// 
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="configuration"/> is null.
 /// </exception>
 /// 
 internal ConfigurationInfo(string name, ScriptBlock configuration, ExecutionContext context) : this(name, configuration, context, null)
 {
 }
Example #10
0
 /// <summary>
 /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
 /// </summary>
 /// 
 /// <param name="name">
 /// The name of the configuration.
 /// </param>
 /// 
 /// <param name="configuration">
 /// The ScriptBlock for the configuration
 /// </param>
 /// 
 /// <param name="options">
 /// The options to set on the function. Note, Constant can only be set at creation time.
 /// </param>
 /// 
 /// <param name="context">
 /// The execution context for the configuration.
 /// </param>
 /// 
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="configuration"/> is null.
 /// </exception>
 /// 
 internal ConfigurationInfo(string name, ScriptBlock configuration, ScopedItemOptions options, ExecutionContext context) : this(name, configuration, options, context, null)
 {
 }
Example #11
0
        /// <summary>
        /// Sets the function of the specified name to the specified value
        /// </summary>
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        /// <param name="value">
        /// The new value for the function.
        /// </param>
        /// <param name="writeItem">
        /// If true, the item that was set should be written to WriteItemObject.
        /// </param>
#pragma warning disable 0162
        internal override void SetSessionStateItem(string name, object value, bool writeItem)
        {
            Dbg.Diagnostics.Assert(
                !String.IsNullOrEmpty(name),
                "The caller should verify this parameter");

            FunctionProviderDynamicParameters dynamicParameters =
                DynamicParameters as FunctionProviderDynamicParameters;

            CommandInfo modifiedItem = null;

            bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet;

            if (value == null)
            {
                // If the value wasn't specified but the options were, just set the
                // options on the existing function.
                // If the options weren't specified, then remove the function

                if (dynamicParametersSpecified)
                {
                    modifiedItem = (CommandInfo)GetSessionStateItem(name);

                    if (modifiedItem != null)
                    {
                        SetOptions(modifiedItem, dynamicParameters.Options);
                    }
                }
                else
                {
                    RemoveSessionStateItem(name);
                }
            }
            else
            {
                do // false loop
                {
                    // Unwrap the PSObject before binding it as a scriptblock...
                    PSObject pso = value as PSObject;
                    if (pso != null)
                    {
                        value = pso.BaseObject;
                    }

                    ScriptBlock scriptBlockValue = value as ScriptBlock;
                    if (scriptBlockValue != null)
                    {
                        if (dynamicParametersSpecified)
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlockValue,
                                                                             null, dynamicParameters.Options, Force, Context.Origin);
                        }
                        else
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlockValue, null, Force, Context.Origin);
                        }
                        break;
                    }

                    FunctionInfo function = value as FunctionInfo;
                    if (function != null)
                    {
                        ScopedItemOptions options = function.Options;

                        if (dynamicParametersSpecified)
                        {
                            options = dynamicParameters.Options;
                        }

                        modifiedItem = SessionState.Internal.SetFunction(name, function.ScriptBlock, function, options, Force, Context.Origin);
                        break;
                    }

                    string stringValue = value as string;
                    if (stringValue != null)
                    {
                        ScriptBlock scriptBlock = ScriptBlock.Create(Context.ExecutionContext, stringValue);

                        if (dynamicParametersSpecified)
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlock, null, dynamicParameters.Options, Force, Context.Origin);
                        }
                        else
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlock, null, Force, Context.Origin);
                        }
                        break;
                    }

                    throw PSTraceSource.NewArgumentException("value");
                } while (false);

                if (writeItem && modifiedItem != null)
                {
                    WriteItemObject(modifiedItem, modifiedItem.Name, false);
                }
            }
        }
Example #12
0
 private static bool ArbitraryFilter(NtProcess proc, ScriptBlock filter)
 {
     return(filter.InvokeWithArg(false, proc));
 }
Example #13
0
        private static MulticastDelegate CreateDelegate(ScriptBlock scriptBlock, Closure sourceClosure, Type delegateType)
        {
            var sb = Expression.Constant(scriptBlock, typeof(ScriptBlock));
            var sourceClosureExpr = Expression.Constant(sourceClosure, typeof(Closure));

            var closure      = Expression.Variable(typeof(Closure));
            var invokeResult = Expression.Variable(typeof(object));
            var variables    = new List <ParameterExpression> {
                closure, invokeResult
            };

            MethodInfo invokeMethod = delegateType.GetMethod(nameof(Action.Invoke));

            ParameterInfo[]       parameters = invokeMethod.GetParameters();
            ParameterExpression[] parameterExprs;
            Expression[]          convertedParameters;
            Type[] delegateTypes;
            Type   returnType = invokeMethod.ReturnType;

            if (parameters.Length > 0)
            {
                convertedParameters = new Expression[parameters.Length];
                parameterExprs      = new ParameterExpression[parameters.Length];
                delegateTypes       = new Type[parameters.Length + 1];
                for (var i = 0; i < parameters.Length; i++)
                {
                    var parameter = Expression.Parameter(parameters[i].ParameterType, parameters[i].Name);
                    parameterExprs[i]      = parameter;
                    convertedParameters[i] = Expression.Convert(parameter, typeof(object));
                    // Expression.Convert(

                    // typeof(object));

                    delegateTypes[i] = parameters[i].ParameterType;
                }

                delegateTypes[parameters.Length] = invokeMethod.ReturnType;
            }
            else
            {
                parameterExprs      = Array.Empty <ParameterExpression>();
                convertedParameters = Array.Empty <Expression>();
                delegateTypes       = new[] { invokeMethod.ReturnType };
            }

            var body = new List <Expression>
            {
                Expression.Assign(
                    closure,
                    Expression.Call(
                        sourceClosureExpr,
                        typeof(Closure).GetMethod(nameof(Closure.Clone), BindingFlags.Instance | BindingFlags.NonPublic),
                        Expression.NewArrayInit(typeof(object), convertedParameters))),

                Expression.Assign(
                    invokeResult,
                    Expression.Call(
                        Expression.Field(closure, typeof(Closure).GetField(nameof(Closure.ScriptBlock))),
                        typeof(ScriptBlock).GetMethod(nameof(ScriptBlock.InvokeReturnAsIs)),
                        Expression.NewArrayInit(typeof(object), Expression.Convert(closure, typeof(object)))))
            };

            if (returnType == typeof(void))
            {
                body.Add(Expression.Empty());
            }
            else
            {
                var convertedResult = Expression.Variable(returnType);
                variables.Add(convertedResult);
                body.Add(
                    Expression.Condition(
                        Expression.Call(
                            typeof(LanguagePrimitives),
                            nameof(LanguagePrimitives.TryConvertTo),
                            new[] { returnType },
                            invokeResult,
                            convertedResult),
                        convertedResult,
                        Expression.Default(returnType)));
            }

            return((MulticastDelegate)Expression.Lambda(
                       Expression.GetDelegateType(delegateTypes),
                       Expression.Block(
                           returnType,
                           variables,
                           body),
                       parameterExprs)
                   .Compile());
        }
Example #14
0
 public static Func <object, object, object, object, object, object, object, object, object, object, object, object, object, object> CreateTridecenaryFunction(ScriptBlock script)
 {
     return((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13) => {
         return script.Invoke(null, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
     });
 }
Example #15
0
 public static Func <object> CreateNullaryFunction(ScriptBlock script)
 {
     return(() => {
         return script.Invoke(null);
     });
 }
Example #16
0
 public static Func <object, object, object, object, object, object, object, object, object> CreateOctonaryFunction(ScriptBlock script)
 {
     return((arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) => {
         return script.Invoke(null, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
     });
 }
Example #17
0
 public static Func <object, object, object, object, object, object> CreateQuinaryFunction(ScriptBlock script)
 {
     return((arg1, arg2, arg3, arg4, arg5) => {
         return script.Invoke(null, arg1, arg2, arg3, arg4, arg5);
     });
 }
Example #18
0
        /// <summary>
        /// The expression will be executed in the remote computer if a
        /// remote runspace parameter or computer name is specified. If
        /// none other than command parameter is specified, then it
        /// just executes the command locally without creating a new
        /// remote runspace object.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (ParameterSetName == DefinitionNameParameterSet)
            {
                // Get the Job2 object from the Job Manager for this definition name and start the job.
                string resolvedPath = null;
                if (!string.IsNullOrEmpty(_definitionPath))
                {
                    ProviderInfo provider = null;
                    System.Collections.ObjectModel.Collection <string> paths =
                        this.Context.SessionState.Path.GetResolvedProviderPathFromPSPath(_definitionPath, out provider);

                    // Only file system paths are allowed.
                    if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotFSProvider,
                                                           _definitionName,
                                                           _definitionPath,
                                                           provider.FullName);
                        WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotFileSystemProvider",
                                                   ErrorCategory.InvalidArgument, null));

                        return;
                    }

                    // Only a single file path is allowed.
                    if (paths.Count != 1)
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotSingle,
                                                           _definitionName,
                                                           _definitionPath);
                        WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotSingle",
                                                   ErrorCategory.InvalidArgument, null));

                        return;
                    }

                    resolvedPath = paths[0];
                }
                List <Job2> jobs = JobManager.GetJobToStart(_definitionName, resolvedPath, _definitionType, this, false);

                if (jobs.Count == 0)
                {
                    string message = (_definitionType != null) ?
                                     StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound2, _definitionType, _definitionName) :
                                     StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound1, _definitionName);

                    WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameNotFound",
                                               ErrorCategory.ObjectNotFound, null));

                    return;
                }

                if (jobs.Count > 1)
                {
                    string message = StringUtil.Format(RemotingErrorIdStrings.StartJobManyDefNameMatches, _definitionName);
                    WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameMoreThanOneMatch",
                                               ErrorCategory.InvalidResult, null));

                    return;
                }

                // Start job.
                Job2 job = jobs[0];
                job.StartJob();

                // Write job object to host.
                WriteObject(job);

                return;
            }

            if (_firstProcessRecord)
            {
                _firstProcessRecord = false;

                PSRemotingJob job = new PSRemotingJob(ResolvedComputerNames, Operations,
                                                      ScriptBlock.ToString(), ThrottleLimit, _name);

                job.PSJobTypeName = s_startJobType;

                this.JobRepository.Add(job);
                WriteObject(job);
            }

            // inject input
            if (InputObject != AutomationNull.Value)
            {
                foreach (IThrottleOperation operation in Operations)
                {
                    ExecutionCmdletHelper helper = (ExecutionCmdletHelper)operation;
                    helper.Pipeline.Input.Write(InputObject);
                }
            }
        } // ProcessRecord
Example #19
0
 public WPFJob(string name, string command, ScriptBlock scriptBlock, InitialSessionState initalSessionState) : base(command, name)
 {
     this.initialSessionState = initalSessionState;
     Start(scriptBlock, new Hashtable());
 }
Example #20
0
 public ScriptBlock FailingScriptBlockTest(ScriptBlock scripts)
 {
     return scripts.AppendFile("simpleTests.js")
         .AppendInlineScript("failingTest();");
 }
        /// <summary>
        /// Adds an inline script block to the page.
        /// </summary>
        /// <param name="key">A unique identifier for the script block.</param>
        /// <param name="script">The JavaScript code to include in the Page.</param>
        public ScriptBlock Block(string key, Action script)
        {
            ScriptBlock block;
            if (!_blocks.TryGetValue(key, out block))
            {
                block = new ScriptBlock(this);
                _blocks[key] = block;
            }
            if (script != null)
                block.Append(script);

            return block;
        }
        private static ScriptBlock GetScript(string filePath)
        {
            var scriptText = string.Format(Resources.FileContentCompletion, filePath?.Replace("\"", "\"\""));

            return(ScriptBlock.Create(scriptText));
        }
Example #23
0
        } // FilterInfo ctor

        /// <summary>
        /// Creates an instance of the FilterInfo class with the specified name and ScriptBlock
        /// </summary>
        /// 
        /// <param name="name">
        /// The name of the filter.
        /// </param>
        /// 
        /// <param name="filter">
        /// The ScriptBlock for the filter
        /// </param>
        /// 
        /// <param name="options">
        /// The options to set on the function. Note, Constant can only be set at creation time.
        /// </param>
        /// 
        /// <param name="context">
        /// The execution context for the filter.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="filter"/> is null.
        /// </exception>
        /// 
        internal FilterInfo(string name, ScriptBlock filter, ScopedItemOptions options, ExecutionContext context) : this(name, filter, options, context, null)
        {
        } // FilterInfo ctor
Example #24
0
 /// <exception cref="ParseException"></exception>
 internal void VerifyScriptBlockText(string scriptText)
 {
     ScriptBlock.Create(scriptText);
 }
Example #25
0
        private static void LoadScriptBlock(Level level, ScriptDef targetSD, XmlNode node, ScriptBlock root, string firstChildName = "")
        {
            if (node == null || root == null) {
                return;
            }

            var child = node.FirstChild;
            if (child == null) {
                return;
            }

            do {
                if (!firstChildName.Equals("")) {
                    if (!child.Name.Equals(firstChildName, StringComparison.InvariantCultureIgnoreCase)) {
                        Log.WriteInfo("Attention ! Impossible d'ajouter le scriptBlock : " + child.Name + " alors que le scriptBlock obligatoire est : " + firstChildName);
                        continue;
                    }
                }

                ScriptBlock scriptBlock = null;

                switch (child.Name.ToLower()) {
                    case "action": {
                            var a = child.Attributes?["a"];
                            if (a == null)
                                throw new Exception(" le scriptBlock <action> ne contient pas d'action \"a\" !");
                            var p = child.Attributes?["p"];
                            if (p == null)
                                throw new Exception(" le scriptBlock <action> ne contient pas de paramètres ! \"p\" ");

                            var parameters = new List<string>();

                            var i = 1;

                            do {
                                parameters.Add(p.Value);
                                ++i;
                            } while ((p = child.Attributes?["p" + i]) != null);

                            scriptBlock = new ScriptAction(level, a.Value, parameters);
                        }
                        break;

                    case "update": {
                            var delayA = child.Attributes?["delay"];
                            if (delayA == null)
                                throw new Exception(" le scriptBlock <update> ne contient pas de delay");

                            double delay = 0.0;
                            if (delayA.Value.Equals("$FRAME_RATE")) {
                                delay = 1.0 / 60.0;
                            }
                            else {
                                if (!double.TryParse(delayA.Value, out delay))
                                    throw new Exception(" le scriptBlock <update> ne contient pas de delay valide !");
                                if (delay <= 0)
                                    throw new Exception(" le scriptBlock <update> ne contient pas un delay valide ! Il est plus petit ou égal à 0 !");
                            }
                            scriptBlock = new ScriptUpdate(delay);
                            LoadScriptBlock(level, targetSD, child, scriptBlock);
                        }
                        break;
                    case "condition": {
                            var varRefA = child.Attributes?["ref"];
                            var valueConditionA = child.Attributes?["value"];

                            if (varRefA == null || valueConditionA == null)
                                throw new Exception(" le scriptBlock <condition> ne contient pas la référence vers la variable ou sa condition \"ref\" ou \"value\" !");

                            if (!targetSD.Variables.ContainsKey(varRefA.Value))
                                throw new Exception(" le scriptBlock <condition> utilise la variable : " + varRefA.Value + " alors qu'elle n'est pas définie dans <variables> !");

                            var variable = targetSD.Variables[varRefA.Value];

                            if (variable is int) {
                                if (!int.TryParse(valueConditionA.Value, out var condition)) {
                                    throw new Exception(" dans le scriptBlock <condition>, la condition utilisée ne peut pas être convertie en nombre (int) !");
                                }
                                scriptBlock = new ScriptCondition<int>(varRefA.Value, condition);
                            }
                            else if (variable is bool) {
                                if (!bool.TryParse(valueConditionA.Value, out var condition)) {
                                    throw new Exception(" dans le scriptBlock <condition>, la condition utilisée ne peut pas être convertie en booléen (bool) !");
                                }
                                scriptBlock = new ScriptCondition<bool>(varRefA.Value, condition);
                            }
                            else
                                throw new Exception(" le scriptBlock <condition> utilise une variable dont le type est inconnu !");

                            LoadScriptBlock(level, targetSD, child, scriptBlock);
                        }
                        break;
                    case "collision": {
                            var dirSide = child.Attributes?["side"];
                            var typeRef = child.Attributes?["typeRef"];
                            if (dirSide == null || typeRef == null)
                                throw new Exception(" le scriptBlock <collision> ne contient pas la direction \"side\" ou la référence \"typeRef\" !");

                            var sides = new List<PhysicsBody.CollisionSide>();

                            var rawSides = dirSide.Value.Split('|');

                            foreach (var rawSide in rawSides) {
                                if (!Enum.TryParse<PhysicsBody.CollisionSide>(rawSide, out var side))
                                    throw new Exception(" le scriptBlock <collision> contient une erreur ! Impossible de convertir : " + dirSide.Value + " en direction !");
                                sides.Add(side);
                            }

                            scriptBlock = new ScriptCollisionEvent(sides, typeRef.Value);
                            LoadScriptBlock(level, targetSD, child, scriptBlock);
                        }
                        break;
                    case "key": {
                            var codeA = child.Attributes?["code"];
                            var justPressedA = child.Attributes?["justPressed"];
                            var upA = child.Attributes?["up"];

                            if (codeA == null)
                                throw new Exception(" le scriptBlock <key> ne contient pas la touche \"code\"");

                            if (!Enum.TryParse<Keyboard.Key>(codeA.Value, true, out var key)) {
                                throw new Exception(" le scriptBlock <key> contient une touche qui n'existe pas ! : " + codeA.Value);
                            }

                            bool justPressed = false, up = false;

                            if (justPressedA != null) {
                                if (!bool.TryParse(justPressedA.Value, out justPressed))
                                    throw new Exception(" le scriptBlock <key> contient des erreurs ! Impossible de convertir : " + justPressedA.Value + " en valeur booléenne !");
                            }

                            if (upA != null) {
                                if (!bool.TryParse(upA.Value, out up))
                                    throw new Exception(" le scriptBlock <key> contient des erreurs ! Impossible de convertir : " + upA.Value + " en valeur booléenne !");
                            }

                            scriptBlock = new ScriptInput(key, justPressed, up);
                            LoadScriptBlock(level, targetSD, child, scriptBlock);
                        }
                        break;
                }

                if (scriptBlock == null)
                    throw new Exception(" le script contient un scriptBlock inconnu !");

                root.AddChild(scriptBlock);

            } while ((child = child.NextSibling) != null);
        }
Example #26
0
 public override void ResumeJob()
 {
     ScriptBlock.Create("$args[0] | Resume-PrintJob -ComputerName $args[1]").Invoke(_source, ComputerName);
 }
Example #27
0
        private IEnumerable <Field> GetFieldsFromParamBlock()
        {
            var paramBlock = (ParamBlockAst)Endpoint.Ast.Find(m => m is ParamBlockAst, false);
            var fields     = new List <Field>();

            if (paramBlock == null)
            {
                return(fields);
            }

            foreach (var parameter in paramBlock.Parameters)
            {
                var parameterAttribute   = parameter.Attributes.OfType <AttributeAst>().FirstOrDefault(m => m.TypeName.Name == "Parameter");
                var validateSetAttribute = parameter.Attributes.OfType <AttributeAst>().FirstOrDefault(m => m.TypeName.Name == "ValidateSet");
                var stringConstant       = parameterAttribute?.NamedArguments?.FirstOrDefault(m => m.ArgumentName.Equals("HelpMessage", StringComparison.OrdinalIgnoreCase))?.Argument as StringConstantExpressionAst;

                var field = new Field();

                if (Validate)
                {
                    var validateErrorMessageAttribute = parameter.Attributes.OfType <AttributeAst>().FirstOrDefault(m => m.TypeName.Name.Equals("UniversalDashboard.ValidationErrorMessage", StringComparison.OrdinalIgnoreCase));
                    var validateErrorMessage          = validateErrorMessageAttribute?.PositionalArguments.FirstOrDefault() as StringConstantExpressionAst;
                    var mandatoryProperty             = parameterAttribute?.NamedArguments?.FirstOrDefault(m => m.ArgumentName.Equals("Mandatory", StringComparison.OrdinalIgnoreCase))?.Argument;
                    var isMandatory = (bool?)mandatoryProperty?.SafeGetValue() == true;

                    var endpoint = new Endpoint(ScriptBlock.Create($"param({parameter.ToString()})"));
                    endpoint.Name      = Guid.NewGuid().ToString();
                    endpoint.SessionId = SessionId;

                    var hostState = this.GetHostState();
                    hostState.EndpointService.Register(endpoint);

                    field.Required               = isMandatory;
                    field.Endpoint               = endpoint;
                    field.ValidationEndpoint     = endpoint.Name;
                    field.ValidationErrorMessage = validateErrorMessage?.Value;
                }

                var placeholder = stringConstant?.Value;
                if (placeholder != null)
                {
                    field.Placeholder = new string[] { placeholder }
                }
                ;

                field.Name = parameter.Name.VariablePath.ToString();

                if (parameter.StaticType == typeof(bool) || parameter.StaticType == typeof(SwitchParameter))
                {
                    field.Type       = FieldTypes.Checkbox;
                    field.Value      = "false";
                    field.DotNetType = parameter.StaticType.FullName;
                }
                else if (parameter.StaticType.IsEnum)
                {
                    field.Type         = FieldTypes.Select;
                    field.ValidOptions = Enum.GetNames(parameter.StaticType);
                    field.DotNetType   = parameter.StaticType.FullName;
                    field.Value        = Enum.GetValues(parameter.StaticType).GetValue(0)?.ToString();
                }
                else if (parameter.StaticType == typeof(DateTime))
                {
                    field.Type       = FieldTypes.Date;
                    field.DotNetType = parameter.StaticType.FullName;
                }
                else if (parameter.StaticType == typeof(SecureString))
                {
                    field.Type       = FieldTypes.Password;
                    field.DotNetType = parameter.StaticType.FullName;
                }
                else if (parameter.StaticType == typeof(String[]))
                {
                    field.Type       = FieldTypes.Textarea;
                    field.DotNetType = parameter.StaticType.FullName;
                }
                else
                {
                    field.Type       = FieldTypes.Textbox;
                    field.DotNetType = typeof(string).FullName;

                    if (validateSetAttribute != null)
                    {
                        field.ValidOptions = validateSetAttribute?.PositionalArguments.OfType <StringConstantExpressionAst>().Select(m => m.Value).ToArray();
                        field.Type         = FieldTypes.Select;
                        field.Value        = field.ValidOptions[0]?.ToString();
                    }
                }

                fields.Add(field);
            }
            return(fields);
        }
Example #28
0
 public override void SuspendJob()
 {
     ScriptBlock.Create("$args[0] | Suspend-PrintJob -ComputerName $args[1]").Invoke(_source, ComputerName);
 }
Example #29
0
 public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block)
 => cmdlet.RunScript <PSObject>(block.ToString());
        /// <summary>
        ///
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = s_PSExePath;

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

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

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

#if CORECLR
            string processArguments = " -s -NoLogo -NoProfile";
#else
            // Adding Version parameter to powershell
            // Version parameter needs to go before all other parameters because the native layer looks for Version or
            // PSConsoleFile parameters before parsing other parameters.
            // The other parameters get parsed in the managed layer.
            Version tempVersion      = powerShellVersion ?? PSVersionInfo.PSVersion;
            string  processArguments = string.Format(CultureInfo.InvariantCulture,
                                                     "-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));

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

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

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

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

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

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
Example #31
0
 public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block)
 => engineIntrinsics.RunScript <PSObject>(block.ToString());
Example #32
0
 /// <summary>
 /// Sets a command breakpoint in the debugger.
 /// </summary>
 /// <param name="command">The name of the command that will trigger the breakpoint. This value is required and may not be null.</param>
 /// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
 /// <param name="path">The path to the script file where the breakpoint may be hit. If null, the breakpoint may be hit anywhere the command is invoked.</param>
 /// <param name="runspaceId">The runspace id of the runspace you want to interact with. Defaults to null (current runspace).</param>
 /// <returns>The command breakpoint that was set.</returns>
 public override CommandBreakpoint SetCommandBreakpoint(string command, ScriptBlock action = null, string path = null, int?runspaceId = null) =>
 _wrappedDebugger.SetCommandBreakpoint(command, action, path, runspaceId);
Example #33
0
 public OnSuccessStep(string workigDirectory, ScriptBlock scriptBlock)
     : base(workigDirectory, scriptBlock)
 {
 }
Example #34
0
 /// <summary>
 /// Sets a variable breakpoint in the debugger.
 /// </summary>
 /// <param name="variableName">The name of the variable that will trigger the breakpoint. This value is required and may not be null.</param>
 /// <param name="accessMode">The variable access mode that will trigger the breakpoint. By default variable breakpoints will trigger only when the variable is updated.</param>
 /// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
 /// <param name="path">The path to the script file where the breakpoint may be hit. If null, the breakpoint may be hit anywhere the variable is accessed using the specified access mode.</param>
 /// <param name="runspaceId">The runspace id of the runspace you want to interact with. Defaults to null (current runspace).</param>
 /// <returns>The variable breakpoint that was set.</returns>
 public override VariableBreakpoint SetVariableBreakpoint(string variableName, VariableAccessMode accessMode = VariableAccessMode.Write, ScriptBlock action = null, string path = null, int?runspaceId = null) =>
 _wrappedDebugger.SetVariableBreakpoint(variableName, accessMode, action, path, runspaceId);
Example #35
0
 public WPFJob(string name, string command, ScriptBlock scriptBlock) : base(command, name)
 {
     this.initialSessionState = InitialSessionState.CreateDefault();
     Start(scriptBlock, new Hashtable());
 }
Example #36
0
 /// <summary>
 /// Sets a line breakpoint in the debugger.
 /// </summary>
 /// <param name="path">The path to the script file where the breakpoint may be hit. This value is required and may not be null.</param>
 /// <param name="line">The line in the script file where the breakpoint may be hit. This value is required and must be greater than or equal to 1.</param>
 /// <param name="column">The column in the script file where the breakpoint may be hit. If 0, the breakpoint will trigger on any statement on the line.</param>
 /// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
 /// <param name="runspaceId">The runspace id of the runspace you want to interact with. Defaults to null (current runspace).</param>
 /// <returns>The line breakpoint that was set.</returns>
 public override LineBreakpoint SetLineBreakpoint(string path, int line, int column = 0, ScriptBlock action = null, int?runspaceId = null) =>
 _wrappedDebugger.SetLineBreakpoint(path, line, column, action, runspaceId);
Example #37
0
 public WPFJob(string name, string command, ScriptBlock scriptBlock, InitialSessionState initalSessionState, Hashtable parameters) : base(command, name)
 {
     this.initialSessionState = initalSessionState;
     Start(scriptBlock, parameters);
 }
 public ScriptTransformationAttribute(ScriptBlock script)
 {
     _script = script;
 }
 public ScriptBlock AnotherInvalidParamsBlockTest(ScriptBlock s, int a)
 {
     return null;
 }
Example #40
0
 /// <summary>
 /// Creates an instance of the FilterInfo class with the specified name and ScriptBlock
 /// </summary>
 /// 
 /// <param name="name">
 /// The name of the filter.
 /// </param>
 /// 
 /// <param name="filter">
 /// The ScriptBlock for the filter
 /// </param>
 /// 
 /// <param name="context">
 /// The ExecutionContext for the filter.
 /// </param>
 /// 
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="filter"/> is null.
 /// </exception>
 /// 
 internal FilterInfo(string name, ScriptBlock filter, ExecutionContext context) : this(name, filter, context, null)
 {
 } // FilterInfo ctor
 public ScriptBlock ScriptBlockTest(ScriptBlock block)
 {
     return block.AppendScript(new InlineScriptSource(ScriptBlockTestScriptName, ScriptBlockTestScript));
 }
Example #42
0
 /// <summary>
 /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
 /// </summary>
 /// 
 /// <param name="name">
 /// The name of the configuration.
 /// </param>
 /// 
 /// <param name="configuration">
 /// The ScriptBlock for the configuration
 /// </param>
 /// 
 /// <param name="context">
 /// The ExecutionContext for the configuration.
 /// </param>
 /// 
 /// <param name="helpFile">
 /// The help file for the configuration.
 /// </param>
 /// 
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="configuration"/> is null.
 /// </exception>
 /// 
 internal ConfigurationInfo(string name, ScriptBlock configuration, ExecutionContext context, string helpFile)
     : base(name, configuration, context, helpFile)
 {
     SetCommandType(CommandTypes.Configuration);
 }
 public int InvalidReturnBlockTest(ScriptBlock s)
 {
     return 0;
 }
Example #44
0
        private Collection <PSObject> InvokeScript(
            ScriptBlock sb,
            bool useNewScope,
            PipelineResultTypes writeToPipeline,
            IList input,
            params object[] args)
        {
            if (_cmdlet != null)
            {
                _cmdlet.ThrowIfStopping();
            }

            Cmdlet cmdletToUse = null;

            ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe;

            // Check if they want output
            if ((writeToPipeline & PipelineResultTypes.Output) == PipelineResultTypes.Output)
            {
                cmdletToUse      = _cmdlet;
                writeToPipeline &= (~PipelineResultTypes.Output);
            }

            // Check if they want error
            if ((writeToPipeline & PipelineResultTypes.Error) == PipelineResultTypes.Error)
            {
                errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe;
                writeToPipeline      &= (~PipelineResultTypes.Error);
            }

            if (writeToPipeline != PipelineResultTypes.None)
            {
                // The only output types are Output and Error.
                throw PSTraceSource.NewNotImplementedException();
            }

            // If the cmdletToUse is not null, then the result of the evaluation will be
            // streamed out the output pipe of the cmdlet.
            object rawResult;

            if (cmdletToUse != null)
            {
                sb.InvokeUsingCmdlet(
                    contextCmdlet: cmdletToUse,
                    useLocalScope: useNewScope,
                    errorHandlingBehavior: errorHandlingBehavior,
                    dollarUnder: AutomationNull.Value,
                    input: input,
                    scriptThis: AutomationNull.Value,
                    args: args);
                rawResult = AutomationNull.Value;
            }
            else
            {
                rawResult = sb.DoInvokeReturnAsIs(
                    useLocalScope: useNewScope,
                    errorHandlingBehavior: errorHandlingBehavior,
                    dollarUnder: AutomationNull.Value,
                    input: input,
                    scriptThis: AutomationNull.Value,
                    args: args);
            }

            if (rawResult == AutomationNull.Value)
            {
                return(new Collection <PSObject>());
            }

            // If the result is already a collection of PSObjects, just return it...
            Collection <PSObject> result = rawResult as Collection <PSObject>;

            if (result != null)
            {
                return(result);
            }

            result = new Collection <PSObject>();

            IEnumerator list = null;

            list = LanguagePrimitives.GetEnumerator(rawResult);

            if (list != null)
            {
                while (list.MoveNext())
                {
                    object val = list.Current;

                    result.Add(LanguagePrimitives.AsPSObjectOrNull(val));
                }
            }
            else
            {
                result.Add(LanguagePrimitives.AsPSObjectOrNull(rawResult));
            }

            return(result);
        }
Example #45
0
        } // FilterInfo ctor

        /// <summary>
        /// Creates an instance of the FilterInfo class with the specified name and ScriptBlock
        /// </summary>
        /// 
        /// <param name="name">
        /// The name of the filter.
        /// </param>
        /// 
        /// <param name="filter">
        /// The ScriptBlock for the filter
        /// </param>
        /// 
        /// <param name="context">
        /// The ExecutionContext for the filter.
        /// </param>
        /// 
        /// <param name="helpFile">
        /// The help file for the filter.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="filter"/> is null.
        /// </exception>
        /// 
        internal FilterInfo(string name, ScriptBlock filter, ExecutionContext context, string helpFile)
            : base(name, filter, context, helpFile)
        {
            SetCommandType(CommandTypes.Filter);
        } // FilterInfo ctor
Example #46
0
        public ScriptState(ScriptState copy)
        {
            Ref = copy.Ref;
            Width = copy.Width;
            Height = copy.Height;

            Textures = new Dictionary<string, FileInfo>(copy.Textures);

            OnLoad = copy.OnLoad.Copy();
            OnDeath = copy.OnDeath.Copy();
            OnCollision = copy.OnCollision.Copy();
            OnKeyPressed = copy.OnKeyPressed.Copy();
            OnUpdate = copy.OnUpdate.Copy();
        }
 public void ScriptBlockSavesSuppliedScripts(InlineScriptSource[] inlineScriptSources)
 {
     var sut = new ScriptBlock(inlineScriptSources);
     Assert.Equal(inlineScriptSources, sut.Scripts);
 }
Example #48
0
        public ScriptState(string reference, int width, int height)
        {
            Ref = reference;
            Width = width;
            Height = height;
            Textures = new Dictionary<string, FileInfo>();

            OnLoad = new ScriptBlock();
            OnDeath = new ScriptBlock();
            OnCollision = new ScriptBlock();
            OnKeyPressed = new ScriptBlock();
            OnUpdate = new ScriptBlock();
        }
Example #49
0
 private void SetKeyHandlerInternal(string[] keys, Action <ConsoleKeyInfo?, object> handler, string briefDescription, string longDescription, ScriptBlock scriptBlock)
 {
     foreach (var key in keys)
     {
         var chord    = ConsoleKeyChordConverter.Convert(key);
         var firstKey = PSKeyInfo.FromConsoleKeyInfo(chord[0]);
         if (chord.Length == 1)
         {
             _dispatchTable[firstKey] = MakeKeyHandler(handler, briefDescription, longDescription, scriptBlock);
         }
         else
         {
             _dispatchTable[firstKey] = MakeKeyHandler(Chord, "ChordFirstKey");
             if (!_chordDispatchTable.TryGetValue(firstKey, out var secondDispatchTable))
             {
                 secondDispatchTable           = new Dictionary <PSKeyInfo, KeyHandler>();
                 _chordDispatchTable[firstKey] = secondDispatchTable;
             }
             secondDispatchTable[PSKeyInfo.FromConsoleKeyInfo(chord[1])] = MakeKeyHandler(handler, briefDescription, longDescription, scriptBlock);
         }
     }
 }
Example #50
0
        CreateCommandProcessor
        (
            ExecutionContext executionContext,
            CommandFactory commandFactory,
            bool addToHistory,
            CommandOrigin origin
        )
        {
            Dbg.Assert(executionContext != null, "Caller should verify the parameters");
            Dbg.Assert(commandFactory != null, "Caller should verify the parameters");


            CommandProcessorBase commandProcessorBase;

            if (IsScript)
            {
                if ((executionContext.LanguageMode == PSLanguageMode.NoLanguage) &&
                    (origin == Automation.CommandOrigin.Runspace))
                {
                    throw InterpreterError.NewInterpreterException(CommandText, typeof(ParseException),
                                                                   null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed);
                }

                ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory);
                if (origin == Automation.CommandOrigin.Internal)
                {
                    scriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
                }

                // If running in restricted language mode, verify that the parse tree represents on legitimate
                // constructions...
                switch (scriptBlock.LanguageMode)
                {
                case PSLanguageMode.RestrictedLanguage:
                    scriptBlock.CheckRestrictedLanguage(null, null, false);
                    break;

                case PSLanguageMode.FullLanguage:
                    // Interactive script commands are permitted in this mode.
                    break;

                case PSLanguageMode.ConstrainedLanguage:
                    // Constrained Language is checked at runtime.
                    break;

                default:
                    // This should never happen...
                    Diagnostics.Assert(false, "Invalid langage mode was set when building a ScriptCommandProcessor");
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }

                if (scriptBlock.UsesCmdletBinding)
                {
                    FunctionInfo functionInfo = new FunctionInfo("", scriptBlock, executionContext);
                    commandProcessorBase = new CommandProcessor(functionInfo, executionContext,
                                                                _useLocalScope ?? false, fromScriptFile: false, sessionState: executionContext.EngineSessionState);
                }
                else
                {
                    commandProcessorBase = new DlrScriptCommandProcessor(scriptBlock,
                                                                         executionContext, _useLocalScope ?? false,
                                                                         origin,
                                                                         executionContext.EngineSessionState);
                }
            }
            else
            {
                // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace
                if ((_useLocalScope.HasValue) && (!_useLocalScope.Value))
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed,
                                                           "UseLocalScope",
                                                           PSLanguageMode.RestrictedLanguage.ToString(),
                                                           PSLanguageMode.NoLanguage.ToString());
                        throw new RuntimeException(message);

                    case PSLanguageMode.FullLanguage:
                        // Interactive script commands are permitted in this mode...
                        break;
                    }
                }

                commandProcessorBase =
                    commandFactory.CreateCommand(CommandText, origin, _useLocalScope);
            }

            CommandParameterCollection parameters = Parameters;

            if (parameters != null)
            {
                bool isNativeCommand = commandProcessorBase is NativeCommandProcessor;
                foreach (CommandParameter publicParameter in parameters)
                {
                    CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, isNativeCommand);
                    commandProcessorBase.AddParameter(internalParameter);
                }
            }

            string       helpTarget;
            HelpCategory helpCategory;

            if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory))
            {
                commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor(
                    executionContext,
                    helpTarget,
                    helpCategory);
            }

            //Set the merge settings
            SetMergeSettingsOnCommandProcessor(commandProcessorBase);

            return(commandProcessorBase);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = s_PSExePath;

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

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

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

            string processArguments = string.Empty;
            // Adding Version parameter to powershell.exe
            // Version parameter needs to go before all other parameters because the native layer looks for Version or 
            // PSConsoleFile parameters before parsing other parameters.
            // The other parameters get parsed in the managed layer.
            Version tempVersion = powerShellVersion ?? PSVersionInfo.PSVersion;
            processArguments = string.Format(CultureInfo.InvariantCulture,
                       "-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));

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

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

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

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

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

            Process = new Process { StartInfo = _startInfo, EnableRaisingEvents = true };
        }
Example #52
0
 /// <summary>
 /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock
 /// </summary>
 /// 
 /// <param name="name">
 /// The name of the configuration.
 /// </param>
 /// 
 /// <param name="configuration">
 /// The ScriptBlock for the configuration
 /// </param>
 /// 
 /// <param name="options">
 /// The options to set on the function. Note, Constant can only be set at creation time.
 /// </param>
 /// 
 /// <param name="context">
 /// The execution context for the configuration.
 /// </param>
 /// 
 /// <param name="helpFile">
 /// The help file for the configuration.
 /// </param>
 /// 
 /// <param name="isMetaConfig">The configuration is a meta configuration</param>
 /// 
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="configuration"/> is null.
 /// </exception>
 /// 
 internal ConfigurationInfo(string name, ScriptBlock configuration, ScopedItemOptions options, ExecutionContext context, string helpFile, bool isMetaConfig)
     : base(name, configuration, options, context, helpFile)
 {
     SetCommandType(CommandTypes.Configuration);
     IsMetaConfiguration = isMetaConfig;
 }