コード例 #1
0
        void RunSbActionWithParams(ScriptBlock sb, object[] parameters)
        {
            Collection <PSObject> psObjects = null;

            try {
                Trace.TraceInformation("runSBActionWithParams.1");
                if (null == parameters || 0 == parameters.Length)
                {
                    psObjects = sb.Invoke();
                }
                else
                {
                    psObjects = sb.Invoke(parameters);
                }
                Trace.TraceInformation("runSBActionWithParams.2");
            } catch (Exception eOuter) {
                // TODO: AOP
                Trace.TraceError("runSBActionWithParams(ScriptBlock sb, object[] parameters)");
                Trace.TraceError(eOuter.Message);
                throw new Exception(
                          "Unable to issue the following command:\r\n" +
                          sb +
                          "\r\nThe exception raised is\r\n" +
                          eOuter.Message);
            }
        }
コード例 #2
0
        /// <summary>
        /// Invokes the callback scriptblock as configured.
        /// </summary>
        /// <param name="Caller">The object containing the information pertaining to the calling command.</param>
        /// <param name="Invoker">The meta object representing the invoking command.</param>
        /// <param name="Data">Extra data that was passed to the event</param>
        public void Invoke(CallerInfo Caller, PSCmdlet Invoker, object Data)
        {
            Hashtable table = new Hashtable(StringComparer.InvariantCultureIgnoreCase);

            table["Command"]        = Invoker.MyInvocation.MyCommand.Name;
            table["ModuleName"]     = Invoker.MyInvocation.MyCommand.ModuleName;
            table["CallerFunction"] = Caller.CallerFunction;
            table["CallerModule"]   = Caller.CallerModule;
            table["Data"]           = Data;

            try
            {
                if (BreakAffinity)
                {
                    lock (_InvokeLock)
                    {
                        UtilityHost.ImportScriptBlock(ScriptBlock);
                        ScriptBlock.Invoke(table);
                    }
                }
                else
                {
                    ScriptBlock.Invoke(table);
                }
            }
            catch (Exception e)
            {
                throw new CallbackException(this, e);
            }
        }
コード例 #3
0
        /// <summary>
        /// Helper function for the Set-PSReadlineKeyHandler cmdlet.
        /// </summary>
        public static void SetKeyHandler(string[] key, ScriptBlock scriptBlock, string briefDescription, string longDescription)
        {
            Action <ConsoleKeyInfo?, object> handler =
                (k, arg) => scriptBlock.Invoke(k, arg);

            _singleton.SetKeyHandlerInternal(key, handler, briefDescription, longDescription, scriptBlock);
        }
コード例 #4
0
 /// <summary>
 /// Obtain value for cached item. Run collector script if necessary, prevent parallel collector execution.
 /// </summary>
 /// <returns>The cached values</returns>
 public object GetValue()
 {
     lock (_GetValueLock)
     {
         if (!Expired)
         {
             return(Value);
         }
         _Value = null;
         if (Collector != null)
         {
             Utility.UtilityHost.ImportScriptBlock(Collector);
             var result = Collector.Invoke(CollectorArgument);
             if (result.Count > 0)
             {
                 Value = result.ToArray();
             }
             else
             {
                 Value = null;
             }
         }
         return(Value);
     }
 }
コード例 #5
0
        /// <summary>
        /// Returns the correct results, either by executing the scriptblock or consulting the cache
        /// </summary>
        /// <returns></returns>
        public string[] Invoke()
        {
            if (!ShouldExecute)
            {
                return(LastResult);
            }

            List <string> results = new List <string>();

            IEnumerable <CallStackFrame> _callStack = System.Management.Automation.Runspaces.Runspace.DefaultRunspace.Debugger.GetCallStack();
            CallStackFrame callerFrame = null;

            if (_callStack.Count() > 0)
            {
                callerFrame = _callStack.First();
            }

            ScriptBlock scriptBlock = ScriptBlock.Create(ScriptBlock.ToString());

            foreach (PSObject item in scriptBlock.Invoke(callerFrame.InvocationInfo.MyCommand.Name, "", "", null, callerFrame.InvocationInfo.BoundParameters))
            {
                results.Add((string)item.Properties["CompletionText"].Value);
            }

            return(results.ToArray());
        }
コード例 #6
0
        protected override void ProcessRecord()
        {
            try
            {
                if (Body == null)
                {
                    return;
                }

                // Evalute selector pre-condition
                if (!AcceptsWith())
                {
                    return;
                }

                // Evaluate script pre-condition
                if (!AcceptsIf())
                {
                    return;
                }

                WriteObject(Body.Invoke(), true);
            }
            finally
            {
            }
        }
コード例 #7
0
        /// <summary>
        /// Returns the values provided by the options specified.
        /// </summary>
        /// <returns>The legal values you may provide.</returns>
        public string[] GetValues()
        {
            if (Values != null && Values.Length > 0)
            {
                return(Values);
            }

            if (ScriptBlock != null)
            {
                List <string> results = new List <string>();
                foreach (object item in ScriptBlock.Invoke())
                {
                    if (item != null)
                    {
                        results.Add(item.ToString());
                    }
                }
                return(results.ToArray());
            }

            if (TabExpansion.TabExpansionHost.Scripts.ContainsKey(TabCompletion.ToLower()))
            {
                return(TabExpansion.TabExpansionHost.Scripts[TabCompletion.ToLower()].Invoke());
            }

            return(new string[0]);
        }
コード例 #8
0
        internal static T InvokeWithArg <T>(this ScriptBlock script_block, T default_value, params object[] args)
        {
            try
            {
                List <PSVariable> vars = new List <PSVariable>();
                if (args.Length > 0)
                {
                    vars.Add(new PSVariable("_", args[0]));
                }
#if NETCORE
                // Work around issue with standard PS library until it's fixed.
                var os = script_block.Invoke(args);
#else
                var os = script_block.InvokeWithContext(null, vars, args);
#endif
                if (os.Count > 0)
                {
                    return((T)Convert.ChangeType(os[0].BaseObject, typeof(T)));
                }
            }
            catch
            {
            }
            return(default_value);
        }
コード例 #9
0
        /// <summary>
        /// Method to read the provided script file and either write
        /// the created instrumented AST object or write elapsed time
        /// for each line in script.
        /// </summary>
        /// <param name="file"></param>
        private void Profile(string file)
        {
            Token[]      tokens;
            ParseError[] errors;
            var          ast          = Parser.ParseFile(file, out tokens, out errors);
            Profiler     profiler     = new Profiler(ast.Extent);
            var          instrumentor = new InstrumentAst {
                Profiler = profiler
            };
            ScriptBlockAst newAst = (ScriptBlockAst)ast.Visit(instrumentor);

            if (Ast)
            {
                WriteObject(newAst);
                return;
            }

            ScriptBlock sb = newAst.GetScriptBlock();

            sb.Invoke();

            string[] allLines = File.ReadAllLines(file);
            for (int i = 0; i < allLines.Length; ++i)
            {
                long time   = (i >= profiler.StopWatches.Length) ? 0 : profiler.StopWatches[i].ElapsedMilliseconds;
                var  result = new PSObject();
                result.Members.Add(new PSNoteProperty("Time", time));
                result.Members.Add(new PSNoteProperty("Line", allLines[i]));
                WriteObject(result);
            }
        }
コード例 #10
0
        //internal static ICollection<PSObject> InvokeNested(ScriptBlock sb, PSVariable[] variables, params object[] args)
        //{
        //   if (variables == null)
        //      throw new ArgumentNullException("variables");

        //   foreach (var v in variables) SetScriptVariable(v);

        //   if (_module != null)
        //   {
        //      sb = _module.NewBoundScriptBlock(sb);
        //   }
        //   Pipeline pipe = null;
        //   ICollection<PSObject> results = null;
        //   try
        //   {
        //      pipe = Runspace.DefaultRunspace.CreateNestedPipeline();
        //      pipe.Commands.AddScript(sb.ToString(), true);
        //      results = pipe.Invoke(args);
        //   }
        //   catch (PSInvalidOperationException ioe)
        //   {
        //      if(pipe != null) pipe.Dispose();
        //      pipe = null;
        //   }

        //   if(pipe == null)
        //   {
        //      try
        //      {
        //         pipe = Runspace.DefaultRunspace.CreatePipeline();
        //         pipe.Commands.AddScript(sb.ToString(), true);
        //         results = pipe.Invoke(args);
        //      }
        //      catch (PSInvalidOperationException ioe)
        //      {
        //         if (pipe != null) pipe.Dispose();
        //         pipe = null;
        //      }
        //   }
        //   if (pipe != null)
        //   {
        //      pipe.Stop();
        //      pipe.Dispose();
        //   }
        //   else
        //   {
        //      results = sb.Invoke(args);
        //   }
        //   return results;
        //}

        /// <summary>
        /// Invoke a <see cref="ScriptBlock"/>, binding it to the module, if possible.
        /// </summary>
        /// <param name="sb">The <see cref="ScriptBlock"/></param>
        /// <param name="args">Arguments to the <see cref="ScriptBlock"/></param>
        /// <returns>A collection of <see cref="PSObject"/></returns>
        internal static ICollection <PSObject> Invoke(ScriptBlock sb, params object[] args)
        {
            if (_module != null)
            {
                sb = _module.NewBoundScriptBlock(sb);
            }
            return(sb.Invoke(args));
        }
コード例 #11
0
        protected IEnumerable <T> GetItemsFromScriptBlock <T>(ScriptBlock scriptBlock)
        {
            if (scriptBlock == null)
            {
                return(null);
            }

            return(scriptBlock.Invoke().Select(m => m.BaseObject).Cast <T>());
        }
コード例 #12
0
ファイル: A.cs プロジェクト: fcenobi/FarNet
        /// <summary>
        /// Invokes the script block and returns the result collection.
        /// </summary>
        /// <param name="script">The script block to invoke.</param>
        /// <param name="args">Script arguments.</param>
        internal static Collection <PSObject> InvokeScript(ScriptBlock script, params object[] args)
        {
            if (Runspace.DefaultRunspace == null)
            {
                Runspace.DefaultRunspace = Psf.Runspace;
            }

            return(script.Invoke(args));
        }
コード例 #13
0
 public EqualityComparer(ScriptBlock equalityScript, ScriptBlock hashScript)
 {
     this.EqualityPredicate = (x, y) => {
         return(equalityScript.Invoke(null, x, y));
     };
     this.HashFunction = (obj) => {
         return(hashScript.Invoke(null, obj));
     };
 }
コード例 #14
0
        public static Collection <T> ToEnumerable <T>(this ScriptBlock scriptBlock)
        {
            if (scriptBlock == null)
            {
                return(null);
            }

            return(new Collection <T>(scriptBlock.Invoke().Select(o => o.BaseObject).Cast <T>().ToList()));
        }
コード例 #15
0
        /// <summary>
        /// The parameters passed can be anything, but essentially a variable with/without any experssions in it.
        /// Expression is not allowed in $Using, so try parameter binding using proxyfunction and return the resolved params.
        /// This can get tricky when on constrained runspace, User need to explicity specifiy the parameters in that case.        ///
        /// </summary>
        /// <param name="proxyCommand"></param>
        /// <param name="scriptToRun"></param>
        /// <param name="cmdStr"></param>
        /// <returns></returns>
        internal static IDictionary FindParams(FunctionInfo proxyCommand, ScriptBlock scriptToRun, string cmdStr, PSObject inputObject)
        {
            string convertedScript = "param($Inputobject) " + scriptToRun.ToString();

            convertedScript = convertedScript.Replace(cmdStr, proxyCommand.Name);
            ScriptBlock commandBlock = ScriptBlock.Create(convertedScript.Replace("$_", "$inputobject"));
            IDictionary boundParams  = (Dictionary <String, Object>)commandBlock.Invoke(inputObject).FirstOrDefault().BaseObject;

            return(boundParams);
        }
コード例 #16
0
        public override bool IsMatch(FileSystemInfo fs)
        {
            Collection <PSObject> result = mMatchScript.Invoke(fs);

            if (result.Count != 1 || !(result[0].BaseObject is bool))
            {
                throw new ArgumentException("Match scripts must return a single true/false result.");
            }
            return((bool)result[0].BaseObject);
        }
コード例 #17
0
 public void Invoke(object target, Style style)
 {
     if (_action != null)
     {
         _action.Invoke(target, style);
     }
     else
     {
         _scriptBlock.Invoke(new object[] { target, style });
     }
 }
コード例 #18
0
        public static void Set(this Trigger trigger, ScriptBlock scriptBlock)
        {
            trigger.Variables.Clear();
            trigger.CodeLines.Clear();

            if (scriptBlock != null)
            {
                var subObjects = scriptBlock.Invoke().Select(o => o.BaseObject);
                trigger.Variables.AddRange(subObjects.OfType <Variable>());
                trigger.CodeLines.AddRange(subObjects.OfType <string>());
            }
        }
コード例 #19
0
        private void StartRunningAllWatchers()
        {
            foreach (var watcher in _watchers.Values)
            {
                watcher.Run();
            }

            if (_afterWatchStarted != null)
            {
                _afterWatchStarted.Invoke();
            }
        }
コード例 #20
0
        /// <summary>
        /// Copy the simple stringification from Write-Host instead of using LanguagePrimitives.ConvertTo
        /// </summary>
        /// <remarks>
        ///     Specifically, Write-Host uses it's own <code>Separator</code> instead of $OFS
        /// </remarks>
        /// <param name="object">The object</param>
        /// <param name="separator">The separator</param>
        /// <returns>A simple string representation</returns>
        public static string ConvertToString(object @object, string separator = " ")
        {
            if (@object != null)
            {
                string      s          = @object as string;
                ScriptBlock sb         = null;
                IEnumerable enumerable = null;
                if (s != null)
                {
                    // strings are IEnumerable, so we special case them
                    if (s.Length > 0)
                    {
                        return(s);
                    }
                }
                else if ((enumerable = @object as IEnumerable) != null)
                {
                    // unroll enumerables, including arrays.

                    bool          printSeparator = false;
                    StringBuilder result         = new StringBuilder();

                    foreach (object element in enumerable)
                    {
                        if (printSeparator == true && separator != null)
                        {
                            result.Append(separator.ToString());
                        }

                        result.Append(ConvertToString(element, separator));
                        printSeparator = true;
                    }

                    return(result.ToString());
                }
                else if ((sb = @object as ScriptBlock) != null)
                {
                    return(ConvertToString(sb.Invoke(), separator));
                }
                else
                {
                    s = @object.ToString();

                    if (s.Length > 0)
                    {
                        return(s);
                    }
                }
            }

            return(null);
        }
コード例 #21
0
 protected override void ProcessRecord()
 {
     try
     {
         if (Body == null)
         {
             return;
         }
         WriteObject(Body.Invoke(), true);
     }
     finally
     {
     }
 }
コード例 #22
0
        public void GlobalSetup()
        {
            SetupRunspace();
            scriptBlock = ScriptBlock.Create(InvokeMethodScript);

            // Run it once to get the C# code jitted and the script compiled.
            // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly
            // believe that there is no need to run many ops in each interation. However, the subsequent runs
            // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings
            // to our benchmarks and make the benchmark results not reliable.
            // Calling this method once in 'GlobalSetup' is a workaround.
            // See https://github.com/dotnet/BenchmarkDotNet/issues/837#issuecomment-828600157
            scriptBlock.Invoke();
        }
コード例 #23
0
ファイル: InvokeApartmentCommand.cs プロジェクト: zyonet/Pscx
        protected override void EndProcessing()
        {
            base.EndProcessing();

            if (_apartment == Thread.CurrentThread.GetApartmentState())
            {
                WriteObject(_script.Invoke());
            }
            else
            {
                _runspace = Runspace.DefaultRunspace;

                Thread thread = new Thread(WorkerThread);
                thread.SetApartmentState(_apartment);

                thread.Start();
                thread.Join();

                if (_exception != null)
                {
                    IContainsErrorRecord errRecordContaier = (_exception as IContainsErrorRecord);

                    if (errRecordContaier != null)
                    {
                        ThrowTerminatingError(errRecordContaier.ErrorRecord);
                    }
                    else
                    {
                        ThrowTerminatingError(new ErrorRecord(_exception, _exception.GetType().Name, ErrorCategory.NotSpecified, null));
                    }
                }
                else
                {
                    WriteObject(_results, true);
                }
            }
        }
コード例 #24
0
ファイル: PSCmdletBase.cs プロジェクト: lddd99/guiatuomation
        void runSBAction(ScriptBlock sb,
                         AutomationElement src,
                         AutomationEventArgs e)
        {
            Collection <PSObject> psObjects = null;

            try {
                psObjects =
                    sb.Invoke();
// int counter = 0;
// foreach (PSObject pso in psObjects) {
//  //if pso.
// counter++;
// WriteVerbose("result " + counter.ToString() + ":");
// WriteVerbose(pso.ToString());
//  //WriteObject(pso.TypeNames
// foreach ( string typeName in pso.TypeNames) {
// WriteVerbose(typeName);
// }
// }
            } catch (Exception eOuter) {
                // 20130318
//                ErrorRecord err =
//                    new ErrorRecord(eOuter,
//                                    "ErrorInInvokingScriptBlock",
//                                    ErrorCategory.InvalidOperation,
//                                    System.Management.Automation.Runspaces.Runspace.DefaultRunspace);
//                err.ErrorDetails =
//                    new ErrorDetails(
//                        "Unable to issue the following command:\r\n" +
//                        sb.ToString() +
//                        "\r\nThe exception raised is\r\n" +
//                        eOuter.Message);
//                                     //"System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();");
//                WriteError(err);

                WriteError(
                    this,
                    "Unable to issue the following command:\r\n" +
                    sb +
                    "\r\nThe exception raised is\r\n" +
                    eOuter.Message,
                    "ErrorInInvokingScriptBlock",
                    ErrorCategory.InvalidOperation,
                    // 20130318
                    //false);
                    true);
            }
        }
コード例 #25
0
        /// <summary>
        /// Applies a value to a configuration item, invoking validation and handler scriptblocks.
        /// </summary>
        /// <param name="Value">The value to apply</param>
        private void ApplyValue(object Value)
        {
            object tempValue = Value;

            #region Validation
            if (!DisableValidation.ToBool() && (!String.IsNullOrEmpty(_Config.Validation)))
            {
                ScriptBlock tempValidation = ScriptBlock.Create(_Config.Validation.ToString());
                //if ((tempValue != null) && ((tempValue as ICollection) != null))
                //    tempValue = new object[1] { tempValue };

                PSObject validationResult = tempValidation.Invoke(tempValue)[0];
                if (!(bool)validationResult.Properties["Success"].Value)
                {
                    _ValidationErrorMessage = (string)validationResult.Properties["Message"].Value;
                    throw new ArgumentException(String.Format("Failed validation: {0}", _ValidationErrorMessage));
                }
                tempValue = validationResult.Properties["Value"].Value;
            }
            #endregion Validation

            #region Handler
            if (!DisableHandler.ToBool() && (_Config.Handler != null))
            {
                object      handlerValue = tempValue;
                ScriptBlock tempHandler  = ScriptBlock.Create(_Config.Handler.ToString());
                if ((tempValue != null) && ((tempValue as ICollection) != null))
                {
                    handlerValue = new object[1] {
                        tempValue
                    }
                }
                ;

                tempHandler.Invoke(handlerValue);
            }
            #endregion Handler

            _Config.Value = tempValue;

            if (Register.ToBool())
            {
                ScriptBlock registerCodeblock = ScriptBlock.Create(@"
param ($Config)
$Config | Register-DbatoolsConfig
");
                registerCodeblock.Invoke(_Config);
            }
        }
コード例 #26
0
        internal static Collection <PSObject> InvokeWithArg(this ScriptBlock script_block, params object[] args)
        {
            List <PSVariable> vars = new List <PSVariable>();

            if (args.Length > 0)
            {
                vars.Add(new PSVariable("_", args[0]));
            }
#if NETCORE
            // Work around issue with standard PS library until it's fixed.
            return(script_block.Invoke(args));
#else
            return(script_block.InvokeWithContext(null, vars, args));
#endif
        }
        private static bool ArbitraryFilter(NtProcess proc, ScriptBlock filter)
        {
            try
            {
                ICollection <PSObject> os = filter.Invoke(proc);
                if (os.Count == 1)
                {
                    return((bool)os.First().BaseObject);
                }
            }
            catch
            {
            }

            return(false);
        }
コード例 #28
0
        /// <summary>
        /// Helper function for the Set-PSReadlineKeyHandler cmdlet.
        /// </summary>
        public static void SetKeyHandler(string[] key, ScriptBlock scriptBlock, string briefDescription, string longDescription)
        {
            Action <ConsoleKeyInfo?, object> handler = (k, arg) =>
            {
                try
                {
                    scriptBlock.Invoke(k, arg);
                }
                catch (Exception e)
                {
                    throw new CustomHandlerException(e);
                }
            };

            _singleton.SetKeyHandlerInternal(key, handler, briefDescription, longDescription, scriptBlock);
        }
コード例 #29
0
        private bool AcceptsIf()
        {
            if (If == null)
            {
                return(true);
            }

            try
            {
                RunspaceContext.CurrentThread.PushScope(RunspaceScope.Condition);
                return(GetResult(If.Invoke()));
            }
            finally
            {
                RunspaceContext.CurrentThread.PopScope();
            }
        }
コード例 #30
0
        protected override void ProcessRecord()
        {
            try
            {
                if (Body == null)
                {
                    return;
                }

                // Evalute type pre-condition
                if (Type != null)
                {
                    var comparer = PipelineContext.CurrentThread.Baseline.GetTargetBinding().IgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
                    if (!Type.Contains(value: PipelineContext.CurrentThread.RuleRecord.TargetType, comparer: comparer))
                    {
                        PipelineContext.CurrentThread.Logger.DebugMessage("Target failed Type precondition");
                        return;
                    }
                }

                // Evaluate script pre-condition
                if (If != null)
                {
                    PipelineContext.CurrentThread.ExecutionScope = ExecutionScope.Precondition;

                    var ifResult = If.InvokeReturnAsIs() as PSObject;

                    if (ifResult == null || !(ifResult.BaseObject is bool) || !(bool)ifResult.BaseObject)
                    {
                        PipelineContext.CurrentThread.Logger.DebugMessage("Target failed If precondition");
                        return;
                    }
                }

                // Evaluate script block
                PipelineContext.CurrentThread.ExecutionScope = ExecutionScope.Condition;
                var invokeResult = RuleConditionResult.Create(Body.Invoke());

                WriteObject(invokeResult);
            }
            finally
            {
                PipelineContext.CurrentThread.ExecutionScope = ExecutionScope.None;
            }
        }