Inheritance: System.Management.Automation.RuntimeException
Ejemplo n.º 1
0
 protected override void ProcessRecord()
 {
     if (this.Force == 0)
     {
         PSVariable atScope = null;
         if (string.IsNullOrEmpty(base.Scope))
         {
             atScope = base.SessionState.PSVariable.GetAtScope(this.name, "local");
         }
         else
         {
             atScope = base.SessionState.PSVariable.GetAtScope(this.name, base.Scope);
         }
         if (atScope != null)
         {
             SessionStateException replaceParentContainsErrorRecordException = new SessionStateException(this.name, SessionStateCategory.Variable, "VariableAlreadyExists", SessionStateStrings.VariableAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
             return;
         }
     }
     string newVariableAction = VariableCommandStrings.NewVariableAction;
     string target = StringUtil.Format(VariableCommandStrings.NewVariableTarget, this.Name, this.Value);
     if (base.ShouldProcess(target, newVariableAction))
     {
         PSVariable variable = new PSVariable(this.name, this._value, this.options);
         if (this._visibility.HasValue)
         {
             variable.Visibility = this._visibility.Value;
         }
         if (this.description != null)
         {
             variable.Description = this.description;
         }
         try
         {
             if (string.IsNullOrEmpty(base.Scope))
             {
                 base.SessionState.Internal.NewVariable(variable, (bool) this.Force);
             }
             else
             {
                 base.SessionState.Internal.NewVariableAtScope(variable, base.Scope, (bool) this.Force);
             }
         }
         catch (SessionStateException exception2)
         {
             base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
             return;
         }
         catch (PSArgumentException exception3)
         {
             base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
             return;
         }
         if (this.passThru)
         {
             base.WriteObject(variable);
         }
     }
 }
Ejemplo n.º 2
0
 public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck)
 {
     if (!IsVisible(origin, valueToCheck))
     {
         SessionStateException exception;
         System.Management.Automation.PSVariable variable = valueToCheck as System.Management.Automation.PSVariable;
         if (variable != null)
         {
             exception = new SessionStateException(variable.Name, SessionStateCategory.Variable, "VariableIsPrivate", SessionStateStrings.VariableIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
             throw exception;
         }
         CommandInfo info = valueToCheck as CommandInfo;
         if (info != null)
         {
             string itemName = null;
             if (info != null)
             {
                 itemName = info.Name;
             }
             if (itemName != null)
             {
                 exception = new SessionStateException(itemName, SessionStateCategory.Command, "NamedCommandIsPrivate", SessionStateStrings.NamedCommandIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
             }
             else
             {
                 exception = new SessionStateException("", SessionStateCategory.Command, "CommandIsPrivate", SessionStateStrings.CommandIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
             }
             throw exception;
         }
         exception = new SessionStateException(null, SessionStateCategory.Resource, "ResourceIsPrivate", SessionStateStrings.ResourceIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
         throw exception;
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Utility to check the visibility of an object based on the current
        /// command origin. If the object implements IHasSessionStateEntryVisibility
        /// then the check will be made. If the check fails, then an exception will be thrown...
        /// </summary>
        /// <param name="origin">The command origin value to check against...</param>
        /// <param name="valueToCheck">The object to check</param>
        public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck)
        {
            SessionStateException exception;

            if (!IsVisible(origin, valueToCheck))
            {
                PSVariable sv = valueToCheck as PSVariable;
                if (sv != null)
                {
                    exception =
                        new SessionStateException(
                            sv.Name,
                            SessionStateCategory.Variable,
                            "VariableIsPrivate",
                            SessionStateStrings.VariableIsPrivate,
                            ErrorCategory.PermissionDenied);

                    throw exception;
                }
                CommandInfo cinfo = valueToCheck as CommandInfo;
                if (cinfo != null)
                {
                    string commandName = cinfo.Name;
                    if (commandName != null)
                    {
                        // If we have a name, use it in the error message
                        exception =
                            new SessionStateException(
                                commandName,
                                SessionStateCategory.Command,
                                "NamedCommandIsPrivate",
                                SessionStateStrings.NamedCommandIsPrivate,
                                ErrorCategory.PermissionDenied);
                    }
                    else
                    {
                        exception =
                            new SessionStateException(
                                string.Empty,
                                SessionStateCategory.Command,
                                "CommandIsPrivate",
                                SessionStateStrings.CommandIsPrivate,
                                ErrorCategory.PermissionDenied);
                    }

                    throw exception;
                }

                // Catch all error for other types of resources...
                exception =
                    new SessionStateException(
                        null,
                        SessionStateCategory.Resource,
                        "ResourceIsPrivate",
                        SessionStateStrings.ResourceIsPrivate,
                        ErrorCategory.PermissionDenied);

                throw exception;
            }
        }
Ejemplo n.º 4
0
 internal void NewDrive(PSDriveInfo newDrive)
 {
     if (newDrive == null)
     {
         throw PSTraceSource.NewArgumentNullException("newDrive");
     }
     if (this.GetDrives().ContainsKey(newDrive.Name))
     {
         SessionStateException exception = new SessionStateException(newDrive.Name, SessionStateCategory.Drive, "DriveAlreadyExists", SessionStateStrings.DriveAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
         throw exception;
     }
     if (!newDrive.IsAutoMounted && (this.GetDrives().Count > (this.DriveCapacity.FastValue - 1)))
     {
         SessionStateOverflowException exception2 = new SessionStateOverflowException(newDrive.Name, SessionStateCategory.Drive, "DriveOverflow", SessionStateStrings.DriveOverflow, new object[] { this.DriveCapacity.FastValue });
         throw exception2;
     }
     if (!newDrive.IsAutoMounted)
     {
         this.GetDrives().Add(newDrive.Name, newDrive);
     }
     else if (!this.GetAutomountedDrives().ContainsKey(newDrive.Name))
     {
         this.GetAutomountedDrives().Add(newDrive.Name, newDrive);
     }
 }
Ejemplo n.º 5
0
        } // SetFunctionRaw

        internal WorkflowInfo SetWorkflowRaw(
            WorkflowInfo workflowInfo,
            CommandOrigin origin)
        {
            string originalName = workflowInfo.Name;
            string name         = originalName;

            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);

            // The script that defines a workflowInfo wrapper is fully trusted
            workflowInfo.ScriptBlock.LanguageMode = PSLanguageMode.FullLanguage;

            if (workflowInfo.Module == null && this.Module != null)
            {
                workflowInfo.Module = this.Module;
            }

            var wfInfo = (WorkflowInfo)
                         searcher.InitialScope.SetFunction(name, workflowInfo.ScriptBlock, null, options, false, origin, ExecutionContext, null,
                                                           (arg1, arg2, arg3, arg4, arg5, arg6) => workflowInfo);

            foreach (var aliasName in GetFunctionAliases(workflowInfo.ScriptBlock.Ast as IParameterMetadataProvider))
            {
                searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin);
            }

            return(wfInfo);
        } // SetWorkflowRaw
Ejemplo n.º 6
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="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>
        internal FunctionInfo SetFunctionRaw(
            string name,
            ScriptBlock function,
            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);

            var functionInfo = searcher.InitialScope.SetFunction(name, function, null, options, false, origin, ExecutionContext);

            foreach (var aliasName in GetFunctionAliases(function.Ast as IParameterMetadataProvider))
            {
                searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin);
            }

            return(functionInfo);
        }
Ejemplo n.º 7
0
        } // 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="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>
        ///
        /// <param name="context">
        /// The execution context for the function.
        /// </param>
        ///
        /// <param name="helpFile">
        /// The name of the help file associated with the function.
        /// </param>
        ///
        /// <param name="isPreValidated">
        /// Set to true if it is a regular function (meaning, we do not need to check this is a workflow or if the script contains JobDefinition Attribute and then process it)
        /// </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,
            ExecutionContext context,
            string helpFile,
            bool isPreValidated)
        {
            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;
            }

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


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

            return(searcher.InitialScope.SetFunction(name, function, originalFunction, options, force, origin, context, helpFile));
        } // SetFunction
Ejemplo n.º 8
0
 internal SessionStateException(
     string itemName,
     SessionStateCategory sessionStateCategory,
     string errorIdAndResourceId,
     ErrorCategory errorCategory,
     params object[] messageArgs)
     : base(SessionStateException.BuildMessage(itemName, errorIdAndResourceId, messageArgs))
 {
     this._itemName             = itemName;
     this._sessionStateCategory = sessionStateCategory;
     this._errorId       = errorIdAndResourceId;
     this._errorCategory = errorCategory;
 }
Ejemplo n.º 9
0
        private static void ThrowIfVariableIsPrivate(PSVariable variable)
        {
            if (variable.Visibility != SessionStateEntryVisibility.Private)
            {
                return;
            }

            var exception = new SessionStateException(
                String.Format("Cannot access the variable '${0}' because it is a private variable", variable.Name),
                variable.ItemName,
                SessionStateCategory.Variable);

            string errorId         = "VariableIsPrivate";
            var    parentException = new ParentContainsErrorRecordException(exception);
            var    error           = new ErrorRecord(parentException, errorId, ErrorCategory.PermissionDenied, variable.Name);

            exception.ErrorRecord = error;

            throw exception;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        /// 
        protected override void ProcessRecord()
        {
            Collection<AliasInfo> importedAliases = GetAliasesFromFile(this.ParameterSetName.Equals(LiteralPathParameterSetName,
                StringComparison.OrdinalIgnoreCase));

            CommandOrigin origin = MyInvocation.CommandOrigin;

            foreach (AliasInfo alias in importedAliases)
            {
                // If not force, then see if the alias already exists

                // NTRAID#Windows Out Of Band Releases-906910-2006/03/17-JonN
                string action = AliasCommandStrings.ImportAliasAction;

                string target = StringUtil.Format(AliasCommandStrings.ImportAliasTarget, alias.Name, alias.Definition);

                if (!ShouldProcess(target, action))
                    continue;

                if (!Force)
                {
                    AliasInfo existingAlias = null;
                    if (String.IsNullOrEmpty(Scope))
                    {
                        existingAlias = SessionState.Internal.GetAlias(alias.Name);
                    }
                    else
                    {
                        existingAlias = SessionState.Internal.GetAliasAtScope(alias.Name, Scope);
                    }

                    if (existingAlias != null)
                    {
                        // Write an error for aliases that aren't visible...
                        try
                        {
                            SessionState.ThrowIfNotVisible(origin, existingAlias);
                        }
                        catch (SessionStateException sessionStateException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    sessionStateException.ErrorRecord,
                                    sessionStateException));
                            // Only report the error once...
                            continue;
                        }

                        // Since the alias already exists, write an error.

                        SessionStateException aliasExists =
                            new SessionStateException(
                                alias.Name,
                                SessionStateCategory.Alias,
                                "AliasAlreadyExists",
                                SessionStateStrings.AliasAlreadyExists,
                                ErrorCategory.ResourceExists);

                        WriteError(
                            new ErrorRecord(
                                aliasExists.ErrorRecord,
                                aliasExists));
                        continue;
                    }

                    if (VerifyShadowingExistingCommandsAndWriteError(alias.Name))
                    {
                        continue;
                    }
                } // if (!Force)

                // Set the alias in the specified scope or the
                // current scope.

                AliasInfo result = null;

                try
                {
                    if (String.IsNullOrEmpty(Scope))
                    {
                        result = SessionState.Internal.SetAliasItem(alias, Force, MyInvocation.CommandOrigin);
                    }
                    else
                    {
                        result = SessionState.Internal.SetAliasItemAtScope(alias, Scope, Force, MyInvocation.CommandOrigin);
                    }
                }
                catch (SessionStateException sessionStateException)
                {
                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    continue;
                }
                catch (PSArgumentOutOfRangeException argOutOfRange)
                {
                    WriteError(
                        new ErrorRecord(
                            argOutOfRange.ErrorRecord,
                            argOutOfRange));
                    continue;
                }
                catch (PSArgumentException argException)
                {
                    WriteError(
                        new ErrorRecord(
                            argException.ErrorRecord,
                            argException));
                    continue;
                }

                // Write the alias to the pipeline if PassThru was specified

                if (PassThru && result != null)
                {
                    WriteObject(result);
                }
            }
        } // ProcessRecord
Ejemplo n.º 11
0
        /// <summary>
        /// Add objects received on the pipeline to an ArrayList of values, to
        /// take the place of the Value parameter if none was specified on the
        /// command line. 
        /// </summary>
        /// 
        protected override void ProcessRecord()
        {
            // If Force is not specified, see if the variable already exists
            // in the specified scope. If the scope isn't specified, then
            // check to see if it exists in the current scope.

            if (!Force)
            {
                PSVariable varFound = null;
                if (String.IsNullOrEmpty(Scope))
                {
                    varFound =
                        SessionState.PSVariable.GetAtScope(Name, "local");
                }
                else
                {
                    varFound =
                        SessionState.PSVariable.GetAtScope(Name, Scope);
                }

                if (varFound != null)
                {
                    SessionStateException sessionStateException =
                        new SessionStateException(
                            Name,
                            SessionStateCategory.Variable,
                            "VariableAlreadyExists",
                            SessionStateStrings.VariableAlreadyExists,
                            ErrorCategory.ResourceExists);

                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    return;
                }
            }

            // Since the variable doesn't exist or -Force was specified,
            // Call should process to validate the set with the user.

            string action = VariableCommandStrings.NewVariableAction;

            string target = StringUtil.Format(VariableCommandStrings.NewVariableTarget, Name, Value);

            if (ShouldProcess(target, action))
            {
                PSVariable newVariable = new PSVariable(Name, Value, Option);

                if (_visibility != null)
                {
                    newVariable.Visibility = (SessionStateEntryVisibility)_visibility;
                }

                if (Description != null)
                {
                    newVariable.Description = Description;
                }

                try
                {
                    if (String.IsNullOrEmpty(Scope))
                    {
                        SessionState.Internal.NewVariable(newVariable, Force);
                    }
                    else
                    {
                        SessionState.Internal.NewVariableAtScope(newVariable, Scope, Force);
                    }
                }
                catch (SessionStateException sessionStateException)
                {
                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    return;
                }
                catch (PSArgumentException argException)
                {
                    WriteError(
                        new ErrorRecord(
                            argException.ErrorRecord,
                            argException));
                    return;
                }

                if (_passThru)
                {
                    WriteObject(newVariable);
                }
            }
        } // ProcessRecord
Ejemplo n.º 12
0
        /// <summary>
        /// Utility to check the visibility of an object based on the current
        /// command origin. If the object implements IHasSessionStateEntryVisibility
        /// then the check will be made. If the check fails, then an exception will be thrown...
        /// </summary>
        /// <param name="origin">The command origin value to check against...</param>
        /// <param name="valueToCheck">The object to check</param>
        public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck)
        {
            SessionStateException exception;
            if (!IsVisible(origin, valueToCheck))
            {
                PSVariable sv = valueToCheck as PSVariable;
                if (sv != null)
                {
                    exception =
                       new SessionStateException(
                           sv.Name,
                           SessionStateCategory.Variable,
                           "VariableIsPrivate",
                           SessionStateStrings.VariableIsPrivate,
                           ErrorCategory.PermissionDenied);

                    throw exception;
                }
                CommandInfo cinfo = valueToCheck as CommandInfo;
                if (cinfo != null)
                {
                    string commandName = null;
                    if (cinfo != null)
                        commandName = cinfo.Name;
                    if (commandName != null)
                    {
                        // If we have a name, use it in the error message
                        exception =
                            new SessionStateException(
                                commandName,
                                SessionStateCategory.Command,
                                "NamedCommandIsPrivate",
                                SessionStateStrings.NamedCommandIsPrivate,
                                ErrorCategory.PermissionDenied);
                    }
                    else
                    {
                        exception =
                            new SessionStateException(
                                "",
                                SessionStateCategory.Command,
                                "CommandIsPrivate",
                                SessionStateStrings.CommandIsPrivate,
                                ErrorCategory.PermissionDenied);
                    }

                    throw exception;
                }

                // Catch all error for other types of resources...
                exception =
                    new SessionStateException(
                        null,
                        SessionStateCategory.Resource,
                        "ResourceIsPrivate",
                        SessionStateStrings.ResourceIsPrivate,
                        ErrorCategory.PermissionDenied);

                throw exception;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Removes the provider of the given name.
        /// </summary>
        /// 
        /// <param name="providerName">
        /// The name of the provider to remove.
        /// </param>
        /// 
        /// <param name="force">
        /// Determines if the provider should be removed forcefully even if there were
        /// drives present or errors.
        /// </param>
        ///
        /// <param name="context">
        /// The context under which the command is being run.
        /// </param>
        /// 
        /// <error cref="ArgumentNullException">
        /// If <paramref name="providerName"/> is null.
        /// </error>
        /// 
        /// <error cref="SessionStateException">
        /// There are still drives associated with this provider,
        /// and the "force" option was not specified.
        /// </error>
        /// 
        /// <error cref="ProviderNotFoundException">
        /// A provider with name <paramref name="providerName"/> could not be found.
        /// </error>
        /// 
        /// <error>
        /// If a provider throws an exception it gets written to the <paramref name="context"/>.
        /// </error>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="providerName"/> is null or empty.
        /// </exception>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="context"/> is null.
        /// </exception>
        /// 
        /// <remarks>
        /// All drives associated with the provider must be removed before the provider
        /// can be removed. Call SessionState.GetDrivesForProvider() to determine if there
        /// are any drives associated with the provider. A SessionStateException
        /// will be written to the context if any such drives do exist.
        /// </remarks>
        /// 
        internal void RemoveProvider(
            string providerName,
            bool force,
            CmdletProviderContext context)
        {
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException("context");
            }

            if (String.IsNullOrEmpty(providerName))
            {
                throw PSTraceSource.NewArgumentException("providerName");
            }

            bool errors = false;

            ProviderInfo provider = null;

            try
            {
                provider = GetSingleProvider(providerName);
            }
            catch (ProviderNotFoundException)
            {
                return;
            }

            try
            {
                // First get an instance of the provider to make sure it exists
                Provider.CmdletProvider providerBase = GetProviderInstance(provider);

                if (providerBase == null)
                {
                    ProviderNotFoundException e = new ProviderNotFoundException(
                        providerName,
                        SessionStateCategory.CmdletProvider,
                        "ProviderNotFound",
                        SessionStateStrings.ProviderNotFound);
                    context.WriteError(new ErrorRecord(e.ErrorRecord, e));

                    errors = true;
                }
                else
                {
                    // See if there are any drives present for the provider

                    int driveCount = 0;
                    foreach (PSDriveInfo drive in GetDrivesForProvider(providerName))
                    {
                        if (drive != null)
                        {
                            ++driveCount;
                            break;
                        }
                    }

                    if (driveCount > 0)
                    {
                        if (force)
                        {
                            // Forcefully remove all the drives

                            foreach (PSDriveInfo drive in GetDrivesForProvider(providerName))
                            {
                                if (drive != null)
                                {
                                    RemoveDrive(drive, true, null);
                                }
                            }
                        }
                        else
                        {
                            errors = true;

                            // Since there are still drives associated with the provider
                            // the provider cannot be removed

                            SessionStateException e = new SessionStateException(
                                providerName,
                                SessionStateCategory.CmdletProvider,
                                "RemoveDrivesBeforeRemovingProvider",
                                SessionStateStrings.RemoveDrivesBeforeRemovingProvider,
                                ErrorCategory.InvalidOperation);
                            context.WriteError(new ErrorRecord(e.ErrorRecord, e));

                            return;
                        }
                    }

                    // Now tell the provider that they are going to be removed by
                    // calling the Stop method

                    try
                    {
                        providerBase.Stop(context);
                    }
                    catch (LoopFlowException)
                    {
                        throw;
                    }
                    catch (PipelineStoppedException)
                    {
                        throw;
                    }
                    catch (ActionPreferenceStopException)
                    {
                        throw;
                    }
                }
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                errors = true;
                context.WriteError(
                    new ErrorRecord(
                        e,
                        "RemoveProviderUnexpectedException",
                        ErrorCategory.InvalidArgument,
                        providerName));
            }
            finally
            {
                if (force || !errors)
                {
                    // Log the provider stopped event

                    MshLog.LogProviderLifecycleEvent(
                        this.ExecutionContext,
                        providerName,
                        ProviderState.Stopped);

                    RemoveProviderFromCollection(provider);
                    ProvidersCurrentWorkingDrive.Remove(provider);

#if RELATIONSHIP_SUPPORTED
    // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release

                   // Now make sure no relationship reference this provider
                    relationships.ProcessRelationshipsOnCmdletProviderRemoval (providerName);
#endif
                }
            }
        } // RemoveProvider
Ejemplo n.º 14
0
        } // InitializeProvider



        /// <summary>
        /// Creates and adds a provider to the provider container 
        /// </summary>
        /// 
        /// <param name="provider">
        /// The provider to add.
        /// </param>
        /// 
        /// <returns>
        /// The provider that was added or null if the provider failed to be added.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="provider"/> is null.
        /// </exception>
        /// 
        /// <exception cref="SessionStateException">
        /// If the provider already exists.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If there was a failure to load the provider or the provider
        /// threw an exception.
        /// </exception>
        /// 
        internal ProviderInfo NewProvider(ProviderInfo provider)
        {
            if (provider == null)
            {
                throw PSTraceSource.NewArgumentNullException("provider");
            }

            // Check to see if the provider already exists.
            // We do the check instead of allowing the hashtable to 
            // throw the exception so that we give a better error
            // message.
            ProviderInfo existingProvider = ProviderExists(provider);
            if (existingProvider != null)
            {
                // If it's an already loaded provider, don't return an error...
                if (existingProvider.ImplementingType == provider.ImplementingType)
                    return existingProvider;

                SessionStateException sessionStateException =
                    new SessionStateException(
                        provider.Name,
                        SessionStateCategory.CmdletProvider,
                        "CmdletProviderAlreadyExists",
                        SessionStateStrings.CmdletProviderAlreadyExists,
                        ErrorCategory.ResourceExists);

                throw sessionStateException;
            }


            // Make sure we are able to create an instance of the provider.
            // Note, this will also set the friendly name if the user didn't
            // specify one.

            Provider.CmdletProvider providerInstance = provider.CreateInstance();

            // Now call start to let the provider initialize itself
            CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
            ProviderInfo newProviderInfo = null;

            try
            {
                newProviderInfo = providerInstance.Start(provider, context);

                // Set the new provider info in the instance in case the provider
                // derived a new one

                providerInstance.SetProviderInformation(newProviderInfo);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            catch (Exception e) // Catch-call OK, 3rd party callout
            {
                CommandProcessorBase.CheckForSevereException(e);
                throw
                    NewProviderInvocationException(
                        "ProviderStartException",
                        SessionStateStrings.ProviderStartException,
                        provider,
                        null,
                        e);
            }

            context.ThrowFirstErrorOrDoNothing(true);

            if (newProviderInfo == null)
            {
                throw
                    PSTraceSource.NewInvalidOperationException(
                        SessionStateStrings.InvalidProviderInfoNull);
            }

            if (newProviderInfo != provider)
            {
                // Since the references are not the same, ensure that the provider
                // name is the same.

                if (!string.Equals(newProviderInfo.Name, provider.Name, StringComparison.OrdinalIgnoreCase))
                {
                    throw
                        PSTraceSource.NewInvalidOperationException(
                            SessionStateStrings.InvalidProviderInfo);
                }

                // Use the new provider info instead
                provider = newProviderInfo;
            }

            // Add the newly create provider to the providers container

            try
            {
                NewProviderEntry(provider);
            }
            catch (ArgumentException)
            {
                SessionStateException sessionStateException =
                    new SessionStateException(
                        provider.Name,
                        SessionStateCategory.CmdletProvider,
                        "CmdletProviderAlreadyExists",
                        SessionStateStrings.CmdletProviderAlreadyExists,
                        ErrorCategory.ResourceExists);

                throw sessionStateException;
            }

            // Add the provider to the provider current working 
            // drive hashtable so that we can associate a current working
            // drive with it.

            ProvidersCurrentWorkingDrive.Add(provider, null);

            bool initializeProviderError = false;
            try
            {
                // Initialize the provider and give it a chance to 
                // mount some drives.

                InitializeProvider(providerInstance, provider, context);
                context.ThrowFirstErrorOrDoNothing(true);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                initializeProviderError = true;
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                initializeProviderError = true;
                throw;
            }
            catch (NotSupportedException)
            {
                // We can safely ignore NotSupportedExceptions because
                // it just means that the provider doesn't support
                // drives.

                initializeProviderError = false;
            }
            catch (SessionStateException)
            {
                initializeProviderError = true;
                throw;
            }
            finally
            {
                if (initializeProviderError)
                {
                    // An exception during initialization should remove the provider from 
                    // session state.

                    Providers.Remove(provider.Name.ToString());
                    ProvidersCurrentWorkingDrive.Remove(provider);
                    provider = null;
                }
            }

#if RELATIONSHIP_SUPPORTED
    // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release

            // Make sure the delay-load relationships get updated for the new provider

            relationships.ProcessDelayLoadRelationships (provider.Name);
#endif

            // Now write out the result

            return provider;
        } // NewProvider
Ejemplo n.º 15
0
        } // 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;
        }
Ejemplo n.º 16
0
 internal void NewDrive(PSDriveInfo newDrive)
 {
     if (newDrive == null)
     {
         throw PSTraceSource.NewArgumentNullException("newDrive");
     }
     if (this.GetDrives().ContainsKey(newDrive.Name))
     {
         SessionStateException exception = new SessionStateException(newDrive.Name, SessionStateCategory.Drive, "DriveAlreadyExists", SessionStateStrings.DriveAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
         throw exception;
     }
     if (!newDrive.IsAutoMounted && (this.GetDrives().Count > (this.DriveCapacity.FastValue - 1)))
     {
         SessionStateOverflowException exception2 = new SessionStateOverflowException(newDrive.Name, SessionStateCategory.Drive, "DriveOverflow", SessionStateStrings.DriveOverflow, new object[] { this.DriveCapacity.FastValue });
         throw exception2;
     }
     if (!newDrive.IsAutoMounted)
     {
         this.GetDrives().Add(newDrive.Name, newDrive);
     }
     else if (!this.GetAutomountedDrives().ContainsKey(newDrive.Name))
     {
         this.GetAutomountedDrives().Add(newDrive.Name, newDrive);
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        /// 
        protected override void ProcessRecord()
        {
            // If not force, then see if the alias already exists

            if (!Force)
            {
                AliasInfo existingAlias = null;
                if (String.IsNullOrEmpty(Scope))
                {
                    existingAlias = SessionState.Internal.GetAlias(Name);
                }
                else
                {
                    existingAlias = SessionState.Internal.GetAliasAtScope(Name, Scope);
                }


                if (existingAlias != null)
                {
                    // Throw if alias exists and is private...
                    SessionState.ThrowIfNotVisible(this.CommandOrigin, existingAlias);

                    // Since the alias already exists, write an error.

                    SessionStateException aliasExists =
                        new SessionStateException(
                            Name,
                            SessionStateCategory.Alias,
                            "AliasAlreadyExists",
                            SessionStateStrings.AliasAlreadyExists,
                            ErrorCategory.ResourceExists);

                    WriteError(
                        new ErrorRecord(
                            aliasExists.ErrorRecord,
                            aliasExists));
                    return;
                }
            }

            // Create the alias info

            AliasInfo newAlias =
                new AliasInfo(
                    Name,
                    Value,
                    Context,
                    Option);

            newAlias.Description = Description;

            string action =
                AliasCommandStrings.NewAliasAction;

            string target =
                    StringUtil.Format(AliasCommandStrings.NewAliasTarget, Name, Value);

            if (ShouldProcess(target, action))
            {
                // Set the alias in the specified scope or the
                // current scope.

                AliasInfo result = null;

                try
                {
                    if (String.IsNullOrEmpty(Scope))
                    {
                        result = SessionState.Internal.SetAliasItem(newAlias, Force, MyInvocation.CommandOrigin);
                    }
                    else
                    {
                        result = SessionState.Internal.SetAliasItemAtScope(newAlias, Scope, Force, MyInvocation.CommandOrigin);
                    }
                }
                catch (SessionStateException sessionStateException)
                {
                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    return;
                }
                catch (PSArgumentOutOfRangeException argOutOfRange)
                {
                    WriteError(
                        new ErrorRecord(
                            argOutOfRange.ErrorRecord,
                            argOutOfRange));
                    return;
                }
                catch (PSArgumentException argException)
                {
                    WriteError(
                        new ErrorRecord(
                            argException.ErrorRecord,
                            argException));
                    return;
                }

                // Write the alias to the pipeline if PassThru was specified

                if (PassThru && result != null)
                {
                    WriteObject(result);
                }
            }
        } // ProcessRecord
Ejemplo n.º 18
0
 protected override void ProcessRecord()
 {
     Collection<AliasInfo> aliasesFromFile = this.GetAliasesFromFile(base.ParameterSetName.Equals("ByLiteralPath", StringComparison.OrdinalIgnoreCase));
     CommandOrigin commandOrigin = base.MyInvocation.CommandOrigin;
     foreach (AliasInfo info in aliasesFromFile)
     {
         string importAliasAction = AliasCommandStrings.ImportAliasAction;
         string target = StringUtil.Format(AliasCommandStrings.ImportAliasTarget, info.Name, info.Definition);
         if (base.ShouldProcess(target, importAliasAction))
         {
             if (this.Force == 0)
             {
                 AliasInfo valueToCheck = null;
                 if (string.IsNullOrEmpty(this.Scope))
                 {
                     valueToCheck = base.SessionState.Internal.GetAlias(info.Name);
                 }
                 else
                 {
                     valueToCheck = base.SessionState.Internal.GetAliasAtScope(info.Name, this.Scope);
                 }
                 if (valueToCheck != null)
                 {
                     try
                     {
                         SessionState.ThrowIfNotVisible(commandOrigin, valueToCheck);
                     }
                     catch (SessionStateException exception)
                     {
                         base.WriteError(new ErrorRecord(exception.ErrorRecord, exception));
                         continue;
                     }
                     SessionStateException replaceParentContainsErrorRecordException = new SessionStateException(info.Name, SessionStateCategory.Alias, "AliasAlreadyExists", SessionStateStrings.AliasAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
                     base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
                     continue;
                 }
                 if (this.VerifyShadowingExistingCommandsAndWriteError(info.Name))
                 {
                     continue;
                 }
             }
             AliasInfo sendToPipeline = null;
             try
             {
                 if (string.IsNullOrEmpty(this.Scope))
                 {
                     sendToPipeline = base.SessionState.Internal.SetAliasItem(info, (bool) this.Force, base.MyInvocation.CommandOrigin);
                 }
                 else
                 {
                     sendToPipeline = base.SessionState.Internal.SetAliasItemAtScope(info, this.Scope, (bool) this.Force, base.MyInvocation.CommandOrigin);
                 }
             }
             catch (SessionStateException exception3)
             {
                 base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
                 continue;
             }
             catch (PSArgumentOutOfRangeException exception4)
             {
                 base.WriteError(new ErrorRecord(exception4.ErrorRecord, exception4));
                 continue;
             }
             catch (PSArgumentException exception5)
             {
                 base.WriteError(new ErrorRecord(exception5.ErrorRecord, exception5));
                 continue;
             }
             if ((this.PassThru != 0) && (sendToPipeline != null))
             {
                 base.WriteObject(sendToPipeline);
             }
         }
     }
 }
Ejemplo n.º 19
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="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 SetFunctionRaw(
            string name,
            ScriptBlock function,
            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);

            var functionInfo = searcher.InitialScope.SetFunction(name, function, null, options, false, origin, ExecutionContext);

            foreach (var aliasName in GetFunctionAliases(function.Ast as IParameterMetadataProvider))
            {
                searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin);
            }

            return functionInfo;
        } // SetFunctionRaw
Ejemplo n.º 20
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);
 }
Ejemplo n.º 21
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);
 }
Ejemplo n.º 22
0
 internal void RemoveProvider(string providerName, bool force, CmdletProviderContext context)
 {
     if (context == null)
     {
         throw PSTraceSource.NewArgumentNullException("context");
     }
     if (string.IsNullOrEmpty(providerName))
     {
         throw PSTraceSource.NewArgumentException("providerName");
     }
     bool flag = false;
     ProviderInfo singleProvider = null;
     try
     {
         singleProvider = this.GetSingleProvider(providerName);
     }
     catch (ProviderNotFoundException)
     {
         return;
     }
     try
     {
         CmdletProvider providerInstance = this.GetProviderInstance(singleProvider);
         if (providerInstance == null)
         {
             ProviderNotFoundException replaceParentContainsErrorRecordException = new ProviderNotFoundException(providerName, SessionStateCategory.CmdletProvider, "ProviderNotFound", SessionStateStrings.ProviderNotFound, new object[0]);
             context.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
             flag = true;
         }
         else
         {
             int num = 0;
             foreach (PSDriveInfo info2 in this.GetDrivesForProvider(providerName))
             {
                 if (info2 != null)
                 {
                     num++;
                     break;
                 }
             }
             if (num > 0)
             {
                 if (force)
                 {
                     foreach (PSDriveInfo info3 in this.GetDrivesForProvider(providerName))
                     {
                         if (info3 != null)
                         {
                             this.RemoveDrive(info3, true, null);
                         }
                     }
                 }
                 else
                 {
                     flag = true;
                     SessionStateException exception2 = new SessionStateException(providerName, SessionStateCategory.CmdletProvider, "RemoveDrivesBeforeRemovingProvider", SessionStateStrings.RemoveDrivesBeforeRemovingProvider, ErrorCategory.InvalidOperation, new object[0]);
                     context.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
                     return;
                 }
             }
             try
             {
                 providerInstance.Stop(context);
             }
             catch (LoopFlowException)
             {
                 throw;
             }
             catch (PipelineStoppedException)
             {
                 throw;
             }
             catch (ActionPreferenceStopException)
             {
                 throw;
             }
         }
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
         flag = true;
         context.WriteError(new ErrorRecord(exception3, "RemoveProviderUnexpectedException", ErrorCategory.InvalidArgument, providerName));
     }
     finally
     {
         if (force || !flag)
         {
             MshLog.LogProviderLifecycleEvent(this.ExecutionContext, providerName, ProviderState.Stopped);
             this.RemoveProviderFromCollection(singleProvider);
             this.ProvidersCurrentWorkingDrive.Remove(singleProvider);
         }
     }
 }
Ejemplo n.º 23
0
 internal ProviderInfo NewProvider(ProviderInfo provider)
 {
     if (provider == null)
     {
         throw PSTraceSource.NewArgumentNullException("provider");
     }
     ProviderInfo info = this.ProviderExists(provider);
     if (info != null)
     {
         if (info.ImplementingType == provider.ImplementingType)
         {
             return info;
         }
         SessionStateException exception = new SessionStateException(provider.Name, SessionStateCategory.CmdletProvider, "CmdletProviderAlreadyExists", SessionStateStrings.CmdletProviderAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
         throw exception;
     }
     CmdletProvider providerInstance = provider.CreateInstance();
     CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(this.ExecutionContext);
     ProviderInfo providerInfoToSet = null;
     try
     {
         providerInfoToSet = providerInstance.Start(provider, cmdletProviderContext);
         providerInstance.SetProviderInformation(providerInfoToSet);
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         throw;
     }
     catch (InvalidOperationException)
     {
         throw;
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
         throw this.NewProviderInvocationException("ProviderStartException", SessionStateStrings.ProviderStartException, provider, null, exception2);
     }
     cmdletProviderContext.ThrowFirstErrorOrDoNothing(true);
     if (providerInfoToSet == null)
     {
         throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "InvalidProviderInfoNull", new object[0]);
     }
     if (providerInfoToSet != provider)
     {
         if (!string.Equals(providerInfoToSet.Name, provider.Name, StringComparison.OrdinalIgnoreCase))
         {
             throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "InvalidProviderInfo", new object[0]);
         }
         provider = providerInfoToSet;
     }
     try
     {
         this.NewProviderEntry(provider);
     }
     catch (ArgumentException)
     {
         SessionStateException exception3 = new SessionStateException(provider.Name, SessionStateCategory.CmdletProvider, "CmdletProviderAlreadyExists", SessionStateStrings.CmdletProviderAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
         throw exception3;
     }
     this.ProvidersCurrentWorkingDrive.Add(provider, null);
     bool flag = false;
     try
     {
         this.InitializeProvider(providerInstance, provider, cmdletProviderContext);
         cmdletProviderContext.ThrowFirstErrorOrDoNothing(true);
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         flag = true;
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         flag = true;
         throw;
     }
     catch (NotSupportedException)
     {
         flag = false;
     }
     catch (SessionStateException)
     {
         flag = true;
         throw;
     }
     finally
     {
         if (flag)
         {
             this.Providers.Remove(provider.Name.ToString());
             this.ProvidersCurrentWorkingDrive.Remove(provider);
             provider = null;
         }
     }
     return provider;
 }
Ejemplo n.º 24
0
        private bool VerifyShadowingExistingCommandsAndWriteError(string aliasName)
        {
            CommandSearcher searcher = new CommandSearcher(aliasName, SearchResolutionOptions.None, CommandTypes.All ^ CommandTypes.Alias, this.Context);
            foreach (string expandedCommandName in searcher.ConstructSearchPatternsFromName(aliasName))
            {
                CommandTypes commandTypeOfExistingCommand;
                if (this.ExistingCommands.TryGetValue(expandedCommandName, out commandTypeOfExistingCommand))
                {
                    // Since the alias already exists, write an error.
                    SessionStateException aliasExists =
                        new SessionStateException(
                            aliasName,
                            SessionStateCategory.Alias,
                            "AliasAlreadyExists",
                            SessionStateStrings.AliasWithCommandNameAlreadyExists,
                            ErrorCategory.ResourceExists,
                            commandTypeOfExistingCommand);

                    WriteError(
                        new ErrorRecord(
                            aliasExists.ErrorRecord,
                            aliasExists));
                    return true;
                }
            }

            return false;
        }
Ejemplo n.º 25
0
 public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck)
 {
     if (!IsVisible(origin, valueToCheck))
     {
         SessionStateException exception;
         System.Management.Automation.PSVariable variable = valueToCheck as System.Management.Automation.PSVariable;
         if (variable != null)
         {
             exception = new SessionStateException(variable.Name, SessionStateCategory.Variable, "VariableIsPrivate", SessionStateStrings.VariableIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
             throw exception;
         }
         CommandInfo info = valueToCheck as CommandInfo;
         if (info != null)
         {
             string itemName = null;
             if (info != null)
             {
                 itemName = info.Name;
             }
             if (itemName != null)
             {
                 exception = new SessionStateException(itemName, SessionStateCategory.Command, "NamedCommandIsPrivate", SessionStateStrings.NamedCommandIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
             }
             else
             {
                 exception = new SessionStateException("", SessionStateCategory.Command, "CommandIsPrivate", SessionStateStrings.CommandIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
             }
             throw exception;
         }
         exception = new SessionStateException(null, SessionStateCategory.Resource, "ResourceIsPrivate", SessionStateStrings.ResourceIsPrivate, ErrorCategory.PermissionDenied, new object[0]);
         throw exception;
     }
 }
Ejemplo n.º 26
0
        protected internal void WriteError(SessionStateException ex)
        {
            string errorId = String.Format("{0},{1}", ex.ErrorRecord.ErrorId, GetType().FullName);
            var error = new ErrorRecord(ex, errorId, ex.ErrorRecord.CategoryInfo.Category, ex.ItemName);
            error.CategoryInfo.Activity = GetActivityName();

            WriteError(error);
        }
Ejemplo n.º 27
0
 internal FunctionInfo SetFunctionRaw(string name, ScriptBlock function, 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);
     return searcher.InitialScope.SetFunction(name, function, null, none, false, origin, this.ExecutionContext);
 }
Ejemplo n.º 28
0
        } // SetFunctionRaw

        internal WorkflowInfo SetWorkflowRaw(
            WorkflowInfo workflowInfo,
            CommandOrigin origin)
        {
            string originalName = workflowInfo.Name;
            string name = originalName;

            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);

            // The script that defines a workflowInfo wrapper is fully trusted
            workflowInfo.ScriptBlock.LanguageMode = PSLanguageMode.FullLanguage;

            if (workflowInfo.Module == null && this.Module != null)
            {
                workflowInfo.Module = this.Module;
            }

            var wfInfo = (WorkflowInfo)
                searcher.InitialScope.SetFunction(name, workflowInfo.ScriptBlock, null, options, false, origin, ExecutionContext, null,
                                                     (arg1, arg2, arg3, arg4, arg5, arg6) => workflowInfo);
            foreach (var aliasName in GetFunctionAliases(workflowInfo.ScriptBlock.Ast as IParameterMetadataProvider))
            {
                searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin);
            }

            return wfInfo;
        } // SetWorkflowRaw
Ejemplo n.º 29
0
 internal WorkflowInfo SetWorkflowRaw(WorkflowInfo workflowInfo, CommandOrigin origin)
 {
     string name = workflowInfo.Name;
     string unqualifiedPath = name;
     FunctionLookupPath lookupPath = new FunctionLookupPath(unqualifiedPath);
     unqualifiedPath = lookupPath.UnqualifiedPath;
     if (string.IsNullOrEmpty(unqualifiedPath))
     {
         SessionStateException exception = new SessionStateException(name, 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);
     workflowInfo.ScriptBlock.LanguageMode = 0;
     return (WorkflowInfo) searcher.InitialScope.SetFunction(unqualifiedPath, workflowInfo.ScriptBlock, null, none, false, origin, this.ExecutionContext, null, (arg1, arg2, arg3, arg4, arg5, arg6) => workflowInfo);
 }
Ejemplo n.º 30
0
 protected override void ProcessRecord()
 {
     if (base.Force == 0)
     {
         AliasInfo valueToCheck = null;
         if (string.IsNullOrEmpty(base.Scope))
         {
             valueToCheck = base.SessionState.Internal.GetAlias(base.Name);
         }
         else
         {
             valueToCheck = base.SessionState.Internal.GetAliasAtScope(base.Name, base.Scope);
         }
         if (valueToCheck != null)
         {
             SessionState.ThrowIfNotVisible(base.CommandOrigin, valueToCheck);
             SessionStateException replaceParentContainsErrorRecordException = new SessionStateException(base.Name, SessionStateCategory.Alias, "AliasAlreadyExists", SessionStateStrings.AliasAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
             return;
         }
     }
     AliasInfo alias = new AliasInfo(base.Name, base.Value, base.Context, base.Option) {
         Description = base.Description
     };
     string newAliasAction = AliasCommandStrings.NewAliasAction;
     string target = StringUtil.Format(AliasCommandStrings.NewAliasTarget, base.Name, base.Value);
     if (base.ShouldProcess(target, newAliasAction))
     {
         AliasInfo sendToPipeline = null;
         try
         {
             if (string.IsNullOrEmpty(base.Scope))
             {
                 sendToPipeline = base.SessionState.Internal.SetAliasItem(alias, (bool) base.Force, base.MyInvocation.CommandOrigin);
             }
             else
             {
                 sendToPipeline = base.SessionState.Internal.SetAliasItemAtScope(alias, base.Scope, (bool) base.Force, base.MyInvocation.CommandOrigin);
             }
         }
         catch (SessionStateException exception2)
         {
             base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
             return;
         }
         catch (PSArgumentOutOfRangeException exception3)
         {
             base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
             return;
         }
         catch (PSArgumentException exception4)
         {
             base.WriteError(new ErrorRecord(exception4.ErrorRecord, exception4));
             return;
         }
         if ((base.PassThru != 0) && (sendToPipeline != null))
         {
             base.WriteObject(sendToPipeline);
         }
     }
 }
Ejemplo n.º 31
0
 private bool VerifyShadowingExistingCommandsAndWriteError(string aliasName)
 {
     CommandSearcher searcher = new CommandSearcher(aliasName, SearchResolutionOptions.None, CommandTypes.Workflow | CommandTypes.Script | CommandTypes.Application | CommandTypes.ExternalScript | CommandTypes.Cmdlet | CommandTypes.Filter | CommandTypes.Function, base.Context);
     foreach (string str in searcher.ConstructSearchPatternsFromName(aliasName))
     {
         CommandTypes types;
         if (this.ExistingCommands.TryGetValue(str, out types))
         {
             SessionStateException replaceParentContainsErrorRecordException = new SessionStateException(aliasName, SessionStateCategory.Alias, "AliasAlreadyExists", SessionStateStrings.AliasWithCommandNameAlreadyExists, ErrorCategory.ResourceExists, new object[] { types });
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 32
0
        private void WriteVariableAlreadyExistsError(PSVariable variable)
        {
            var ex = new SessionStateException(
                String.Format("A variable with name '{0}' already exists.", variable.Name),
                variable.Name,
                SessionStateCategory.Variable);

            string errorId = String.Format("VariableAlreadyExists,{0}", typeof(NewVariableCommand).FullName);
            var error = new ErrorRecord(ex, errorId, ErrorCategory.ResourceExists, variable.Name);
            error.CategoryInfo.Activity = "New-Variable";

            WriteError(error);
        }
Ejemplo n.º 33
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("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);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Adds a new drive to the scope's drive collection.
        /// </summary>
        /// 
        /// <param name="newDrive">
        /// The new drive to be added.
        /// </param>
        /// 
        /// <remarks>
        /// This method assumes the drive has already been verified and
        /// the provider has already been notified.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="newDrive" /> is null.
        /// </exception>
        /// 
        /// <exception cref="SessionStateException">
        /// If a drive of the same name already exists in this scope.
        /// </exception>
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum drive count has been reached for this scope.
        /// </exception>
        /// 
        internal void NewDrive(PSDriveInfo newDrive)
        {
            if (newDrive == null)
            {
                throw PSTraceSource.NewArgumentNullException("newDrive");
            }

            // Ensure that multiple threads do not try to modify the
            // drive data at the same time.

            var driveInfos = GetDrives();
            if (driveInfos.ContainsKey(newDrive.Name))
            {
                SessionStateException e =
                    new SessionStateException(
                        newDrive.Name,
                        SessionStateCategory.Drive,
                        "DriveAlreadyExists",
                        SessionStateStrings.DriveAlreadyExists,
                        ErrorCategory.ResourceExists);

                throw e;
            }

            if (!newDrive.IsAutoMounted &&
                driveInfos.Count > DriveCapacity.FastValue - 1)
            {
                SessionStateOverflowException e =
                    new SessionStateOverflowException(
                        newDrive.Name,
                        SessionStateCategory.Drive,
                        "DriveOverflow",
                        SessionStateStrings.DriveOverflow,
                        DriveCapacity.FastValue);

                throw e;
            }

            if (!newDrive.IsAutoMounted)
            {
                driveInfos.Add(newDrive.Name, newDrive);
            }
            else
            {
                var automountedDrives = GetAutomountedDrives();
                if (!automountedDrives.ContainsKey(newDrive.Name))
                {
                    automountedDrives.Add(newDrive.Name, newDrive);
                }
            }
        } // New Drive