internal CommandNotFoundException(
     string commandName,
     Exception innerException,
     string errorIdAndResourceId,
     params object[] messageArgs)
     : base(CommandNotFoundException.BuildMessage(commandName, errorIdAndResourceId, messageArgs), innerException)
 {
     this.commandName = commandName;
     this._errorId    = errorIdAndResourceId;
 }
Ejemplo n.º 2
0
        private void Init(CmdletInfo cmdletInformation)
        {
            Cmdlet    cmdlet               = (Cmdlet)null;
            Exception exception            = (Exception)null;
            string    errorIdAndResourceId = "CmdletNotFoundException";

            try
            {
                cmdlet = (Cmdlet)Activator.CreateInstance(cmdletInformation.ImplementingType);
            }
            catch (TargetInvocationException ex)
            {
                CommandProcessor.tracer.TraceException((Exception)ex);
                CmdletInvocationException invocationException = new CmdletInvocationException(ex.InnerException, (InvocationInfo)null);
                MshLog.LogCommandHealthEvent(this.context, (Exception)invocationException, Severity.Warning);
                throw invocationException;
            }
            catch (MemberAccessException ex)
            {
                exception = (Exception)ex;
            }
            catch (TypeLoadException ex)
            {
                exception = (Exception)ex;
            }
            catch (InvalidCastException ex)
            {
                exception            = (Exception)ex;
                errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType";
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                CommandProcessor.tracer.TraceException(ex);
                MshLog.LogCommandHealthEvent(this.context, ex, Severity.Warning);
                throw;
            }
            if (exception != null)
            {
                CommandProcessor.tracer.TraceException(exception);
                MshLog.LogCommandHealthEvent(this.context, exception, Severity.Warning);
                CommandNotFoundException notFoundException = new CommandNotFoundException(cmdletInformation.Name, exception, errorIdAndResourceId, new object[1]
                {
                    (object)exception.Message
                });
                CommandProcessor.tracer.TraceException((Exception)notFoundException);
                throw notFoundException;
            }
            this.Command = (InternalCommand)cmdlet;
            this.InitCommon();
        }
Ejemplo n.º 3
0
        private void Init(CmdletInfo cmdletInformation)
        {
            Cmdlet    cmdlet    = null;
            Exception exception = null;
            string    str       = null;
            string    cmdletDoesNotDeriveFromCmdletType = null;

            try
            {
                cmdlet = ConstructInstance(cmdletInformation.ImplementingType);
                if (cmdlet == null)
                {
                    exception = new InvalidCastException();
                    str       = "CmdletDoesNotDeriveFromCmdletType";
                    cmdletDoesNotDeriveFromCmdletType = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType;
                }
            }
            catch (MemberAccessException exception2)
            {
                exception = exception2;
            }
            catch (TypeLoadException exception3)
            {
                exception = exception3;
            }
            catch (Exception exception4)
            {
                CommandProcessorBase.CheckForSevereException(exception4);
                CmdletInvocationException exception5 = new CmdletInvocationException(exception4, null);
                MshLog.LogCommandHealthEvent(base._context, exception5, Severity.Warning);
                throw exception5;
            }
            if (exception != null)
            {
                MshLog.LogCommandHealthEvent(base._context, exception, Severity.Warning);
                CommandNotFoundException exception6 = new CommandNotFoundException(cmdletInformation.Name, exception, str ?? "CmdletNotFoundException", cmdletDoesNotDeriveFromCmdletType ?? DiscoveryExceptions.CmdletNotFoundException, new object[] { exception.Message });
                throw exception6;
            }
            base.Command      = cmdlet;
            base.CommandScope = base.Context.EngineSessionState.CurrentScope;
            this.InitCommon();
        }
Ejemplo n.º 4
0
 private void Init(CmdletInfo cmdletInformation)
 {
     Cmdlet cmdlet = null;
     Exception exception = null;
     string str = null;
     string cmdletDoesNotDeriveFromCmdletType = null;
     try
     {
         cmdlet = ConstructInstance(cmdletInformation.ImplementingType);
         if (cmdlet == null)
         {
             exception = new InvalidCastException();
             str = "CmdletDoesNotDeriveFromCmdletType";
             cmdletDoesNotDeriveFromCmdletType = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType;
         }
     }
     catch (MemberAccessException exception2)
     {
         exception = exception2;
     }
     catch (TypeLoadException exception3)
     {
         exception = exception3;
     }
     catch (Exception exception4)
     {
         CommandProcessorBase.CheckForSevereException(exception4);
         CmdletInvocationException exception5 = new CmdletInvocationException(exception4, null);
         MshLog.LogCommandHealthEvent(base._context, exception5, Severity.Warning);
         throw exception5;
     }
     if (exception != null)
     {
         MshLog.LogCommandHealthEvent(base._context, exception, Severity.Warning);
         CommandNotFoundException exception6 = new CommandNotFoundException(cmdletInformation.Name, exception, str ?? "CmdletNotFoundException", cmdletDoesNotDeriveFromCmdletType ?? DiscoveryExceptions.CmdletNotFoundException, new object[] { exception.Message });
         throw exception6;
     }
     base.Command = cmdlet;
     base.CommandScope = base.Context.EngineSessionState.CurrentScope;
     this.InitCommon();
 }
Ejemplo n.º 5
0
 internal static void ShouldRun(
     ExecutionContext context,
     PSHost host,
     CommandInfo commandInfo,
     CommandOrigin commandOrigin)
 {
     try
     {
         if (commandOrigin == CommandOrigin.Runspace && commandInfo.Visibility != SessionStateEntryVisibility.Public)
         {
             CommandNotFoundException notFoundException = new CommandNotFoundException(commandInfo.Name, (Exception)null, "CommandNotFoundException", new object[0]);
             CommandDiscovery.tracer.TraceException((Exception)notFoundException);
             throw notFoundException;
         }
         context.AuthorizationManager.ShouldRunInternal(commandInfo, commandOrigin, host);
     }
     catch (PSSecurityException ex)
     {
         CommandDiscovery.tracer.TraceException((Exception)ex);
         MshLog.LogCommandHealthEvent(context, (Exception)ex, Severity.Warning);
         MshLog.LogCommandLifecycleEvent(context, CommandState.Terminated, commandInfo.Name);
         throw;
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes the command's request object.
        /// </summary>
        /// <param name="cmdletInformation">
        /// The information about the cmdlet.
        /// </param>
        /// <exception cref="CmdletInvocationException">
        /// If the constructor for the cmdlet threw an exception.
        /// </exception>
        /// <exception cref="MemberAccessException">
        /// The type referenced by <paramref name="cmdletInformation"/> refered to an
        /// abstract type or them member was invoked via a late-binding mechanism.
        /// </exception>
        /// <exception cref="TypeLoadException">
        /// If <paramref name="cmdletInformation"/> refers to a type that is invalid.
        /// </exception>
        private void Init(CmdletInfo cmdletInformation)
        {
            Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null.");

            Cmdlet    newCmdlet            = null;
            Exception initError            = null;
            string    errorIdAndResourceId = null;
            string    resourceStr          = null;

            try
            {
                // Create the request object
                newCmdlet = ConstructInstance(cmdletInformation.ImplementingType);
                if (newCmdlet == null)
                {
                    // We could test the inheritance before constructing, but that's
                    // expensive.  Much cheaper to just check for null.
                    initError            = new InvalidCastException();
                    errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType";
                    resourceStr          = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType;
                }
            }
            catch (MemberAccessException memberAccessException)
            {
                initError = memberAccessException;
            }
            catch (TypeLoadException typeLoadException)
            {
                initError = typeLoadException;
            }
            catch (Exception e) // Catch-all OK, 3rd party callout.
            {
                // We don't have a Command or InvocationInfo at this point,
                // since the command failed to initialize.
                var commandException = new CmdletInvocationException(e, null);

                // Log a command health event
                MshLog.LogCommandHealthEvent(
                    this._context,
                    commandException,
                    Severity.Warning);

                throw commandException;
            }

            if (initError != null)
            {
                // Log a command health event
                MshLog.LogCommandHealthEvent(
                    this._context,
                    initError,
                    Severity.Warning);

                CommandNotFoundException exception =
                    new CommandNotFoundException(
                        cmdletInformation.Name,
                        initError,
                        errorIdAndResourceId ?? "CmdletNotFoundException",
                        resourceStr ?? DiscoveryExceptions.CmdletNotFoundException,
                        initError.Message);
                throw exception;
            }

            this.Command      = newCmdlet;
            this.CommandScope = Context.EngineSessionState.CurrentScope;

            InitCommon();
        }
Ejemplo n.º 7
0
        private static void ThrowCommandNotFoundException(Exception innerException)
        {
            CommandNotFoundException cmdE = new CommandNotFoundException(innerException.Message, innerException);

            throw cmdE;
        }
Ejemplo n.º 8
0
 private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, CommandInfo result, ref Exception lastError)
 {
     int length = commandName.IndexOfAny(new char[] { ':', '\\' });
     if ((length == -1) || (commandName[length] == ':'))
     {
         return null;
     }
     string str = commandName.Substring(0, length);
     string str2 = commandName.Substring(length + 1, (commandName.Length - length) - 1);
     if ((string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2)) || str.EndsWith(".", StringComparison.Ordinal))
     {
         return null;
     }
     try
     {
         discoveryTracer.WriteLine("Executing module-qualified search: {0}", new object[] { commandName });
         context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
         CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
         if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
         {
             List<PSModuleInfo> modules = context.Modules.GetModules(new string[] { str }, false);
             PSModuleInfo info2 = null;
             if ((modules == null) || (modules.Count == 0))
             {
                 CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) {
                     Visibility = cmdlet.Visibility
                 };
                 Command command = new Command(commandInfo);
                 Collection<PSModuleInfo> collection = null;
                 discoveryTracer.WriteLine("Attempting to load module: {0}", new object[] { str });
                 try
                 {
                     collection = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("PassThru").AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke<PSModuleInfo>();
                 }
                 catch (Exception exception)
                 {
                     discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message });
                     lastError = exception;
                     CommandProcessorBase.CheckForSevereException(exception);
                 }
                 if ((collection == null) || (collection.Count == 0))
                 {
                     string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportModule, str);
                     CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoLoadModule", resourceStr, new object[0]);
                     throw exception2;
                 }
                 info2 = collection[0];
             }
             else
             {
                 info2 = modules[0];
             }
             if (info2.ExportedCommands.ContainsKey(str2))
             {
                 result = info2.ExportedCommands[str2];
             }
         }
         return result;
     }
     catch (CommandNotFoundException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
     }
     finally
     {
         context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
     }
     return result;
 }
Ejemplo n.º 9
0
 private static CommandInfo TryModuleAutoDiscovery(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError)
 {
     CommandInfo info = null;
     try
     {
         CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module");
         if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
         {
             cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
             if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
             {
                 discoveryTracer.WriteLine("Executing non module-qualified search: {0}", new object[] { commandName });
                 context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
                 foreach (string str in ModuleUtils.GetDefaultAvailableModuleFiles(true, true, context))
                 {
                     string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(str);
                     Dictionary<string, List<CommandTypes>> dictionary = AnalysisCache.GetExportedCommands(str, false, context);
                     if (dictionary != null)
                     {
                         if (dictionary.ContainsKey(commandName))
                         {
                             CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) {
                                 Visibility = cmdlet.Visibility
                             };
                             Command command = new Command(commandInfo);
                             discoveryTracer.WriteLine("Found in module: {0}", new object[] { str });
                             PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("PassThru").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false);
                             Collection<PSModuleInfo> collection = null;
                             try
                             {
                                 collection = shell.Invoke<PSModuleInfo>();
                             }
                             catch (Exception exception)
                             {
                                 discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message });
                                 lastError = exception;
                                 CommandProcessorBase.CheckForSevereException(exception);
                             }
                             if ((collection == null) || (collection.Count == 0))
                             {
                                 string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, fileNameWithoutExtension);
                                 CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoloadMatchingModule", resourceStr, new object[0]);
                                 throw exception2;
                             }
                             info = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context);
                         }
                         if (info != null)
                         {
                             return info;
                         }
                     }
                 }
             }
             return info;
         }
         return info;
     }
     catch (CommandNotFoundException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
     }
     finally
     {
         context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
     }
     return info;
 }
Ejemplo n.º 10
0
 internal static void ShouldRun(ExecutionContext context, PSHost host, CommandInfo commandInfo, CommandOrigin commandOrigin)
 {
     try
     {
         if ((commandOrigin == CommandOrigin.Runspace) && (commandInfo.Visibility != SessionStateEntryVisibility.Public))
         {
             CommandNotFoundException exception = new CommandNotFoundException(commandInfo.Name, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
             throw exception;
         }
         context.AuthorizationManager.ShouldRunInternal(commandInfo, commandOrigin, host);
     }
     catch (PSSecurityException exception2)
     {
         MshLog.LogCommandHealthEvent(context, exception2, Severity.Warning);
         MshLog.LogCommandLifecycleEvent(context, CommandState.Terminated, commandInfo.Name);
         throw;
     }
 }
Ejemplo n.º 11
0
        internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo, CommandOrigin commandOrigin, bool? useLocalScope, SessionStateInternal sessionState)
        {
            CommandProcessorBase base2 = null;
            FunctionInfo info3;
            CommandNotFoundException exception6;
            HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            while (((commandInfo.CommandType == CommandTypes.Alias) && !set.Contains(commandInfo.Name)) && ((commandOrigin == CommandOrigin.Internal) || (commandInfo.Visibility == SessionStateEntryVisibility.Public)))
            {
                set.Add(commandInfo.Name);
                AliasInfo info = (AliasInfo) commandInfo;
                commandInfo = info.ResolvedCommand;
                if (commandInfo == null)
                {
                    commandInfo = LookupCommandInfo(info.Definition, commandOrigin, this._context);
                }
                if (commandInfo == null)
                {
                    CommandNotFoundException exception = new CommandNotFoundException(info.Name, null, "AliasNotResolvedException", DiscoveryExceptions.AliasNotResolvedException, new object[] { info.UnresolvedCommandName });
                    throw exception;
                }
                PSSQMAPI.IncrementData(CommandTypes.Alias);
            }
            ShouldRun(this._context, this._context.EngineHostInterface, commandInfo, commandOrigin);
            CommandTypes commandType = commandInfo.CommandType;
            if (commandType <= CommandTypes.ExternalScript)
            {
                switch (commandType)
                {
                    case CommandTypes.Function:
                    case CommandTypes.Filter:
                        goto Label_01E3;

                    case CommandTypes.Cmdlet:
                        base2 = new CommandProcessor((CmdletInfo) commandInfo, this._context);
                        goto Label_0260;

                    case CommandTypes.ExternalScript:
                    {
                        ExternalScriptInfo scriptInfo = (ExternalScriptInfo) commandInfo;
                        scriptInfo.SignatureChecked = true;
                        try
                        {
                            if (!this._context.IsSingleShell)
                            {
                                bool? nullable = useLocalScope;
                                base2 = this.CreateScriptProcessorForMiniShell(scriptInfo, nullable.HasValue ? nullable.GetValueOrDefault() : true, sessionState);
                            }
                            else
                            {
                                bool? nullable2 = useLocalScope;
                                base2 = this.CreateScriptProcessorForSingleShell(scriptInfo, this._context, nullable2.HasValue ? nullable2.GetValueOrDefault() : true, sessionState);
                            }
                            goto Label_0260;
                        }
                        catch (ScriptRequiresSyntaxException exception2)
                        {
                            CommandNotFoundException exception3 = new CommandNotFoundException(exception2.Message, exception2);
                            throw exception3;
                        }
                        catch (PSArgumentException exception4)
                        {
                            CommandNotFoundException exception5 = new CommandNotFoundException(commandInfo.Name, exception4, "ScriptRequiresInvalidFormat", DiscoveryExceptions.ScriptRequiresInvalidFormat, new object[0]);
                            throw exception5;
                        }
                        goto Label_01E3;
                    }
                }
                goto Label_023F;
            }
            if (commandType != CommandTypes.Application)
            {
                if (commandType == CommandTypes.Script)
                {
                    bool? nullable4 = useLocalScope;
                    base2 = CreateCommandProcessorForScript((ScriptInfo) commandInfo, this._context, nullable4.HasValue ? nullable4.GetValueOrDefault() : true, sessionState);
                    goto Label_0260;
                }
                if (commandType == CommandTypes.Workflow)
                {
                    goto Label_01E3;
                }
                goto Label_023F;
            }
            base2 = new NativeCommandProcessor((ApplicationInfo) commandInfo, this._context);
            goto Label_0260;
        Label_01E3:
            info3 = (FunctionInfo) commandInfo;
            bool? nullable3 = useLocalScope;
            base2 = CreateCommandProcessorForScript(info3, this._context, nullable3.HasValue ? nullable3.GetValueOrDefault() : true, sessionState);
            goto Label_0260;
        Label_023F:
            exception6 = new CommandNotFoundException(commandInfo.Name, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
            throw exception6;
        Label_0260:
            PSSQMAPI.IncrementData(commandInfo.CommandType);
            base2.Command.CommandOriginInternal = commandOrigin;
            base2.Command.MyInvocation.InvocationName = commandInfo.Name;
            return base2;
        }
Ejemplo n.º 12
0
        internal static CommandInfo LookupCommandInfo(string commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
        {
            if (string.IsNullOrEmpty(commandName))
            {
                return null;
            }
            CommandInfo result = null;
            string command = commandName;
            Exception lastError = null;
            CommandLookupEventArgs e = null;
            EventHandler<CommandLookupEventArgs> preCommandLookupAction = context.EngineIntrinsics.InvokeCommand.PreCommandLookupAction;
            if (preCommandLookupAction != null)
            {
                discoveryTracer.WriteLine("Executing PreCommandLookupAction: {0}", new object[] { commandName });
                try
                {
                    context.CommandDiscovery.RegisterLookupCommandInfoAction("ActivePreLookup", command);
                    e = new CommandLookupEventArgs(command, commandOrigin, context);
                    preCommandLookupAction(command, e);
                    discoveryTracer.WriteLine("PreCommandLookupAction returned: {0}", new object[] { e.Command });
                }
                catch (Exception exception2)
                {
                    CommandProcessorBase.CheckForSevereException(exception2);
                }
                finally
                {
                    context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActivePreLookup", commandName);
                }
            }
            if ((e == null) || !e.StopSearch)
            {
                discoveryTracer.WriteLine("Looking up command: {0}", new object[] { commandName });
                result = TryNormalSearch(commandName, context, commandOrigin, searchResolutionOptions, commandTypes, ref lastError);
                if (result == null)
                {
                    PSModuleAutoLoadingPreference preference = GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                    if (preference != PSModuleAutoLoadingPreference.None)
                    {
                        result = TryModuleAutoLoading(commandName, context, command, commandOrigin, result, ref lastError);
                    }
                    if (result == null)
                    {
                        if (preference == PSModuleAutoLoadingPreference.All)
                        {
                            result = TryModuleAutoDiscovery(commandName, context, command, commandOrigin, searchResolutionOptions, commandTypes, ref lastError);
                        }
                        if (result == null)
                        {
                            result = InvokeCommandNotFoundHandler(commandName, context, command, commandOrigin, result);
                        }
                    }
                }
            }
            else if (e.Command != null)
            {
                result = e.Command;
            }
            if (result != null)
            {
                EventHandler<CommandLookupEventArgs> postCommandLookupAction = context.EngineIntrinsics.InvokeCommand.PostCommandLookupAction;
                if (postCommandLookupAction != null)
                {
                    discoveryTracer.WriteLine("Executing PostCommandLookupAction: {0}", new object[] { command });
                    try
                    {
                        context.CommandDiscovery.RegisterLookupCommandInfoAction("ActivePostCommand", command);
                        e = new CommandLookupEventArgs(command, commandOrigin, context) {
                            Command = result
                        };
                        postCommandLookupAction(command, e);
                        if (e != null)
                        {
                            result = e.Command;
                            discoveryTracer.WriteLine("PreCommandLookupAction returned: {0}", new object[] { e.Command });
                        }
                    }
                    catch (Exception exception3)
                    {
                        CommandProcessorBase.CheckForSevereException(exception3);
                    }
                    finally
                    {
                        context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActivePostCommand", command);
                    }
                }
            }
            if (result == null)
            {
                discoveryTracer.TraceError("'{0}' is not recognized as a cmdlet, function, operable program or script file.", new object[] { commandName });
                CommandNotFoundException exception4 = new CommandNotFoundException(command, lastError, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);

				throw exception4;
            }
            return result;
        }
Ejemplo n.º 13
0
 private static void ThrowCommandNotFoundException(Exception innerException)
 {
     CommandNotFoundException exception = new CommandNotFoundException(innerException.Message, innerException);
     throw exception;
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes the command's request object
        /// </summary>
        /// 
        /// <param name="cmdletInformation">
        /// The information about the cmdlet.
        /// </param>
        /// 
        /// <exception cref="CmdletInvocationException">
        /// If the constructor for the cmdlet threw an exception.
        /// </exception>
        /// 
        /// <exception cref="MemberAccessException">
        /// The type referenced by <paramref name="cmdletInformation"/> refered to an
        /// abstract type or them member was invoked via a late-binding mechanism.
        /// </exception>
        /// 
        /// <exception cref="TypeLoadException">
        /// If <paramref name="cmdletInformation"/> refers to a type that is invalid.
        /// </exception>
        /// 
        private void Init(CmdletInfo cmdletInformation)
        {
            Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned  null.");

            Cmdlet newCmdlet = null;
            Exception initError = null;
            string errorIdAndResourceId = null;
            string resourceStr = null;
            try
            {
                // Create the request object
                newCmdlet = ConstructInstance(cmdletInformation.ImplementingType);
                if (newCmdlet == null)
                {
                    // We could test the inheritance before constructing, but that's
                    // expensive.  Much cheaper to just check for null.
                    initError = new InvalidCastException();
                    errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType";
                    resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType;
                }
            }
            catch (MemberAccessException memberAccessException)
            {
                initError = memberAccessException;
            }
            catch (TypeLoadException typeLoadException)
            {
                initError = typeLoadException;
            }
            catch (Exception e) // Catch-all OK, 3rd party callout.
            {
                CommandProcessorBase.CheckForSevereException(e);

                // We don't have a Command or InvocationInfo at this point,
                // since the command failed to initialize.
                var commandException = new CmdletInvocationException(e, null);

                // Log a command health event
                MshLog.LogCommandHealthEvent(
                    this._context,
                    commandException,
                    Severity.Warning);

                throw commandException;
            }
            if (null != initError)
            {
                // Log a command health event
                MshLog.LogCommandHealthEvent(
                    this._context,
                    initError,
                    Severity.Warning);

                CommandNotFoundException exception =
                    new CommandNotFoundException(
                        cmdletInformation.Name,
                        initError,
                        errorIdAndResourceId ?? "CmdletNotFoundException",
                        resourceStr ?? DiscoveryExceptions.CmdletNotFoundException,
                        initError.Message);
                throw exception;
            }

            this.Command = newCmdlet;
            this.CommandScope = Context.EngineSessionState.CurrentScope;

            InitCommon();
        }
Ejemplo n.º 15
0
        internal CommandInfo LookupCommandInfo(
            string commandName,
            CommandOrigin commandOrigin)
        {
            CommandInfo commandInfo    = (CommandInfo)null;
            string      commandName1   = commandName;
            Exception   innerException = (Exception)null;

            while (true)
            {
                CommandDiscovery.discoveryTracer.WriteLine("Looking up command: {0}", (object)commandName);
                if (!string.IsNullOrEmpty(commandName))
                {
                    CommandSearcher commandSearcher = new CommandSearcher(commandName, SearchResolutionOptions.AllowDuplicateCmdletNames, CommandTypes.All, this._context);
                    commandSearcher.CommandOrigin = commandOrigin;
                    try
                    {
                        if (!commandSearcher.MoveNext())
                        {
                            if (!commandName.Contains("-"))
                            {
                                CommandDiscovery.discoveryTracer.WriteLine("The command [{0}] was not found, trying again with get- prepended", (object)commandName);
                                commandName = "get" + (object)'-' + commandName;
                            }
                            else
                            {
                                goto label_13;
                            }
                        }
                        else
                        {
                            commandInfo = ((IEnumerator <CommandInfo>)commandSearcher).Current;
                            goto label_13;
                        }
                    }
                    catch (ArgumentException ex)
                    {
                        innerException = (Exception)ex;
                        goto label_13;
                    }
                    catch (PathTooLongException ex)
                    {
                        innerException = (Exception)ex;
                        goto label_13;
                    }
                    catch (FileLoadException ex)
                    {
                        innerException = (Exception)ex;
                        goto label_13;
                    }
                    catch (FormatException ex)
                    {
                        innerException = (Exception)ex;
                        goto label_13;
                    }
                    catch (MetadataException ex)
                    {
                        innerException = (Exception)ex;
                        goto label_13;
                    }
                }
                else
                {
                    break;
                }
            }
            CommandDiscovery.discoveryTracer.TraceError("Command name empty or null");
label_13:
            if (commandInfo == null)
            {
                CommandDiscovery.discoveryTracer.TraceError("'{0}' is not recognized as a cmdlet, function, operable program or script file.", (object)commandName);
                CommandNotFoundException notFoundException = new CommandNotFoundException(commandName1, innerException, "CommandNotFoundException", new object[0]);
                CommandDiscovery.tracer.TraceException((Exception)notFoundException);
                throw notFoundException;
            }
            return(commandInfo);
        }
Ejemplo n.º 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);
        }