Example #1
0
        internal static bool TrySafeEval(ExpressionAst ast, ExecutionContext executionContext, out object value)
        {
            bool flag;

            if (!((bool)ast.Accept(new SafeExprEvaluator())))
            {
                value = null;
                return(false);
            }
            PSLanguageMode?nullable = null;

            try
            {
                if (ExecutionContext.HasEverUsedConstrainedLanguage)
                {
                    nullable = new PSLanguageMode?(executionContext.LanguageMode);
                    executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                }
                value = Compiler.GetExpressionValue(ast, executionContext, (IList)null);
                flag  = true;
            }
            catch
            {
                value = null;
                flag  = false;
            }
            finally
            {
                if (nullable.HasValue)
                {
                    executionContext.LanguageMode = nullable.Value;
                }
            }
            return(flag);
        }
Example #2
0
 internal static bool TrySafeEval(ExpressionAst ast, ExecutionContext executionContext, out object value)
 {
     bool flag;
     if (!((bool) ast.Accept(new SafeExprEvaluator())))
     {
         value = null;
         return false;
     }
     PSLanguageMode? nullable = null;
     try
     {
         if (ExecutionContext.HasEverUsedConstrainedLanguage)
         {
             nullable = new PSLanguageMode?(executionContext.LanguageMode);
             executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
         }
         value = Compiler.GetExpressionValue(ast, executionContext, (IList)null);
         flag = true;
     }
     catch
     {
         value = null;
         flag = false;
     }
     finally
     {
         if (nullable.HasValue)
         {
             executionContext.LanguageMode = nullable.Value;
         }
     }
     return flag;
 }
Example #3
0
        /// <summary>
        /// Creates a local runspace with the autoloading turned on.
        /// </summary>
        /// <returns></returns>
        internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true)
        {
            InitialSessionState iss = GetInitialSessionStateWithSharedTypesAndNoFormat();

            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                iss.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            if (languageMode != null && languageMode.HasValue)
            {
                iss.LanguageMode = languageMode.Value;
            }

            // Add a variable indicating that we're in Workflow endpoint. This enables the
            // autoloading feature.
            SessionStateVariableEntry ssve = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint",
                                                                           true, "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant);

            iss.Variables.Add(ssve);
            Runspace runspace = RunspaceFactory.CreateRunspace(iss);

            if (useCurrentThreadForExecution)
            {
                runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            }

            return(runspace);
        }
Example #4
0
        private Runspace AssignRunspaceIfPossible(PSLanguageMode?sourceLanguageMode = null)
        {
            Runspace       runspace     = null;
            PSLanguageMode languageMode = (sourceLanguageMode != null) ? sourceLanguageMode.Value :
                                          (_languageMode != null) ? _languageMode.Value : GetSystemLanguageMode();

            lock (_runspaceCache.TimerServicingSyncObject)
            {
                // Retrieve or create a local runspace having the same language mode as the source, if provided.
                foreach (Item <Runspace> item in _runspaceCache.Cast <Item <Runspace> >().Where(item => !item.Busy))
                {
                    if (item.Value.SessionStateProxy.LanguageMode == languageMode)
                    {
                        item.Idle = false;
                        item.Busy = true;
                        runspace  = item.Value;
                        break;
                    }
                }

                if ((runspace == null || runspace.RunspaceStateInfo.State != RunspaceState.Opened) &&
                    (_maxRunspaces == MaxRunspacesPossible || _runspaceCache.Cache.Count < _maxRunspaces))
                {
                    runspace = CreateLocalActivityRunspace(languageMode);

                    runspace.Open();
                    _tracer.WriteMessage("New local runspace created");

                    _runspaceCache.Add(new Item <Runspace>(runspace, runspace.InstanceId));
                }
            }

            return(runspace);
        }
        internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode?languageMode)
        {
            object obj;

            this._syncObject       = new object();
            this._tracer           = PowerShellTraceSourceFactory.GetTraceSource();
            this._languageMode     = languageMode;
            this._useJobIPCProcess = true;
            this._tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
            this._processInstance = new PowerShellProcessInstance();
            this._tracer.WriteMessage("END Creating new PowerShell process instance ");
            this._runspace = this.CreateRunspace();
            Guid instanceId = this._runspace.InstanceId;

            this._tracer.WriteMessage("New runspace created ", instanceId.ToString());
            Timer timer = new Timer();

            timer.AutoReset      = false;
            timer.Interval       = 300000;
            this._timer          = timer;
            this._timer.Elapsed += new ElapsedEventHandler(this.TimerElapsed);
            Timer timer1 = this._timer;

            if (activityHostTimeoutSec > 0)
            {
                obj = activityHostTimeoutSec * 0x3e8;
            }
            else
            {
                obj = 0x493e0;
            }
            timer1.Interval = (double)obj;
            ActivityHostProcess._perfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 21, (long)1, true);
        }
 internal LocalRunspaceProvider(int timeoutSeconds, int maxRunspaces, PSLanguageMode?languageMode)
 {
     this._requests      = new ConcurrentQueue <LocalRunspaceAsyncResult>();
     this._callbacks     = new ConcurrentQueue <LocalRunspaceAsyncResult>();
     this._tracer        = PowerShellTraceSourceFactory.GetTraceSource();
     this._runspaceCache = new TimeBasedCache <Runspace>(timeoutSeconds);
     this._maxRunspaces  = maxRunspaces;
     this._languageMode  = languageMode;
 }
Example #7
0
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock, PSLanguageMode languageMode, InvocationInfo invocationInfo)
 {
     if (scriptBlock.LanguageMode.HasValue)
     {
         PSLanguageMode?nullable2 = scriptBlock.LanguageMode;
         PSLanguageMode mode      = languageMode;
         if (((((PSLanguageMode)nullable2.GetValueOrDefault()) != mode) || !nullable2.HasValue) && ((languageMode == PSLanguageMode.RestrictedLanguage) || (languageMode == PSLanguageMode.ConstrainedLanguage)))
         {
             ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(DiscoveryExceptions.DotSourceNotSupported), "DotSourceNotSupported", ErrorCategory.InvalidOperation, null);
             errorRecord.SetInvocationInfo(invocationInfo);
             throw new CmdletInvocationException(errorRecord);
         }
     }
 }
Example #8
0
 internal PSScriptProperty(string name, string getterScript, string setterScript, PSLanguageMode?languageMode)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     base.name = name;
     if ((getterScript == null) && (setterScript == null))
     {
         throw PSTraceSource.NewArgumentException("getterScript setterScript");
     }
     this.getterScriptText = getterScript;
     this.setterScriptText = setterScript;
     this.languageMode     = languageMode;
 }
Example #9
0
 internal PSScriptProperty(string name, string getterScript, string setterScript, PSLanguageMode? languageMode)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     base.name = name;
     if ((getterScript == null) && (setterScript == null))
     {
         throw PSTraceSource.NewArgumentException("getterScript setterScript");
     }
     this.getterScriptText = getterScript;
     this.setterScriptText = setterScript;
     this.languageMode = languageMode;
 }
Example #10
0
 private void OpenRunspace(Runspace runspace)
 {
     try
     {
         Guid instanceId = this._runspace.InstanceId;
         this._tracer.WriteMessage("Opening runspace ", instanceId.ToString());
         runspace.Open();
         Guid guid = this._runspace.InstanceId;
         this._tracer.WriteMessage("Runspace opened successfully ", guid.ToString());
         PSLanguageMode?nullable = this._languageMode;
         if (nullable.HasValue)
         {
             PSLanguageMode?nullable1 = this._languageMode;
             if (nullable1.HasValue)
             {
                 PowerShell powerShell = PowerShell.Create();
                 using (powerShell)
                 {
                     powerShell.Runspace = runspace;
                     PSLanguageMode?nullable2 = this._languageMode;
                     string         str       = string.Concat("$ExecutionContext.SessionState.LanguageMode = '", nullable2.Value.ToString(), "'");
                     powerShell.AddScript(str);
                     powerShell.Invoke();
                 }
             }
         }
     }
     catch (PSRemotingTransportRedirectException pSRemotingTransportRedirectException)
     {
         Guid instanceId1 = this._runspace.InstanceId;
         this._tracer.WriteMessage("Opening runspace threw  PSRemotingTransportRedirectException", instanceId1.ToString());
     }
     catch (PSRemotingTransportException pSRemotingTransportException1)
     {
         PSRemotingTransportException pSRemotingTransportException = pSRemotingTransportException1;
         Guid guid1 = this._runspace.InstanceId;
         this._tracer.WriteMessage("Opening runspace threw  PSRemotingTransportException", guid1.ToString());
         this._tracer.TraceException(pSRemotingTransportException);
         throw;
     }
     catch (PSRemotingDataStructureException pSRemotingDataStructureException)
     {
         Guid instanceId2 = this._runspace.InstanceId;
         this._tracer.WriteMessage("Opening runspace threw  PSRemotingDataStructureException", instanceId2.ToString());
     }
 }
Example #11
0
        /// <summary>
        /// Constructs runtime based on configuration
        /// </summary>
        /// <param name="configuration"></param>
        public PSWorkflowRuntime(PSWorkflowConfigurationProvider configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            // Only allow FullLanguage or ConstraintLanguage or it can be null in that case system wide default will take an affect
            PSLanguageMode?langMode = configuration.LanguageMode;

            if (langMode != null && langMode.HasValue && (langMode.Value == PSLanguageMode.NoLanguage || langMode.Value == PSLanguageMode.RestrictedLanguage))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.NotSupportedLanguageMode, langMode.Value.ToString()));
            }

            _configuration         = configuration;
            _configuration.Runtime = this;
        }
 internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode?languageMode)
 {
     _languageMode     = languageMode;
     _useJobIPCProcess = true;
     _tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
     _processInstance = new PowerShellProcessInstance();
     _tracer.WriteMessage("END Creating new PowerShell process instance ");
     _runspace = CreateRunspace();
     _tracer.WriteMessage("New runspace created ", _runspace.InstanceId.ToString());
     _timer = new Timer {
         AutoReset = false, Interval = TimeOut
     };
     _timer.Elapsed += TimerElapsed;
     _timer.Interval = activityHostTimeoutSec > 0 ? activityHostTimeoutSec * 1000 : TimeOut;
     _perfCountersMgr.UpdateCounterByValue(
         PSWorkflowPerformanceCounterSetInfo.CounterSetId,
         PSWorkflowPerformanceCounterIds.ActivityHostMgrCreatedProcessesCount);
 }
Example #13
0
        /// <summary>
        /// Begin for obtaining a runspace for the specified ConnectionInfo
        /// </summary>
        /// <param name="connectionInfo">connection info to be used for remote connections</param>
        /// <param name="retryCount">number of times to retry</param>
        /// <param name="callback">optional user defined callback</param>
        /// <param name="state">optional user specified state</param>
        /// <param name="retryInterval">time in milliseconds before the next retry has to be attempted</param>
        /// <returns>async result</returns>
        public override IAsyncResult BeginGetRunspace(WSManConnectionInfo connectionInfo, uint retryCount, uint retryInterval, AsyncCallback callback, object state)
        {
            if (connectionInfo != null)
            {
                throw new InvalidOperationException();
            }

            LocalRunspaceAsyncResult asyncResult = new LocalRunspaceAsyncResult(state, callback, Guid.Empty);

            // Get the source language mode from the activity arguments if available and pass to runspace fetching.
            PSLanguageMode?      sourceLanguageMode = null;
            RunCommandsArguments args = state as RunCommandsArguments;

            if (args != null)
            {
                PSWorkflowRuntime wfRuntime = args.WorkflowHost as PSWorkflowRuntime;
                if (wfRuntime != null)
                {
                    PSWorkflowJob wfJob = wfRuntime.JobManager.GetJob(args.PSActivityContext.JobInstanceId);
                    if (wfJob != null)
                    {
                        sourceLanguageMode = wfJob.SourceLanguageMode;
                    }
                }
            }

            Runspace runspace = AssignRunspaceIfPossible(sourceLanguageMode);

            if (runspace != null)
            {
                asyncResult.Runspace = runspace;
                asyncResult.CompletedSynchronously = true;
                asyncResult.SetAsCompleted(null);
            }
            else
            {
                // queue the request
                _requests.Enqueue(asyncResult);
                CheckAndStartRequestServicingThread();
            }

            return(asyncResult);
        }
        internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true)
        {
            InitialSessionState initialSessionStateWithSharedTypesAndNoFormat = LocalRunspaceProvider.GetInitialSessionStateWithSharedTypesAndNoFormat();

            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }
            if (languageMode.HasValue && languageMode.HasValue)
            {
                initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = languageMode.Value;
            }
            SessionStateVariableEntry sessionStateVariableEntry = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", (object)((bool)1), "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant);

            initialSessionStateWithSharedTypesAndNoFormat.Variables.Add(sessionStateVariableEntry);
            Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionStateWithSharedTypesAndNoFormat);

            if (useCurrentThreadForExecution)
            {
                runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            }
            return(runspace);
        }
Example #15
0
 public PSWorkflowRuntime(PSWorkflowConfigurationProvider configuration)
 {
     this._syncObject = new object();
     if (configuration != null)
     {
         PSLanguageMode?languageMode = configuration.LanguageMode;
         if (!languageMode.HasValue || !languageMode.HasValue || languageMode.Value != PSLanguageMode.NoLanguage && languageMode.Value != PSLanguageMode.RestrictedLanguage)
         {
             this._configuration         = configuration;
             this._configuration.Runtime = this;
             return;
         }
         else
         {
             object[] str = new object[1];
             str[0] = languageMode.Value.ToString();
             throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.NotSupportedLanguageMode, str));
         }
     }
     else
     {
         throw new ArgumentNullException("configuration");
     }
 }
Example #16
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;
                    }
                }
            }
        }
Example #17
0
 internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode? languageMode)
 {
     _languageMode = languageMode;
     _useJobIPCProcess = true;
     _tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
     _processInstance = new PowerShellProcessInstance();
     _tracer.WriteMessage("END Creating new PowerShell process instance ");
     _runspace = CreateRunspace();
     _tracer.WriteMessage("New runspace created ", _runspace.InstanceId.ToString());
     _timer = new Timer {AutoReset = false, Interval = TimeOut};
     _timer.Elapsed += TimerElapsed;
     _timer.Interval = activityHostTimeoutSec > 0 ? activityHostTimeoutSec*1000 : TimeOut;
     _perfCountersMgr.UpdateCounterByValue(
         PSWorkflowPerformanceCounterSetInfo.CounterSetId,
         PSWorkflowPerformanceCounterIds.ActivityHostMgrCreatedProcessesCount);
 }
Example #18
0
 internal PSScriptProperty(string name, string getterScript, string setterScript, PSLanguageMode?languageMode, bool shouldCloneOnAccess) : this(name, getterScript, setterScript, languageMode)
 {
     this.shouldCloneOnAccess = shouldCloneOnAccess;
 }
Example #19
0
 internal LocalRunspaceProvider(int timeoutSeconds, PSLanguageMode?languageMode) : this(timeoutSeconds, DefaultMaxRunspaces, languageMode)
 {
 }
Example #20
0
        internal void InvokeWithPipeImpl(bool createLocalScope, ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior, object dollarUnder, object input, object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, object[] args)
        {
            bool flag;
            bool hasValue;
            ExecutionContext contextFromTLS = this.GetContextFromTLS();
            if (!contextFromTLS.CurrentPipelineStopping)
            {
                if (args == null)
                {
                    args = new object[0];
                }
                if (contextFromTLS._debuggingMode > 0)
                {
                    flag = false;
                }
                else
                {
                    flag = createLocalScope;
                }
                bool flag1 = flag;
                Action<FunctionContext> codeToInvoke = this.GetCodeToInvoke(ref flag1);
                if (codeToInvoke != null)
                {
                    if (outputPipe == null)
                    {
                        Pipe pipe = new Pipe();
                        pipe.NullPipe = true;
                        outputPipe = pipe;
                    }
                    MutableTuple mutableTuple = this.MakeLocalsTuple(flag1);
                    if (dollarUnder != AutomationNull.Value)
                    {
                        mutableTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnder, contextFromTLS);
                    }
                    if (input != AutomationNull.Value)
                    {
                        mutableTuple.SetAutomaticVariable(AutomaticVariable.Input, input, contextFromTLS);
                    }
                    if (scriptThis != AutomationNull.Value)
                    {
                        mutableTuple.SetAutomaticVariable(AutomaticVariable.This, scriptThis, contextFromTLS);
                    }
                    this.SetPSScriptRootAndPSCommandPath(mutableTuple, contextFromTLS);
                    Pipe shellFunctionErrorOutputPipe = contextFromTLS.ShellFunctionErrorOutputPipe;
                    PipelineWriter externalErrorOutput = contextFromTLS.ExternalErrorOutput;
                    CommandOrigin scopeOrigin = contextFromTLS.EngineSessionState.CurrentScope.ScopeOrigin;
                    SessionStateInternal engineSessionState = contextFromTLS.EngineSessionState;
                    PSLanguageMode? nullable = null;
                    PSLanguageMode? languageMode = null;
                    PSLanguageMode? languageMode1 = this.LanguageMode;
                    if (languageMode1.HasValue)
                    {
                        PSLanguageMode? nullable1 = this.LanguageMode;
                        PSLanguageMode pSLanguageMode = contextFromTLS.LanguageMode;
                        if (nullable1.GetValueOrDefault() != pSLanguageMode)
                        {
                            hasValue = true;
                        }
                        else
                        {
                            hasValue = !nullable1.HasValue;
                        }
                        if (hasValue)
                        {
                            nullable = new PSLanguageMode?(contextFromTLS.LanguageMode);
                            languageMode = this.LanguageMode;
                        }
                    }
                    Dictionary<string, PSVariable> strs = null;
                    try
                    {
                        try
                        {
                            InvocationInfo invocationInfo1 = invocationInfo;
                            if (invocationInfo1 == null)
                            {
                                invocationInfo1 = new InvocationInfo(null, ((Ast)this._ast).Extent, contextFromTLS);
                            }
                            mutableTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, invocationInfo1, contextFromTLS);
                            if (this.SessionStateInternal != null)
                            {
                                contextFromTLS.EngineSessionState = this.SessionStateInternal;
                            }
                            ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior1 = errorHandlingBehavior;
                            switch (errorHandlingBehavior1)
                            {
                                case ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe:
                                    {
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                                case ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe:
                                    {
                                        contextFromTLS.ShellFunctionErrorOutputPipe = null;
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                                case ScriptBlock.ErrorHandlingBehavior.SwallowErrors:
                                    {
                                        contextFromTLS.ShellFunctionErrorOutputPipe = null;
                                        contextFromTLS.ExternalErrorOutput = new DiscardingPipelineWriter();
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                                default:
                                    {
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                            }
                        }
                        catch (TargetInvocationException targetInvocationException1)
                        {
                            TargetInvocationException targetInvocationException = targetInvocationException1;
                            throw targetInvocationException.InnerException;
                        }
                    }
					catch(Exception ex)
					{
						var msg = ex.Message;
					}
                    finally
                    {
                        if (nullable.HasValue)
                        {
                            contextFromTLS.LanguageMode = nullable.Value;
                        }
                        contextFromTLS.ShellFunctionErrorOutputPipe = shellFunctionErrorOutputPipe;
                        contextFromTLS.ExternalErrorOutput = externalErrorOutput;
                        contextFromTLS.EngineSessionState.CurrentScope.ScopeOrigin = scopeOrigin;
                        if (!createLocalScope)
                        {
                            if (strs != null)
                            {
                                contextFromTLS.EngineSessionState.CurrentScope.DottedScopes.Pop();
                                foreach (KeyValuePair<string, PSVariable> str in strs)
                                {
                                    if (str.Value == null)
                                    {
                                        contextFromTLS.EngineSessionState.RemoveVariable(str.Key);
                                    }
                                    else
                                    {
                                        contextFromTLS.EngineSessionState.SetVariable(str.Value, false, CommandOrigin.Internal);
                                    }
                                }
                            }
                        }
                        else
                        {
                            contextFromTLS.EngineSessionState.RemoveScope(contextFromTLS.EngineSessionState.CurrentScope);
                        }
                        contextFromTLS.EngineSessionState = engineSessionState;
                    }
                    return;
                }
                else
                {
                    return;
                }
            }
            else
            {
                throw new PipelineStoppedException();
            }
        }
Example #21
0
 internal LocalRunspaceProvider(int timeoutSeconds, int maxRunspaces, PSLanguageMode?languageMode)
 {
     _runspaceCache = new TimeBasedCache <Runspace>(timeoutSeconds);
     _maxRunspaces  = maxRunspaces;
     _languageMode  = languageMode;
 }
Example #22
0
 private ScriptBlock(IParameterMetadataProvider ast, bool isFilter, CompiledScriptBlockData _scriptBlockData)
 {
     this.languageMode = null;
     this._ast = ast;
     this._scriptBlockData = _scriptBlockData;
     this._isFilter = isFilter;
     this.SetLanguageModeFromContext();
 }
Example #23
0
		internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode? languageMode)
		{
			object obj;
			this._syncObject = new object();
			this._tracer = PowerShellTraceSourceFactory.GetTraceSource();
			this._languageMode = languageMode;
			this._useJobIPCProcess = true;
			this._tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
			this._processInstance = new PowerShellProcessInstance();
			this._tracer.WriteMessage("END Creating new PowerShell process instance ");
			this._runspace = this.CreateRunspace();
			Guid instanceId = this._runspace.InstanceId;
			this._tracer.WriteMessage("New runspace created ", instanceId.ToString());
			Timer timer = new Timer();
			timer.AutoReset = false;
			timer.Interval = 300000;
			this._timer = timer;
			this._timer.Elapsed += new ElapsedEventHandler(this.TimerElapsed);
			Timer timer1 = this._timer;
			if (activityHostTimeoutSec > 0)
			{
				obj = activityHostTimeoutSec * 0x3e8;
			}
			else
			{
				obj = 0x493e0;
			}
			timer1.Interval = (double)obj;
			ActivityHostProcess._perfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 21, (long)1, true);
		}
 internal LocalRunspaceProvider(int timeoutSeconds, PSLanguageMode?languageMode) : this(timeoutSeconds, -1, languageMode)
 {
 }
Example #25
0
 private void RunClause(Action<FunctionContext> clause, object dollarUnderbar, object inputToProcess)
 {
     Pipe shellFunctionErrorOutputPipe = base.Context.ShellFunctionErrorOutputPipe;
     PSLanguageMode? nullable = null;
     PSLanguageMode? nullable2 = null;
     if (this._scriptBlock.LanguageMode.HasValue)
     {
         PSLanguageMode? languageMode = this._scriptBlock.LanguageMode;
         PSLanguageMode mode = base.Context.LanguageMode;
         if ((((PSLanguageMode) languageMode.GetValueOrDefault()) != mode) || !languageMode.HasValue)
         {
             nullable = new PSLanguageMode?(base.Context.LanguageMode);
             nullable2 = this._scriptBlock.LanguageMode;
         }
     }
     try
     {
         try
         {
             this.EnterScope();
             if (this._commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
             {
                 base.Context.RedirectErrorPipe(this._commandRuntime.OutputPipe);
             }
             else if (this._commandRuntime.ErrorOutputPipe.IsRedirected)
             {
                 base.Context.RedirectErrorPipe(this._commandRuntime.ErrorOutputPipe);
             }
             if (dollarUnderbar != AutomationNull.Value)
             {
                 this._localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, base.Context);
             }
             if (inputToProcess != AutomationNull.Value)
             {
                 this._localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, base.Context);
             }
             if (nullable2.HasValue)
             {
                 base.Context.LanguageMode = nullable2.Value;
             }
             clause(this._functionContext);
         }
         catch (TargetInvocationException exception)
         {
             throw exception.InnerException;
         }
         finally
         {
             base.Context.RestoreErrorPipe(shellFunctionErrorOutputPipe);
             if (nullable.HasValue)
             {
                 base.Context.LanguageMode = nullable.Value;
             }
             this.ExitScope();
         }
     }
     catch (ExitException exception2)
     {
         if (!this._fromScriptFile || this._rethrowExitException)
         {
             throw;
         }
         this._exitWasCalled = true;
         int argument = (int) exception2.Argument;
         base.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, argument);
         if (argument != 0)
         {
             this._commandRuntime.PipelineProcessor.ExecutionFailed = true;
         }
     }
     catch (TerminateException)
     {
         throw;
     }
     catch (RuntimeException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
         throw;
     }
 }
Example #26
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;
             }
         }
     }
 }
Example #27
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);
        }
Example #28
0
		internal LocalRunspaceProvider(int timeoutSeconds, int maxRunspaces, PSLanguageMode? languageMode)
		{
			this._requests = new ConcurrentQueue<LocalRunspaceAsyncResult>();
			this._callbacks = new ConcurrentQueue<LocalRunspaceAsyncResult>();
			this._tracer = PowerShellTraceSourceFactory.GetTraceSource();
			this._runspaceCache = new TimeBasedCache<Runspace>(timeoutSeconds);
			this._maxRunspaces = maxRunspaces;
			this._languageMode = languageMode;
		}
 private void RunClause(Action<FunctionContext> clause, object dollarUnderbar, object inputToProcess)
 {
     ExecutionContext.CheckStackDepth();
     Pipe shellFunctionErrorOutputPipe = base.Context.ShellFunctionErrorOutputPipe;
     PSLanguageMode? nullable = null;
     PSLanguageMode? nullable2 = null;
     if (this._scriptBlock.LanguageMode.HasValue)
     {
         PSLanguageMode? languageMode = this._scriptBlock.LanguageMode;
         PSLanguageMode mode = base.Context.LanguageMode;
         if ((((PSLanguageMode) languageMode.GetValueOrDefault()) != mode) || !languageMode.HasValue)
         {
             nullable = new PSLanguageMode?(base.Context.LanguageMode);
             nullable2 = this._scriptBlock.LanguageMode;
         }
     }
     try
     {
         CommandOrigin scopeOrigin = base.Context.EngineSessionState.CurrentScope.ScopeOrigin;
         try
         {
             base.Context.EngineSessionState.CurrentScope.ScopeOrigin = base._dontUseScopeCommandOrigin ? CommandOrigin.Internal : base.Command.CommandOrigin;
             if (nullable2.HasValue)
             {
                 base.Context.LanguageMode = nullable2.Value;
             }
             this.EnterScope();
             if (base.commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
             {
                 base.Context.RedirectErrorPipe(base.commandRuntime.OutputPipe);
             }
             else if (base.commandRuntime.ErrorOutputPipe.IsRedirected)
             {
                 base.Context.RedirectErrorPipe(base.commandRuntime.ErrorOutputPipe);
             }
             if (dollarUnderbar != AutomationNull.Value)
             {
                 this._localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, base._context);
             }
             if (inputToProcess != AutomationNull.Value)
             {
                 if (inputToProcess == null)
                 {
                     inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator();
                 }
                 else
                 {
                     IList list = inputToProcess as IList;
                     inputToProcess = (list != null) ? list.GetEnumerator() : LanguagePrimitives.GetEnumerator(inputToProcess);
                 }
                 this._localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, base._context);
             }
             clause(this._functionContext);
         }
         catch (TargetInvocationException exception)
         {
             throw exception.InnerException;
         }
         finally
         {
             base.Context.RestoreErrorPipe(shellFunctionErrorOutputPipe);
             if (nullable.HasValue)
             {
                 base.Context.LanguageMode = nullable.Value;
             }
             base.Context.EngineSessionState.CurrentScope.ScopeOrigin = scopeOrigin;
         }
     }
     catch (ExitException exception2)
     {
         if (!base.FromScriptFile || base._rethrowExitException)
         {
             throw;
         }
         base._exitWasCalled = true;
         int argument = (int) exception2.Argument;
         base.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, argument);
         if (argument != 0)
         {
             base.commandRuntime.PipelineProcessor.ExecutionFailed = true;
         }
     }
     catch (FlowControlException)
     {
         throw;
     }
     catch (RuntimeException exception3)
     {
         base.ManageScriptException(exception3);
         throw;
     }
     catch (Exception exception4)
     {
         CommandProcessorBase.CheckForSevereException(exception4);
         throw base.ManageInvocationException(exception4);
     }
 }
Example #30
0
 protected ScriptBlock(SerializationInfo info, StreamingContext context)
 {
     this.languageMode = null;
 }
        private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess)
        {
            ExecutionContext.CheckStackDepth();

            _anyClauseExecuted = true;
            Pipe oldErrorOutputPipe = this.Context.ShellFunctionErrorOutputPipe;

            // If the script block has a different language mode than the current,
            // change the language mode.
            PSLanguageMode?oldLanguageMode = null;
            PSLanguageMode?newLanguageMode = null;

            if ((_scriptBlock.LanguageMode.HasValue) &&
                (_scriptBlock.LanguageMode != Context.LanguageMode))
            {
                oldLanguageMode = Context.LanguageMode;
                newLanguageMode = _scriptBlock.LanguageMode;
            }

            try
            {
                var oldScopeOrigin = this.Context.EngineSessionState.CurrentScope.ScopeOrigin;

                try
                {
                    this.Context.EngineSessionState.CurrentScope.ScopeOrigin =
                        this._dontUseScopeCommandOrigin ? CommandOrigin.Internal : this.Command.CommandOrigin;

                    // Set the language mode. We do this before EnterScope(), so that the language
                    // mode is appropriately applied for evaluation parameter defaults.
                    if (newLanguageMode.HasValue)
                    {
                        Context.LanguageMode = newLanguageMode.Value;
                    }

                    bool?oldLangModeTransitionStatus = null;
                    try
                    {
                        // If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place.
                        if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && newLanguageMode == PSLanguageMode.FullLanguage)
                        {
                            oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding;
                            Context.LanguageModeTransitionInParameterBinding = true;
                        }

                        EnterScope();
                    }
                    finally
                    {
                        if (oldLangModeTransitionStatus.HasValue)
                        {
                            // Revert the transition state to old value after doing the parameter binding
                            Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus.Value;
                        }
                    }

                    if (commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
                    {
                        Context.RedirectErrorPipe(commandRuntime.OutputPipe);
                    }
                    else if (commandRuntime.ErrorOutputPipe.IsRedirected)
                    {
                        Context.RedirectErrorPipe(commandRuntime.ErrorOutputPipe);
                    }

                    if (dollarUnderbar != AutomationNull.Value)
                    {
                        _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, _context);
                    }
                    else if (_dollarUnderbar != AutomationNull.Value)
                    {
                        _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, _dollarUnderbar, _context);
                    }

                    if (inputToProcess != AutomationNull.Value)
                    {
                        if (inputToProcess == null)
                        {
                            inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator();
                        }
                        else
                        {
                            IList list = inputToProcess as IList;
                            inputToProcess = (list != null)
                                                 ? list.GetEnumerator()
                                                 : LanguagePrimitives.GetEnumerator(inputToProcess);
                        }

                        _localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, _context);
                    }

                    clause(_functionContext);
                }
                catch (TargetInvocationException tie)
                {
                    // DynamicInvoke wraps exceptions, unwrap them here.
                    throw tie.InnerException;
                }
                finally
                {
                    Context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe;

                    if (oldLanguageMode.HasValue)
                    {
                        Context.LanguageMode = oldLanguageMode.Value;
                    }

                    Context.EngineSessionState.CurrentScope.ScopeOrigin = oldScopeOrigin;
                }
            }
            catch (ExitException ee)
            {
                if (!this.FromScriptFile || _rethrowExitException)
                {
                    throw;
                }

                this._exitWasCalled = true;

                int exitCode = (int)ee.Argument;
                this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode);

                if (exitCode != 0)
                {
                    this.commandRuntime.PipelineProcessor.ExecutionFailed = true;
                }
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (RuntimeException e)
            {
                // This method always throws.
                ManageScriptException(e);
            }
            catch (Exception e)
            {
                // This cmdlet threw an exception, so wrap it and bubble it up.
                throw ManageInvocationException(e);
            }
        }
Example #32
0
        private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess)
        {
            Pipe           shellFunctionErrorOutputPipe = base.Context.ShellFunctionErrorOutputPipe;
            PSLanguageMode?nullable  = null;
            PSLanguageMode?nullable2 = null;

            if (this._scriptBlock.LanguageMode.HasValue)
            {
                PSLanguageMode?languageMode = this._scriptBlock.LanguageMode;
                PSLanguageMode mode         = base.Context.LanguageMode;
                if ((((PSLanguageMode)languageMode.GetValueOrDefault()) != mode) || !languageMode.HasValue)
                {
                    nullable  = new PSLanguageMode?(base.Context.LanguageMode);
                    nullable2 = this._scriptBlock.LanguageMode;
                }
            }
            try
            {
                try
                {
                    this.EnterScope();
                    if (this._commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
                    {
                        base.Context.RedirectErrorPipe(this._commandRuntime.OutputPipe);
                    }
                    else if (this._commandRuntime.ErrorOutputPipe.IsRedirected)
                    {
                        base.Context.RedirectErrorPipe(this._commandRuntime.ErrorOutputPipe);
                    }
                    if (dollarUnderbar != AutomationNull.Value)
                    {
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, base.Context);
                    }
                    if (inputToProcess != AutomationNull.Value)
                    {
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, base.Context);
                    }
                    if (nullable2.HasValue)
                    {
                        base.Context.LanguageMode = nullable2.Value;
                    }
                    clause(this._functionContext);
                }
                catch (TargetInvocationException exception)
                {
                    throw exception.InnerException;
                }
                finally
                {
                    base.Context.RestoreErrorPipe(shellFunctionErrorOutputPipe);
                    if (nullable.HasValue)
                    {
                        base.Context.LanguageMode = nullable.Value;
                    }
                    this.ExitScope();
                }
            }
            catch (ExitException exception2)
            {
                if (!this._fromScriptFile || this._rethrowExitException)
                {
                    throw;
                }
                this._exitWasCalled = true;
                int argument = (int)exception2.Argument;
                base.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, argument);
                if (argument != 0)
                {
                    this._commandRuntime.PipelineProcessor.ExecutionFailed = true;
                }
            }
            catch (TerminateException)
            {
                throw;
            }
            catch (RuntimeException)
            {
                throw;
            }
            catch (Exception exception3)
            {
                CommandProcessorBase.CheckForSevereException(exception3);
                throw;
            }
        }
        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));
        }
        private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess)
        {
            ExecutionContext.CheckStackDepth();
            Pipe           shellFunctionErrorOutputPipe = base.Context.ShellFunctionErrorOutputPipe;
            PSLanguageMode?nullable  = null;
            PSLanguageMode?nullable2 = null;

            if (this._scriptBlock.LanguageMode.HasValue)
            {
                PSLanguageMode?languageMode = this._scriptBlock.LanguageMode;
                PSLanguageMode mode         = base.Context.LanguageMode;
                if ((((PSLanguageMode)languageMode.GetValueOrDefault()) != mode) || !languageMode.HasValue)
                {
                    nullable  = new PSLanguageMode?(base.Context.LanguageMode);
                    nullable2 = this._scriptBlock.LanguageMode;
                }
            }
            try
            {
                CommandOrigin scopeOrigin = base.Context.EngineSessionState.CurrentScope.ScopeOrigin;
                try
                {
                    base.Context.EngineSessionState.CurrentScope.ScopeOrigin = base._dontUseScopeCommandOrigin ? CommandOrigin.Internal : base.Command.CommandOrigin;
                    if (nullable2.HasValue)
                    {
                        base.Context.LanguageMode = nullable2.Value;
                    }
                    this.EnterScope();
                    if (base.commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
                    {
                        base.Context.RedirectErrorPipe(base.commandRuntime.OutputPipe);
                    }
                    else if (base.commandRuntime.ErrorOutputPipe.IsRedirected)
                    {
                        base.Context.RedirectErrorPipe(base.commandRuntime.ErrorOutputPipe);
                    }
                    if (dollarUnderbar != AutomationNull.Value)
                    {
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, base._context);
                    }
                    if (inputToProcess != AutomationNull.Value)
                    {
                        if (inputToProcess == null)
                        {
                            inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator();
                        }
                        else
                        {
                            IList list = inputToProcess as IList;
                            inputToProcess = (list != null) ? list.GetEnumerator() : LanguagePrimitives.GetEnumerator(inputToProcess);
                        }
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, base._context);
                    }
                    clause(this._functionContext);
                }
                catch (TargetInvocationException exception)
                {
                    throw exception.InnerException;
                }
                finally
                {
                    base.Context.RestoreErrorPipe(shellFunctionErrorOutputPipe);
                    if (nullable.HasValue)
                    {
                        base.Context.LanguageMode = nullable.Value;
                    }
                    base.Context.EngineSessionState.CurrentScope.ScopeOrigin = scopeOrigin;
                }
            }
            catch (ExitException exception2)
            {
                if (!base.FromScriptFile || base._rethrowExitException)
                {
                    throw;
                }
                base._exitWasCalled = true;
                int argument = (int)exception2.Argument;
                base.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, argument);
                if (argument != 0)
                {
                    base.commandRuntime.PipelineProcessor.ExecutionFailed = true;
                }
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (RuntimeException exception3)
            {
                base.ManageScriptException(exception3);
                throw;
            }
            catch (Exception exception4)
            {
                CommandProcessorBase.CheckForSevereException(exception4);
                throw base.ManageInvocationException(exception4);
            }
        }
Example #35
0
        /// <summary>
        /// Prepares the command. Encodes the command-line parameters
        /// JonN     2003-04-02 Split from Execute()
        /// </summary>
        /// <exception cref="ParameterBindingException">
        /// If any parameters fail to bind,
        /// or
        /// If any mandatory parameters are missing.
        /// </exception>
        /// <exception cref="MetadataException">
        /// If there is an error generating the metadata for dynamic parameters.
        /// </exception>
        internal override void Prepare(IDictionary psDefaultParameterValues)
        {
            // Note that Prepare() and DoBegin() should NOT be combined.
            // Reason: Encoding of commandline parameters happen as part of
            // Prepare(). If they are combined, the first command's
            // DoBegin() will be called before the next command's Prepare().
            // Since BeginProcessing() can write objects to the downstream
            // commandlet, it will end up calling DoExecute() (from Pipe.Add())
            // before Prepare.

            // Steps involved:
            // (1) Backup the default parameter values
            // (2) Handle input objects - add them to the input pipe.
            // (3) Bind the parameters to properties (encoding)
            // (4) Execute the command method using DoExecute() (repeatedly)

            this.CmdletParameterBinderController.DefaultParameterValues = psDefaultParameterValues;

            Diagnostics.Assert(
                this.Command != null,
                "CommandProcessor did not initialize Command\n" + this.CommandInfo.Name);

            PSLanguageMode?oldLanguageMode             = null;
            bool?          oldLangModeTransitionStatus = null;

            try
            {
                var scriptCmdletInfo = this.CommandInfo as IScriptCommandInfo;
                if (scriptCmdletInfo != null &&
                    scriptCmdletInfo.ScriptBlock.LanguageMode.HasValue &&
                    scriptCmdletInfo.ScriptBlock.LanguageMode != Context.LanguageMode)
                {
                    // Set the language mode before parameter binding if it's necessary for a script cmdlet, so that the language
                    // mode is appropriately applied for evaluating parameter defaults and argument type conversion.
                    oldLanguageMode      = Context.LanguageMode;
                    Context.LanguageMode = scriptCmdletInfo.ScriptBlock.LanguageMode.Value;

                    // If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place.
                    if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && Context.LanguageMode == PSLanguageMode.FullLanguage)
                    {
                        oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding;
                        Context.LanguageModeTransitionInParameterBinding = true;
                    }
                }

                BindCommandLineParameters();
            }
            finally
            {
                if (oldLanguageMode.HasValue)
                {
                    // Revert to the original language mode after doing the parameter binding
                    Context.LanguageMode = oldLanguageMode.Value;
                }

                if (oldLangModeTransitionStatus.HasValue)
                {
                    // Revert the transition state to old value after doing the parameter binding
                    Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus.Value;
                }
            }
        }
Example #36
0
 internal LocalRunspaceProvider(int timeoutSeconds, int maxRunspaces, PSLanguageMode? languageMode)
 {
     _runspaceCache = new TimeBasedCache<Runspace>(timeoutSeconds);
     _maxRunspaces = maxRunspaces;
     _languageMode = languageMode;
 }