Exemple #1
0
 internal FunctionInfo(FunctionInfo other) : base(other)
 {
     this.verb = string.Empty;
     this.noun = string.Empty;
     this._helpFile = string.Empty;
     this.CopyFieldsFromOther(other);
 }
Exemple #2
0
 public void Set(string name, ScriptBlock function, string description = "")
 {
     var qualName = new SessionStateScope<FunctionInfo>.QualifiedName(name);
     var info = new FunctionInfo(qualName.UnqualifiedName, function);
     info.Description = description;
     _scope.Set(name, info, true, true);
 }
Exemple #3
0
 private void CopyFieldsFromOther(FunctionInfo other)
 {
     this._scriptBlock = other._scriptBlock;
     this._description = other._description;
     this._options = other._options;
     this._helpFile = other._helpFile;
 }
Exemple #4
0
 internal FunctionInfo(string name, FunctionInfo other) : base(name, other)
 {
     this.verb = string.Empty;
     this.noun = string.Empty;
     this._helpFile = string.Empty;
     this.CopyFieldsFromOther(other);
     CmdletInfo.SplitCmdletName(name, out this.verb, out this.noun);
 }
Exemple #5
0
 protected internal override void Update(FunctionInfo function, bool force, ScopedItemOptions options, string helpFile)
 {
     WorkflowInfo other = function as WorkflowInfo;
     if (other == null)
     {
         throw PSTraceSource.NewArgumentException("function");
     }
     base.Update(function, force, options, helpFile);
     this.CopyFields(other);
 }
        } // SetWorkflowRaw

        /// <summary>
        /// Set a function in the current scope of session state.
        /// </summary>
        /// 
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        /// 
        /// <param name="function">
        /// The new value of the function being set.
        /// </param>
        /// 
        /// <param name="originalFunction">
        /// The original function (if any) from which the ScriptBlock is derived.
        /// </param>
        /// 
        /// <param name="options">
        /// The options to set on the function.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the function will be set even if its ReadOnly.
        /// </param>
        /// 
        /// <param name="origin">
        /// Origin of the caller of this API
        /// </param>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="function"/> is null.
        /// </exception>
        /// 
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is read-only or constant.
        /// </exception> 
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum number of functions have been reached for this scope.
        /// </exception>
        /// 
        internal FunctionInfo SetFunction(
            string name,
            ScriptBlock function,
            FunctionInfo originalFunction,
            ScopedItemOptions options,
            bool force,
            CommandOrigin origin)
        {
            return SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext, null);
        } // SetFunction
Exemple #7
0
        /// <summary>
        /// This is a copy constructor, used primarily for get-command.
        /// </summary>
        internal FunctionInfo(string name, FunctionInfo other)
            : base(name, other)
        {
            CopyFieldsFromOther(other);

            // Get the verb and noun from the name
            CmdletInfo.SplitCmdletName(name, out _verb, out _noun);
        }
Exemple #8
0
 internal static CommandProcessorBase CreateCommandProcessorForScript(ScriptBlock scriptblock, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
 {
     sessionState = sessionState ?? (scriptblock.SessionStateInternal ?? context.EngineSessionState);
     if (scriptblock.UsesCmdletBinding)
     {
         FunctionInfo scriptCommandInfo = new FunctionInfo("", scriptblock, context);
         return GetScriptAsCmdletProcessor(scriptCommandInfo, context, useNewScope, false, sessionState);
     }
     return new DlrScriptCommandProcessor(scriptblock, context, useNewScope, CommandOrigin.Internal, sessionState);
 }
 internal DlrScriptCommandProcessor(FunctionInfo functionInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState) : base(functionInfo, context, useNewScope, sessionState)
 {
     this._input = new ArrayList();
     this.Init();
 }
Exemple #10
0
        internal CommandProcessorBase CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, bool addToHistory, CommandOrigin origin)
        {
            CommandProcessorBase base2;
            string str2;
            HelpCategory category;
            if (!this.IsScript)
            {
                if (this._useLocalScope.HasValue && !this._useLocalScope.Value)
                {
                    switch (executionContext.LanguageMode)
                    {
                        case PSLanguageMode.RestrictedLanguage:
                        case PSLanguageMode.NoLanguage:
                            throw new RuntimeException(StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed, new object[] { "UseLocalScope", PSLanguageMode.RestrictedLanguage.ToString(), PSLanguageMode.NoLanguage.ToString() }));
                    }
                }
                base2 = commandFactory.CreateCommand(this.CommandText, origin, this._useLocalScope);
            }
            else
            {
                if (executionContext.LanguageMode == PSLanguageMode.NoLanguage)
                {
                    throw InterpreterError.NewInterpreterException(this.CommandText, typeof(ParseException), null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed, new object[0]);
                }
                ScriptBlock function = executionContext.Engine.ParseScriptBlock(this.CommandText, addToHistory);
                switch (executionContext.LanguageMode)
                {
                    case PSLanguageMode.FullLanguage:
                    case PSLanguageMode.ConstrainedLanguage:
                        break;

                    case PSLanguageMode.RestrictedLanguage:
                        function.CheckRestrictedLanguage(null, null, false);
                        break;

                    default:
                        throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }
                if (function.UsesCmdletBinding)
                {
                    FunctionInfo scriptCommandInfo = new FunctionInfo("", function, executionContext);
                    bool? nullable = this._useLocalScope;
                    base2 = new CommandProcessor(scriptCommandInfo, executionContext, nullable.HasValue ? nullable.GetValueOrDefault() : false, false, executionContext.EngineSessionState);
                }
                else
                {
                    bool? nullable2 = this._useLocalScope;
                    base2 = new DlrScriptCommandProcessor(function, executionContext, nullable2.HasValue ? nullable2.GetValueOrDefault() : false, CommandOrigin.Runspace, executionContext.EngineSessionState);
                }
            }
            CommandParameterCollection parameters = this.Parameters;
            if (parameters != null)
            {
                bool forNativeCommand = base2 is NativeCommandProcessor;
                foreach (CommandParameter parameter in parameters)
                {
                    CommandParameterInternal internal2 = CommandParameter.ToCommandParameterInternal(parameter, forNativeCommand);
                    base2.AddParameter(internal2);
                }
            }
            if (base2.IsHelpRequested(out str2, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(executionContext, str2, category);
            }
            this.SetMergeSettingsOnCommandProcessor(base2);
            return base2;
        }
Exemple #11
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, string helpFile)
 {
     return this.SetFunction(name, function, originalFunction, options, force, origin, this.ExecutionContext, helpFile, false);
 }
Exemple #12
0
 public void Set(FunctionInfo info)
 {
     _scope.SetAtScope(info, "local", true);
 }
Exemple #13
0
 /// <summary/>
 protected internal virtual void Update(FunctionInfo newFunction, bool force, ScopedItemOptions options, string helpFile)
 {
     Update(newFunction.ScriptBlock, force, options, helpFile);
 }
Exemple #14
0
 /// <summary>
 /// This is a copy constructor, used primarily for get-command.
 /// </summary>
 internal FunctionInfo(FunctionInfo other)
     : base(other)
 {
     CopyFieldsFromOther(other);
 }
 internal DlrScriptCommandProcessor(FunctionInfo functionInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
     : base(functionInfo, context, useNewScope, sessionState)
 {
     Init();
 }
Exemple #16
0
        internal CommandProcessorBase LookupCommandProcessor(
            CommandInfo commandInfo,
            CommandOrigin commandOrigin,
            bool?useLocalScope)
        {
            if (commandInfo.CommandType == CommandTypes.Alias && (commandOrigin == CommandOrigin.Internal || commandInfo.Visibility == SessionStateEntryVisibility.Public))
            {
                AliasInfo aliasInfo = (AliasInfo)commandInfo;
                commandInfo = aliasInfo.ResolvedCommand;
                if (commandInfo == null)
                {
                    CommandNotFoundException notFoundException = new CommandNotFoundException(aliasInfo.Name, (Exception)null, "AliasNotResolvedException", new object[1]
                    {
                        (object)aliasInfo.UnresolvedCommandName
                    });
                    CommandDiscovery.tracer.TraceException((Exception)notFoundException);
                    throw notFoundException;
                }
                PSSQMAPI.IncrementData(CommandTypes.Alias);
            }
            CommandDiscovery.ShouldRun(this._context, (PSHost)this._context.EngineHostInterface, commandInfo, commandOrigin);
            CommandProcessorBase commandProcessorBase;

            switch (commandInfo.CommandType)
            {
            case CommandTypes.Function:
            case CommandTypes.Filter:
                FunctionInfo     functionInfo = (FunctionInfo)commandInfo;
                ExecutionContext context1     = this._context;
                bool?            nullable1    = useLocalScope;
                int num1 = nullable1.HasValue ? (nullable1.GetValueOrDefault() ? 1 : 0) : 1;
                commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(functionInfo, context1, num1 != 0);
                break;

            case CommandTypes.Cmdlet:
                commandProcessorBase = (CommandProcessorBase) new CommandProcessor((CmdletInfo)commandInfo, this._context);
                break;

            case CommandTypes.ExternalScript:
                ExternalScriptInfo externalScriptInfo = (ExternalScriptInfo)commandInfo;
                externalScriptInfo.SignatureChecked = true;
                try
                {
                    if (!this._context.IsSingleShell)
                    {
                        ExternalScriptInfo scriptInfo = externalScriptInfo;
                        bool?nullable2 = useLocalScope;
                        int  num2      = nullable2.HasValue ? (nullable2.GetValueOrDefault() ? 1 : 0) : 1;
                        commandProcessorBase = this.CreateScriptProcessorForMiniShell(scriptInfo, num2 != 0);
                        break;
                    }
                    ExternalScriptInfo           scriptInfo1           = externalScriptInfo;
                    RunspaceConfigForSingleShell runspaceConfiguration = this._context.RunspaceConfiguration as RunspaceConfigForSingleShell;
                    bool?nullable3 = useLocalScope;
                    int  num3      = nullable3.HasValue ? (nullable3.GetValueOrDefault() ? 1 : 0) : 1;
                    commandProcessorBase = this.CreateScriptProcessorForSingleShell(scriptInfo1, runspaceConfiguration, num3 != 0);
                    break;
                }
                catch (ScriptRequiresSyntaxException ex)
                {
                    CommandNotFoundException notFoundException = new CommandNotFoundException(ex.Message, (Exception)ex);
                    CommandDiscovery.tracer.TraceException((Exception)notFoundException);
                    throw notFoundException;
                }
                catch (PSArgumentException ex)
                {
                    CommandNotFoundException notFoundException = new CommandNotFoundException(commandInfo.Name, (Exception)ex, "ScriptRequiresInvalidFormat", new object[0]);
                    CommandDiscovery.tracer.TraceException((Exception)notFoundException);
                    throw notFoundException;
                }

            case CommandTypes.Application:
                commandProcessorBase = (CommandProcessorBase) new NativeCommandProcessor((ApplicationInfo)commandInfo, this._context);
                break;

            case CommandTypes.Script:
                ScriptInfo       scriptInfo2 = (ScriptInfo)commandInfo;
                ExecutionContext context2    = this._context;
                bool?            nullable4   = useLocalScope;
                int num4 = nullable4.HasValue ? (nullable4.GetValueOrDefault() ? 1 : 0) : 1;
                commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(scriptInfo2, context2, num4 != 0);
                break;

            default:
                CommandNotFoundException notFoundException1 = new CommandNotFoundException(commandInfo.Name, (Exception)null, "CommandNotFoundException", new object[0]);
                CommandDiscovery.tracer.TraceException((Exception)notFoundException1);
                throw notFoundException1;
            }
            PSSQMAPI.IncrementData(commandInfo.CommandType);
            commandProcessorBase.Command.CommandOriginInternal       = commandOrigin;
            commandProcessorBase.Command.MyInvocation.InvocationName = commandInfo.Name;
            return(commandProcessorBase);
        }
Exemple #17
0
 /// <summary>
 /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
 /// sets based on an argument list (so we can get the dynamic parameters.)
 /// </summary>
 internal override CommandInfo CreateGetCommandCopy(object[] arguments)
 {
     FunctionInfo copy = new FunctionInfo(this) { IsGetCommandCopy = true, Arguments = arguments };
     return copy;
 }
        } // SetFunction

        /// <summary>
        /// Set a function in the current scope of session state.
        /// </summary>
        /// 
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        /// 
        /// <param name="function">
        /// The new value of the function being set.
        /// </param>
        /// 
        /// <param name="originalFunction">
        /// The original function (if any) from which the ScriptBlock is derived.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the function will be set even if its ReadOnly.
        /// </param>
        /// 
        /// <param name="origin">
        /// The origin of the caller
        /// </param>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// or
        /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see>
        /// or <see cref="FunctionInfo">FunctionInfo</see>
        /// </exception>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="function"/> is null.
        /// </exception>
        /// 
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is read-only or constant.
        /// </exception> 
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum number of functions have been reached for this scope.
        /// </exception>
        /// 
        internal FunctionInfo SetFunction(
            string name,
            ScriptBlock function,
            FunctionInfo originalFunction,
            bool force,
            CommandOrigin origin)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            if (function == null)
            {
                throw PSTraceSource.NewArgumentNullException("function");
            }

            string originalName = name;

            FunctionLookupPath path = new FunctionLookupPath(name);
            name = path.UnqualifiedPath;

            if (String.IsNullOrEmpty(name))
            {
                SessionStateException exception =
                    new SessionStateException(
                        originalName,
                        SessionStateCategory.Function,
                        "ScopedFunctionMustHaveName",
                        SessionStateStrings.ScopedFunctionMustHaveName,
                        ErrorCategory.InvalidArgument);

                throw exception;
            }

            ScopedItemOptions options = ScopedItemOptions.None;
            if (path.IsPrivate)
            {
                options |= ScopedItemOptions.Private;
            }


            FunctionScopeItemSearcher searcher =
                new FunctionScopeItemSearcher(
                    this,
                    path,
                    origin);

            FunctionInfo result = null;

            SessionStateScope scope = searcher.InitialScope;

            if (searcher.MoveNext())
            {
                scope = searcher.CurrentLookupScope;
                name = searcher.Name;

                if (path.IsPrivate)
                {
                    // Need to add the Private flag
                    FunctionInfo existingFunction = scope.GetFunction(name);
                    options |= existingFunction.Options;
                    result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }
            else
            {
                if (path.IsPrivate)
                {
                    result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }
            return result;
        }
Exemple #19
0
        private void AddInitialSessionCommands()
        {

            foreach (SessionStateCommandEntry cmdEntry in _initialSessionState.Commands)
            {
                if (cmdEntry is SessionStateAliasEntry)
                {
                    var aliasEntry = (SessionStateAliasEntry)cmdEntry;
                    var aliasInfo = new AliasInfo(aliasEntry.Name, aliasEntry.Definition, aliasEntry.Description,
                                                  CommandManager, aliasEntry.Options);
                    ExecutionContext.SessionState.Alias.Set(aliasInfo, "global");
                }
                else if (cmdEntry is SessionStateFunctionEntry)
                {
                    var funEntry = (SessionStateFunctionEntry)cmdEntry;
                    var scriptBlock = new ScriptBlock(Parser.ParseInput(funEntry.Definition));
                    var funInfo = new FunctionInfo(funEntry.Name, scriptBlock, null, funEntry.Options);
                    ExecutionContext.SessionState.Function.Set(funInfo);
                }
            }
        }
        private static FunctionInfo CreateFunction(string name, ScriptBlock function, FunctionInfo originalFunction,
            ScopedItemOptions options, ExecutionContext context, string helpFile)
        {
            FunctionInfo newValue = null;

            if (options == ScopedItemOptions.Unspecified)
            {
                options = ScopedItemOptions.None;
            }

            // First use the copy constructors
            if (originalFunction is FilterInfo)
            {
                newValue = new FilterInfo(name, (FilterInfo)originalFunction);
            }
            else if (originalFunction is WorkflowInfo)
            {
                newValue = new WorkflowInfo(name, (WorkflowInfo)originalFunction);
            }
            else if (originalFunction is ConfigurationInfo)
            {
                newValue = new ConfigurationInfo(name, (ConfigurationInfo)originalFunction);
            }
            else if (originalFunction != null)
            {
                newValue = new FunctionInfo(name, originalFunction);
            }

            // Then use the creation constructors - workflows don't get here because the workflow info
            // is created during compilation.
            else if (function.IsFilter) { newValue = new FilterInfo(name, function, options, context, helpFile); }
            else if (function.IsConfiguration)
            {
                newValue = new ConfigurationInfo(name, function, options, context, helpFile, function.IsMetaConfiguration());
            }
            else newValue = new FunctionInfo(name, function, options, context, helpFile);

            return newValue;
        }
Exemple #21
0
        /// <summary>
        /// Set a function in the current scope of session state.
        /// </summary>
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        /// <param name="function">
        /// The new value of the function being set.
        /// </param>
        /// <param name="originalFunction">
        /// The original function (if any) from which the ScriptBlock is derived.
        /// </param>
        /// <param name="force">
        /// If true, the function will be set even if its ReadOnly.
        /// </param>
        /// <param name="origin">
        /// The origin of the caller
        /// </param>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// or
        /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see>
        /// or <see cref="FunctionInfo">FunctionInfo</see>
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="function"/> is null.
        /// </exception>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is read-only or constant.
        /// </exception>
        internal FunctionInfo SetFunction(
            string name,
            ScriptBlock function,
            FunctionInfo originalFunction,
            bool force,
            CommandOrigin origin)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException(nameof(name));
            }

            if (function == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(function));
            }

            string originalName = name;

            FunctionLookupPath path = new FunctionLookupPath(name);

            name = path.UnqualifiedPath;

            if (string.IsNullOrEmpty(name))
            {
                SessionStateException exception =
                    new SessionStateException(
                        originalName,
                        SessionStateCategory.Function,
                        "ScopedFunctionMustHaveName",
                        SessionStateStrings.ScopedFunctionMustHaveName,
                        ErrorCategory.InvalidArgument);

                throw exception;
            }

            ScopedItemOptions options = ScopedItemOptions.None;

            if (path.IsPrivate)
            {
                options |= ScopedItemOptions.Private;
            }

            FunctionScopeItemSearcher searcher =
                new FunctionScopeItemSearcher(
                    this,
                    path,
                    origin);

            FunctionInfo result = null;

            SessionStateScope scope = searcher.InitialScope;

            if (searcher.MoveNext())
            {
                scope = searcher.CurrentLookupScope;
                name  = searcher.Name;

                if (path.IsPrivate)
                {
                    // Need to add the Private flag
                    FunctionInfo existingFunction = scope.GetFunction(name);
                    options |= existingFunction.Options;
                    result   = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }
            else
            {
                if (path.IsPrivate)
                {
                    result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }

            return(result);
        }
Exemple #22
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, bool force, CommandOrigin origin)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     if (function == null)
     {
         throw PSTraceSource.NewArgumentNullException("function");
     }
     string itemName = name;
     FunctionLookupPath lookupPath = new FunctionLookupPath(name);
     name = lookupPath.UnqualifiedPath;
     if (string.IsNullOrEmpty(name))
     {
         SessionStateException exception = new SessionStateException(itemName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument, new object[0]);
         throw exception;
     }
     ScopedItemOptions none = ScopedItemOptions.None;
     if (lookupPath.IsPrivate)
     {
         none |= ScopedItemOptions.Private;
     }
     FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher(this, lookupPath, origin);
     SessionStateScope initialScope = searcher.InitialScope;
     if (searcher.MoveNext())
     {
         initialScope = searcher.CurrentLookupScope;
         name = searcher.Name;
         if (!lookupPath.IsPrivate)
         {
             return initialScope.SetFunction(name, function, force, origin, this.ExecutionContext);
         }
         FunctionInfo info2 = initialScope.GetFunction(name);
         FunctionInfo info3 = info2;
         if (info3 != null)
         {
             none |= info3.Options;
         }
         else
         {
             none |= ((FilterInfo) info2).Options;
         }
         return initialScope.SetFunction(name, function, originalFunction, none, force, origin, this.ExecutionContext);
     }
     if (lookupPath.IsPrivate)
     {
         return initialScope.SetFunction(name, function, originalFunction, none, force, origin, this.ExecutionContext);
     }
     return initialScope.SetFunction(name, function, force, origin, this.ExecutionContext);
 }
Exemple #23
0
        } // FunctionInfo ctor

        /// <summary>
        /// This is a copy constructor, used primarily for get-command.
        /// </summary>
        internal FunctionInfo(FunctionInfo other)
            : base(other)
        {
            CopyFieldsFromOther(other);
        }
Exemple #24
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context, string helpFile, bool isPreValidated)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     if (function == null)
     {
         throw PSTraceSource.NewArgumentNullException("function");
     }
     string itemName = name;
     FunctionLookupPath lookupPath = new FunctionLookupPath(name);
     name = lookupPath.UnqualifiedPath;
     if (string.IsNullOrEmpty(name))
     {
         SessionStateException exception = new SessionStateException(itemName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument, new object[0]);
         throw exception;
     }
     if (lookupPath.IsPrivate)
     {
         options |= ScopedItemOptions.Private;
     }
     FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher(this, lookupPath, origin);
     return searcher.InitialScope.SetFunction(name, function, originalFunction, options, force, origin, context, helpFile);
 }
Exemple #25
0
 private static bool IsFunctionOptionSet(FunctionInfo function, ScopedItemOptions options)
 {
     return ((function.Options & options) != ScopedItemOptions.None);
 }
Exemple #26
0
 private FunctionInfo createFunction(string name, string description = "",
                                     ScopedItemOptions options = ScopedItemOptions.None)
 {
     var info = new FunctionInfo(name, null, null, options);
     info.Description = description;
     return info;
 }
Exemple #27
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context, string helpFile)
 {
     return this.SetFunction(name, function, originalFunction, options, force, origin, context, helpFile, new Func<string, ScriptBlock, FunctionInfo, ScopedItemOptions, System.Management.Automation.ExecutionContext, string, FunctionInfo>(SessionStateScope.CreateFunction));
 }
Exemple #28
0
 internal static CommandProcessorBase CreateCommandProcessorForScript(FunctionInfo functionInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
 {
     sessionState = sessionState ?? (functionInfo.ScriptBlock.SessionStateInternal ?? context.EngineSessionState);
     CommandProcessorBase base2 = GetScriptAsCmdletProcessor(functionInfo, context, useNewScope, false, sessionState);
     if (base2 != null)
     {
         return base2;
     }
     return new DlrScriptCommandProcessor(functionInfo, context, useNewScope, sessionState);
 }
        /// <summary>
        /// Sets an function to the given function declaration.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        ///
        /// <param name="function">
        /// The script block that the function should represent.
        /// </param>
        ///
        /// <param name="originalFunction">
        /// The original function (if any) from which the scriptblock was derived.
        /// </param>
        ///
        /// <param name="options">
        /// The options that should be applied to the function.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the function will be set even if its ReadOnly.
        /// </param>
        /// 
        /// <param name="origin">
        /// The origin of the caller of this API
        /// </param>
        /// 
        /// <param name="context">
        /// The execution context for the function/filter.
        /// </param>
        /// 
        /// <param name="helpFile">
        /// The name of the help file associated with the function.
        /// </param>
        /// 
        /// <param name="functionFactory">
        /// Function to create the FunctionInfo.
        /// </param>
        ///
        /// <returns>
        /// A FunctionInfo that is either a FilterInfo or FunctionInfo representing the
        /// function or filter.
        /// </returns>
        ///
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is read-only or constant.
        /// </exception> 
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum number of functions have been reached for this scope.
        /// </exception>
        /// 
        internal FunctionInfo SetFunction(
            string name,
            ScriptBlock function,
            FunctionInfo originalFunction,
            ScopedItemOptions options,
            bool force,
            CommandOrigin origin,
            ExecutionContext context,
            string helpFile,
            Func<string, ScriptBlock, FunctionInfo, ScopedItemOptions, ExecutionContext, string, FunctionInfo> functionFactory)
        {
            Diagnostics.Assert(
                name != null,
                "The caller should verify the name");

            var functionInfos = GetFunctions();
            FunctionInfo existingValue;
            FunctionInfo result;
            if (!functionInfos.TryGetValue(name, out existingValue))
            {
                if (functionInfos.Count > FunctionCapacity.FastValue - 1)
                {
                    SessionStateOverflowException e =
                        new SessionStateOverflowException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionOverflow",
                                SessionStateStrings.FunctionOverflow,
                                FunctionCapacity.FastValue);

                    throw e;
                }

                result = functionFactory(name, function, originalFunction, options, context, helpFile);
                functionInfos[name] = result;

                if (IsFunctionOptionSet(result, ScopedItemOptions.AllScope))
                {
                    GetAllScopeFunctions()[name] = result;
                }
            }
            else
            {
                // Make sure the function isn't constant or readonly

                SessionState.ThrowIfNotVisible(origin, existingValue);

                if (IsFunctionOptionSet(existingValue, ScopedItemOptions.Constant) ||
                    (!force && IsFunctionOptionSet(existingValue, ScopedItemOptions.ReadOnly)))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionNotWritable",
                                SessionStateStrings.FunctionNotWritable);

                    throw e;
                }

                // Ensure we are not trying to set the function to constant as this can only be
                // done at creation time.

                if ((options & ScopedItemOptions.Constant) != 0)
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionCannotBeMadeConstant",
                                SessionStateStrings.FunctionCannotBeMadeConstant);

                    throw e;
                }

                // Ensure we are not trying to remove the AllScope option

                if ((options & ScopedItemOptions.AllScope) == 0 &&
                    IsFunctionOptionSet(existingValue, ScopedItemOptions.AllScope))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionAllScopeOptionCannotBeRemoved",
                                SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved);

                    throw e;
                }

                FunctionInfo existingFunction = existingValue;
                FunctionInfo newValue = null;

                // If the function type changes (i.e.: function to workflow or back)
                // then we need to blast what was there
                newValue = functionFactory(name, function, originalFunction, options, context, helpFile);

                bool changesFunctionType = existingFunction.GetType() != newValue.GetType();

                // Since the options are set after the script block, we have to
                // forcefully apply the script block if the options will be
                // set to not being ReadOnly
                if (changesFunctionType ||
                    ((existingFunction.Options & ScopedItemOptions.ReadOnly) != 0 && force))
                {
                    result = newValue;
                    functionInfos[name] = newValue;
                }
                else
                {
                    bool applyForce = force || (options & ScopedItemOptions.ReadOnly) == 0;

                    existingFunction.Update(newValue, applyForce, options, helpFile);
                    result = existingFunction;
                }
            }

            return result;
        } // SetFunction
Exemple #30
0
 private static FunctionInfo CreateFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, System.Management.Automation.ExecutionContext context, string helpFile)
 {
     if (options == ScopedItemOptions.Unspecified)
     {
         options = ScopedItemOptions.None;
     }
     if (originalFunction is FilterInfo)
     {
         return new FilterInfo(name, (FilterInfo) originalFunction);
     }
     if (originalFunction is WorkflowInfo)
     {
         return new WorkflowInfo(name, (WorkflowInfo) originalFunction);
     }
     if (originalFunction != null)
     {
         return new FunctionInfo(name, originalFunction);
     }
     if (function.IsFilter)
     {
         return new FilterInfo(name, function, options, context, helpFile);
     }
     return new FunctionInfo(name, function, options, context, helpFile);
 }
Exemple #31
0
 private void CopyFieldsFromOther(FunctionInfo other)
 {
     _verb = other._verb;
     _noun = other._noun;
     _scriptBlock = other._scriptBlock;
     _description = other._description;
     _options = other._options;
     _helpFile = other._helpFile;
 }
Exemple #32
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context)
 {
     return this.SetFunction(name, function, originalFunction, options, force, origin, context, null);
 }
Exemple #33
0
 protected internal virtual void Update(FunctionInfo newFunction, bool force, ScopedItemOptions options, string helpFile)
 {
     this.Update(newFunction.ScriptBlock, force, options, helpFile);
 }
Exemple #34
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context, string helpFile, Func<string, ScriptBlock, FunctionInfo, ScopedItemOptions, System.Management.Automation.ExecutionContext, string, FunctionInfo> functionFactory)
 {
     if (!this.GetFunctions().ContainsKey(name))
     {
         if (this.GetFunctions().Count > (this.FunctionCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Function, "FunctionOverflow", SessionStateStrings.FunctionOverflow, new object[] { this.FunctionCapacity.FastValue });
             throw exception;
         }
         FunctionInfo info = functionFactory(name, function, originalFunction, options, context, helpFile);
         this.GetFunctions()[name] = info;
         if (IsFunctionOptionSet(info, ScopedItemOptions.AllScope))
         {
             this.GetAllScopeFunctions()[name] = info;
         }
     }
     else
     {
         FunctionInfo valueToCheck = this.GetFunctions()[name];
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         if (IsFunctionOptionSet(valueToCheck, ScopedItemOptions.Constant) || (!force && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.ReadOnly)))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionNotWritable", SessionStateStrings.FunctionNotWritable);
             throw exception2;
         }
         if ((options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionCannotBeMadeConstant", SessionStateStrings.FunctionCannotBeMadeConstant);
             throw exception3;
         }
         if (((options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.AllScope))
         {
             SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionAllScopeOptionCannotBeRemoved", SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved);
             throw exception4;
         }
         FunctionInfo info3 = valueToCheck;
         FunctionInfo newFunction = null;
         if (info3 != null)
         {
             newFunction = functionFactory(name, function, originalFunction, options, context, helpFile);
             if (!info3.GetType().Equals(newFunction.GetType()) || (((info3.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && force))
             {
                 this.GetFunctions()[name] = newFunction;
             }
             else
             {
                 bool flag2 = force || ((options & ScopedItemOptions.ReadOnly) == ScopedItemOptions.None);
                 info3.Update(newFunction, flag2, options, helpFile);
             }
         }
     }
     return this.GetFunctions()[name];
 }
 internal DlrScriptCommandProcessor(FunctionInfo functionInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
     : base(functionInfo, context, useNewScope, sessionState)
 {
     Init();
 }