示例#1
0
        /// <summary>
        /// Executes a piece of text as a script synchronously using the options provided.
        /// </summary>
        /// <param name="script">The script to evaluate.</param>
        /// <param name="useNewScope">If true, evaluate the script in its own scope.
        /// If false, the script will be evaluated in the current scope i.e. it will be "dotted"</param>
        /// <param name="writeToPipeline">If set to Output, all output will be streamed
        /// to the output pipe of the calling cmdlet. If set to None, the result will be returned
        /// to the caller as a collection of PSObjects. No other flags are supported at this time and
        /// will result in an exception if used.</param>
        /// <param name="input">The list of objects to use as input to the script.</param>
        /// <param name="args">The array of arguments to the command.</param>
        /// <returns>A collection of MshCobjects generated by the script. This will be
        /// empty if output was redirected.</returns>
        /// <exception cref="ParseException">Thrown if there was a parsing error in the script.</exception>
        /// <exception cref="RuntimeException">Represents a script-level exception</exception>
        /// <exception cref="NotImplementedException">Thrown if any redirect other than output is attempted</exception>
        /// <exception cref="FlowControlException"></exception>
        public Collection <PSObject> InvokeScript(string script, bool useNewScope,
                                                  PipelineResultTypes writeToPipeline, IList input, params object[] args)
        {
            if (script == null)
            {
                throw new ArgumentNullException("script");
            }

            // Compile the script text into an executable script block.
            ScriptBlock sb = ScriptBlock.Create(_context, script);

            return(InvokeScript(sb, useNewScope, writeToPipeline, input, args));
        }
示例#2
0
        public PSObject NewTotalCount(ulong totalCount, double accuracy)
        {
            PSObject       obj2   = new PSObject(totalCount);
            string         script = string.Format(CultureInfo.CurrentCulture, "\r\n                    $totalCount = $this.PSObject.BaseObject\r\n                    switch ($this.Accuracy) {{\r\n                        {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }}\r\n                        {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }}\r\n                        default          {{ '{2}' -f $totalCount }}\r\n                    }}\r\n                ", new object[] { CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate), CommandMetadata.EscapeSingleQuotedString(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate) });
            PSScriptMethod member = new PSScriptMethod("ToString", ScriptBlock.Create(script));

            obj2.Members.Add(member);
            accuracy = Math.Max(0.0, Math.Min(1.0, accuracy));
            PSNoteProperty property = new PSNoteProperty("Accuracy", accuracy);

            obj2.Members.Add(property);
            return(obj2);
        }
        private static ScriptBlock ParseScriptContents(Parser parser, string fileName, string fileContents, PSLanguageMode?definingLanguageMode)
        {
            // If we are in ConstrainedLanguage mode but the defining language mode is FullLanguage, then we need
            // to parse the script contents in FullLanguage mode context.  Otherwise we will get bogus parsing errors
            // such as "Configuration keyword not allowed".
            if (definingLanguageMode.HasValue && (definingLanguageMode == PSLanguageMode.FullLanguage))
            {
                var context = LocalPipeline.GetExecutionContextFromTLS();
                if ((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage))
                {
                    context.LanguageMode = PSLanguageMode.FullLanguage;
                    try
                    {
                        return(ScriptBlock.Create(parser, fileName, fileContents));
                    }
                    finally
                    {
                        context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                    }
                }
            }

            return(ScriptBlock.Create(parser, fileName, fileContents));
        }
示例#4
0
        private void OnDebuggerStop(InvocationInfo invocationInfo, List <Breakpoint> breakpoints)
        {
            LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace;

            if ((currentRunspace.PulsePipeline != null) && (currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline()))
            {
                this._context.EngineHostInterface.UI.WriteWarningLine((breakpoints.Count > 0) ? string.Format(CultureInfo.CurrentCulture, DebuggerStrings.WarningBreakpointWillNotBeHit, new object[] { breakpoints[0] }) : new InvalidOperationException().Message);
            }
            else
            {
                this._steppingMode = SteppingMode.None;
                EventHandler <DebuggerStopEventArgs> debuggerStop = this.DebuggerStop;
                if (debuggerStop != null)
                {
                    this.InBreakpoint = true;
                    this._context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints));
                    FunctionInfo baseObject = null;
                    bool         flag       = false;
                    try
                    {
                        Collection <PSObject> collection = this._context.SessionState.InvokeProvider.Item.Get(@"function:\prompt");
                        if ((collection != null) && (collection.Count > 0))
                        {
                            baseObject = collection[0].BaseObject as FunctionInfo;
                            if (string.Equals(baseObject.Definition, InitialSessionState.DefaultPromptString, StringComparison.OrdinalIgnoreCase))
                            {
                                flag = true;
                            }
                        }
                    }
                    catch (ItemNotFoundException)
                    {
                    }
                    if (flag)
                    {
                        string script = "\"[DBG]: PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) \"";
                        baseObject.Update(ScriptBlock.Create(script), true, ScopedItemOptions.Unspecified);
                    }
                    PSLanguageMode languageMode = this._context.LanguageMode;
                    PSLanguageMode?nullable     = null;
                    if (this._context.UseFullLanguageModeInDebugger && (this._context.LanguageMode != PSLanguageMode.FullLanguage))
                    {
                        nullable = new PSLanguageMode?(this._context.LanguageMode);
                        this._context.LanguageMode = PSLanguageMode.FullLanguage;
                    }
                    else if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
                    {
                        nullable = new PSLanguageMode?(this._context.LanguageMode);
                        this._context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                    }
                    RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability;
                    this._context.CurrentRunspace.UpdateRunspaceAvailability((this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null) ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true);
                    try
                    {
                        this._context._debuggingMode = -1;
                        if (this._callStack.Any <CallStackInfo>())
                        {
                            this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = true;
                        }
                        DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints);
                        debuggerStop(this, e);
                        this.ResumeExecution(e.ResumeAction);
                    }
                    finally
                    {
                        this._context._debuggingMode = 1;
                        if (this._callStack.Any <CallStackInfo>())
                        {
                            this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = false;
                        }
                        this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true);
                        if (nullable.HasValue)
                        {
                            this._context.LanguageMode = nullable.Value;
                        }
                        this._context.EngineSessionState.RemoveVariable("PSDebugContext");
                        if (flag)
                        {
                            baseObject.Update(ScriptBlock.Create(InitialSessionState.DefaultPromptString), true, ScopedItemOptions.Unspecified);
                        }
                        this.InBreakpoint = false;
                    }
                }
            }
        }
示例#5
0
 public static ScriptBlock Create(string script) => ScriptBlock.Create(new Parser(), script);
示例#6
0
        private PSModuleInfo CreateModuleImplementation(
            string name,
            string path,
            object moduleCode,
            Token callerToken,
            SessionState ss,
            out ArrayList result,
            params object[] arguments)
        {
            if (ss == null)
            {
                ss = new SessionState(this._context.EngineSessionState, true, true);
            }
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            PSModuleInfo         psModuleInfo       = new PSModuleInfo(name, path, this._context, ss);

            ss.Internal.Module = psModuleInfo;
            bool flag = false;
            int  num  = 0;

            try
            {
                ArrayList resultList = (ArrayList)null;
                this._context.EngineSessionState = ss.Internal;
                this._context.EngineSessionState.SetVariableValue("PSScriptRoot", (object)Path.GetDirectoryName(path), CommandOrigin.Internal);
                switch (moduleCode)
                {
                case ExternalScriptInfo externalScriptInfo:
                    this._context.EngineSessionState.SetVariableValue("MyInvocation", (object)new InvocationInfo((CommandInfo)externalScriptInfo, callerToken), CommandOrigin.Internal);
                    scriptBlock = externalScriptInfo.ScriptBlock;
                    break;

                case ScriptBlock scriptBlock:
                    scriptBlock = scriptBlock.Clone(true);
                    scriptBlock.SessionState = ss;
                    break;

                case string _:
                    scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode);
                    break;
                }
                if (scriptBlock == null)
                {
                    throw ModuleIntrinsics.tracer.NewInvalidOperationException();
                }
                scriptBlock.SessionStateInternal = ss.Internal;
                try
                {
                    if (arguments == null)
                    {
                        scriptBlock.InvokeWithPipe(false, true, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList);
                    }
                    else
                    {
                        scriptBlock.InvokeWithPipe(false, true, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList, arguments);
                    }
                }
                catch (ExitException ex)
                {
                    num  = (int)ex.Argument;
                    flag = true;
                }
                result = resultList;
            }
            finally
            {
                this._context.EngineSessionState = engineSessionState;
            }
            if (flag)
            {
                this._context.SetVariable("global:LASTEXITCODE", (object)num);
            }
            return(psModuleInfo);
        }
示例#7
0
 public object GetRealObject(StreamingContext context)
 {
     return(ScriptBlock.Create(this.scriptText));
 }
示例#8
0
 private void LoadScriptInfo()
 {
     if (this._context.RunspaceConfiguration == null)
     {
         return;
     }
     foreach (ScriptConfigurationEntry script in (IEnumerable <ScriptConfigurationEntry>) this._context.RunspaceConfiguration.Scripts)
     {
         try
         {
             this.cachedScriptInfo.Add(script.Name, new ScriptInfo(script.Name, ScriptBlock.Create(this._context, script.Definition), this._context));
         }
         catch (ArgumentException ex)
         {
             throw CommandDiscovery.tracer.NewNotSupportedException("DiscoveryExceptions", "DuplicateScriptName", (object)script.Name);
         }
     }
 }
示例#9
0
        private PSModuleInfo CreateModuleImplementation(string name, string path, object moduleCode, IScriptExtent scriptPosition, SessionState ss, object privateData, out ArrayList result, params object[] arguments)
        {
            if (ss == null)
            {
                ss = new SessionState(this._context, true, true);
            }
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            PSModuleInfo         info = new PSModuleInfo(name, path, this._context, ss);

            ss.Internal.Module = info;
            info.PrivateData   = privateData;
            bool flag     = false;
            int  newValue = 0;

            try
            {
                ScriptBlock scriptBlock;
                this._context.EngineSessionState = ss.Internal;
                ExternalScriptInfo scriptCommandInfo = moduleCode as ExternalScriptInfo;
                if (scriptCommandInfo != null)
                {
                    scriptBlock = scriptCommandInfo.ScriptBlock;
                    this._context.Debugger.RegisterScriptFile(scriptCommandInfo);
                }
                else
                {
                    scriptBlock = moduleCode as ScriptBlock;
                    if (scriptBlock != null)
                    {
                        PSLanguageMode?languageMode = scriptBlock.LanguageMode;
                        scriptBlock = scriptBlock.Clone(true);
                        scriptBlock.LanguageMode = languageMode;
                        scriptBlock.SessionState = ss;
                    }
                    else if (moduleCode is string)
                    {
                        scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode);
                    }
                }
                if (scriptBlock == null)
                {
                    throw PSTraceSource.NewInvalidOperationException();
                }
                scriptBlock.SessionStateInternal = ss.Internal;
                InvocationInfo invocationInfo = new InvocationInfo(scriptCommandInfo, scriptPosition);
                info._definitionExtent = scriptBlock.Ast.Extent;
                ArrayList resultList = new ArrayList();
                try
                {
                    Pipe outputPipe = new Pipe(resultList);
                    scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, invocationInfo, arguments ?? new object[0]);
                }
                catch (ExitException exception)
                {
                    newValue = (int)exception.Argument;
                    flag     = true;
                }
                result = resultList;
            }
            finally
            {
                this._context.EngineSessionState = engineSessionState;
            }
            if (flag)
            {
                this._context.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue);
            }
            return(info);
        }