Exemplo n.º 1
1
        } // RemoveDrive

        /// <summary>
        /// Removes the drive with the specified name.
        /// </summary>
        /// 
        /// <param name="driveName">
        /// The name of the drive to remove.
        /// </param>
        /// 
        /// <param name="force">
        /// Determines whether drive should be forcefully removed even if there was errors.
        /// </param>
        ///
        /// <param name="scopeID">
        /// The ID of the scope from which to remove the drive.
        /// If the scope ID is null or empty, the scope hierarchy will be searched
        /// starting at the current scope through all the parent scopes to the
        /// global scope until a drive of the given name is found to remove.
        /// </param>
        /// 
        /// <param name="context">
        /// The context of the command.
        /// </param>
        /// 
        internal void RemoveDrive(
            string driveName,
            bool force,
            string scopeID,
            CmdletProviderContext context)
        {
            if (driveName == null)
            {
                throw PSTraceSource.NewArgumentNullException("driveName");
            }

            Dbg.Diagnostics.Assert(
                context != null,
                "The caller should verify the context");

            PSDriveInfo drive = GetDrive(driveName, scopeID);

            if (drive == null)
            {
                DriveNotFoundException e = new DriveNotFoundException(
                    driveName,
                    "DriveNotFound",
                    SessionStateStrings.DriveNotFound);
                context.WriteError(new ErrorRecord(e.ErrorRecord, e));
            }
            else
            {
                RemoveDrive(drive, force, scopeID, context);
            }
        } // RemoveDrive
Exemplo n.º 2
0
 internal void WriteErrorsToContext(CmdletProviderContext errorContext)
 {
     if (errorContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("errorContext");
     }
     if (this.HasErrors())
     {
         foreach (ErrorRecord record in this.GetAccumulatedErrorObjects())
         {
             errorContext.WriteError(record);
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Writes all the accumulated errors to the specified context using WriteError.
        /// </summary>
        /// <param name="errorContext">
        /// The context to write the errors to.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="errorContext"/> is null.
        /// </exception>
        internal void WriteErrorsToContext(CmdletProviderContext errorContext)
        {
            if (errorContext is null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(errorContext));
            }

            if (HasErrors())
            {
                foreach (ErrorRecord errorRecord in GetAccumulatedErrorObjects())
                {
                    errorContext.WriteError(errorRecord);
                }
            }
        }
Exemplo n.º 4
0
        private PSDriveInfo ValidateDriveWithProvider(
            DriveCmdletProvider driveProvider,
            PSDriveInfo drive,
            CmdletProviderContext context,
            bool resolvePathIfPossible)
        {
            Dbg.Diagnostics.Assert(
                drive != null,
                "drive should have been validated by the caller");

            Dbg.Diagnostics.Assert(
                driveProvider != null,
                "driveProvider should have been validated by the caller");

            // Mark the drive as being created so that the provider can modify the
            // root if necessary

            drive.DriveBeingCreated = true;

            // Only try to resolve the root as an MSH path if there is a current drive.

            if (CurrentDrive != null && resolvePathIfPossible)
            {
                string newRoot = GetProviderRootFromSpecifiedRoot(drive.Root, drive.Provider);

                if (newRoot != null)
                {
                    drive.SetRoot(newRoot);
                }
            }

            PSDriveInfo result = null;

            try
            {
                result = driveProvider.NewDrive(drive, context);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception e) // Catch-all OK, 3rd party callout
            {
                CommandProcessorBase.CheckForSevereException(e);
                ProviderInvocationException pie =
                    NewProviderInvocationException(
                        "NewDriveProviderException",
                        SessionStateStrings.NewDriveProviderException,
                        driveProvider.ProviderInfo,
                        drive.Root,
                        e);
                context.WriteError(
                    new ErrorRecord(
                        pie.ErrorRecord,
                        pie));
            }
            finally
            {
                drive.DriveBeingCreated = false;
            }
            return result;
        } // ValidateDriveWithProvider
Exemplo n.º 5
0
        } // GenerateNewPathsWithGlobLeaf

        /// <summary>
        /// Gets the child names in the specified path by using the provider
        /// </summary>
        /// 
        /// <param name="dir">
        /// The path of the directory to get the child names from. If this is an Msh Path,
        /// dirIsProviderPath must be false, If this is a provider-internal path,
        /// dirIsProviderPath must be true.
        /// </param>
        /// 
        /// <param name="leafElement">
        /// The element that we are ultimately looking for. Used to set filters on the context
        /// if desired.
        /// </param>
        /// 
        /// <param name="getAllContainers">
        /// Determines if the GetChildNames call should get all containers even if they don't
        /// match the filter.
        /// </param>
        /// 
        /// <param name="context">
        /// The context to be used for the command. The context is copied to a new context, the
        /// results are accumulated and then returned.
        /// </param>
        /// 
        /// <param name="dirIsProviderPath">
        /// Specifies whether the dir parameter is a provider-internal path (true) or Msh Path (false).
        /// </param>
        /// 
        /// <param name="drive">
        /// The drive to use to qualify the Msh path if dirIsProviderPath is false.
        /// </param>
        /// 
        /// <param name="provider">
        /// The provider to use to get the child names.
        /// </param>
        /// 
        /// <param name="modifiedDirPath">
        /// Returns the modified dir path. If dirIsProviderPath is true, this is the unescaped dir path.
        /// If dirIsProviderPath is false, this is the unescaped resolved provider path.
        /// </param>
        /// 
        /// <returns>
        /// A collection of PSObjects whose BaseObject is a string that contains the name of the child.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="dir"/> or <paramref name="drive"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// If the path is a provider-qualified path for a provider that is
        /// not loaded into the system.
        /// </exception>
        /// 
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="path"/> refers to a drive that could not be found.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider used to build the path threw an exception.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="path"/> represents is not a NavigationCmdletProvider
        /// or ContainerCmdletProvider.
        /// </exception>
        /// 
        /// <exception cref="InvalidOperationException">
        /// If the <paramref name="path"/> starts with "~" and the home location is not set for 
        /// the provider.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with the <paramref name="path"/> threw an
        /// exception when its GetParentPath or MakePath was called while
        /// processing the <paramref name="path"/>.
        /// </exception>
        /// 
        /// <exception cref="PipelineStoppedException">
        /// If <paramref name="context"/> has been signaled for
        /// StopProcessing.
        /// </exception>
        /// 
        /// <exception>
        /// Any exception can be thrown by the provider that is called to build
        /// the provider path.
        /// </exception>
        /// 
        private Collection<PSObject> GetChildNamesInDir(
            string dir,
            string leafElement,
            bool getAllContainers,
            CmdletProviderContext context,
            bool dirIsProviderPath,
            PSDriveInfo drive,
            ContainerCmdletProvider provider,
            out string modifiedDirPath)
        {
            // See if the provider wants to convert the path and filter
            string convertedPath = null;
            string convertedFilter = null;
            string originalFilter = context.Filter;
            bool changedPathOrFilter = provider.ConvertPath(leafElement, context.Filter, ref convertedPath, ref convertedFilter, context);

            if (changedPathOrFilter)
            {
                if (s_tracer.IsEnabled)
                {
                    s_tracer.WriteLine("Provider converted path and filter.");
                    s_tracer.WriteLine("Original path: {0}", leafElement);
                    s_tracer.WriteLine("Converted path: {0}", convertedPath);
                    s_tracer.WriteLine("Original filter: {0}", context.Filter);
                    s_tracer.WriteLine("Converted filter: {0}", convertedFilter);
                }

                leafElement = convertedPath;
                context.Filter = convertedFilter;
            }

            ReturnContainers returnContainers = ReturnContainers.ReturnAllContainers;
            if (!getAllContainers)
            {
                returnContainers = ReturnContainers.ReturnMatchingContainers;
            }

            CmdletProviderContext getChildNamesContext =
                new CmdletProviderContext(context);

            // Remove the include/exclude filters from the new context
            getChildNamesContext.SetFilters(
                new Collection<string>(),
                new Collection<string>(),
                context.Filter);

            try
            {
                // Use the provider to get the children
                string unescapedDir = null;
                modifiedDirPath = null;

                if (dirIsProviderPath)
                {
                    modifiedDirPath = unescapedDir = context.SuppressWildcardExpansion ? dir : RemoveGlobEscaping(dir);
                }
                else
                {
                    Dbg.Diagnostics.Assert(
                        drive != null,
                        "Caller should verify that drive is not null when dirIsProviderPath is false");

                    // If the directory is an MSH path we must resolve it before calling GetChildNames()
                    // -- If the path is passed in by LiteralPath (context.SuppressWildcardExpansion == false), we surely should use 'dir' unchanged.
                    // -- If the path is passed in by Path (context.SuppressWildcardExpansion == true), we still should use 'dir' unchanged, in case that the special character
                    //    in 'dir' is escaped
                    modifiedDirPath = GetMshQualifiedPath(dir, drive);

                    ProviderInfo providerIgnored = null;
                    CmdletProvider providerInstanceIgnored = null;
                    Collection<string> resolvedPaths =
                        GetGlobbedProviderPathsFromMonadPath(
                            modifiedDirPath,
                            false,
                            getChildNamesContext,
                            out providerIgnored,
                            out providerInstanceIgnored);

                    // After resolving the path, we unescape the modifiedDirPath if necessary.
                    modifiedDirPath = context.SuppressWildcardExpansion
                                          ? modifiedDirPath
                                          : RemoveGlobEscaping(modifiedDirPath);
                    if (resolvedPaths.Count > 0)
                    {
                        unescapedDir = resolvedPaths[0];
                    }
                    else
                    {
                        // If there were no results from globbing but no
                        // exception was thrown, that means there was filtering.
                        // So return an empty collection and let the caller deal
                        // with it.

                        if (changedPathOrFilter)
                        {
                            context.Filter = originalFilter;
                        }

                        return new Collection<PSObject>();
                    }
                }

                if (provider.HasChildItems(unescapedDir, getChildNamesContext))
                {
                    provider.GetChildNames(
                        unescapedDir,
                        returnContainers,
                        getChildNamesContext);
                }

                // First check to see if there were any errors, and write them
                // to the real context if there are.

                if (getChildNamesContext.HasErrors())
                {
                    Collection<ErrorRecord> errors = getChildNamesContext.GetAccumulatedErrorObjects();

                    if (errors != null &&
                        errors.Count > 0)
                    {
                        foreach (ErrorRecord errorRecord in errors)
                        {
                            context.WriteError(errorRecord);
                        }
                    }
                }

                Collection<PSObject> childNamesObjectArray = getChildNamesContext.GetAccumulatedObjects();

                if (changedPathOrFilter)
                {
                    context.Filter = originalFilter;
                }

                return childNamesObjectArray;
            }
            finally
            {
                getChildNamesContext.RemoveStopReferral();
            }
        } // GetChildNamesInDir
Exemplo n.º 6
0
 private PSDriveInfo ValidateDriveWithProvider(DriveCmdletProvider driveProvider, PSDriveInfo drive, CmdletProviderContext context, bool resolvePathIfPossible)
 {
     drive.DriveBeingCreated = true;
     if ((this.CurrentDrive != null) && resolvePathIfPossible)
     {
         string providerRootFromSpecifiedRoot = this.GetProviderRootFromSpecifiedRoot(drive.Root, drive.Provider);
         if (providerRootFromSpecifiedRoot != null)
         {
             drive.SetRoot(providerRootFromSpecifiedRoot);
         }
     }
     PSDriveInfo info = null;
     try
     {
         info = driveProvider.NewDrive(drive, context);
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         throw;
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         ProviderInvocationException replaceParentContainsErrorRecordException = this.NewProviderInvocationException("NewDriveProviderException", SessionStateStrings.NewDriveProviderException, driveProvider.ProviderInfo, drive.Root, exception);
         context.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
     }
     finally
     {
         drive.DriveBeingCreated = false;
     }
     return info;
 }
Exemplo n.º 7
0
 internal void RenameItem(string path, string newName, CmdletProviderContext context)
 {
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     ProviderInfo info = null;
     CmdletProvider providerInstance = null;
     Collection<string> targetObject = this.Globber.GetGlobbedProviderPathsFromMonadPath(path, false, context, out info, out providerInstance);
     if (targetObject.Count == 1)
     {
         this.RenameItem(providerInstance, targetObject[0], newName, context);
     }
     else
     {
         ArgumentException exception = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "RenameMultipleItemError", new object[0]);
         context.WriteError(new ErrorRecord(exception, "RenameMultipleItemError", ErrorCategory.InvalidArgument, targetObject));
     }
 }
Exemplo n.º 8
0
 internal void RemoveDrive(string driveName, bool force, string scopeID, CmdletProviderContext context)
 {
     if (driveName == null)
     {
         throw PSTraceSource.NewArgumentNullException("driveName");
     }
     PSDriveInfo drive = this.GetDrive(driveName, scopeID);
     if (drive == null)
     {
         System.Management.Automation.DriveNotFoundException replaceParentContainsErrorRecordException = new System.Management.Automation.DriveNotFoundException(driveName, "DriveNotFound", SessionStateStrings.DriveNotFound);
         context.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
     }
     else
     {
         this.RemoveDrive(drive, force, scopeID, context);
     }
 }
Exemplo n.º 9
0
 internal string NormalizeRelativePath(string path, string basePath, CmdletProviderContext context)
 {
     string str2;
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     CmdletProviderContext context2 = new CmdletProviderContext(context);
     try
     {
         PSDriveInfo drive = null;
         ProviderInfo provider = null;
         string str = this.Globber.GetProviderPath(path, context2, out provider, out drive);
         if (context2.HasErrors())
         {
             context2.WriteErrorsToContext(context);
             return null;
         }
         if ((str == null) || (provider == null))
         {
             Exception exception = PSTraceSource.NewArgumentException("path");
             context.WriteError(new ErrorRecord(exception, "NormalizePathNullResult", ErrorCategory.InvalidArgument, path));
             return null;
         }
         if (drive != null)
         {
             context.Drive = drive;
             if (((this.GetProviderInstance(provider) is NavigationCmdletProvider) && !string.IsNullOrEmpty(drive.Root)) && path.StartsWith(drive.Root, StringComparison.OrdinalIgnoreCase))
             {
                 str = path;
             }
         }
         str2 = this.NormalizeRelativePath(provider, str, basePath, context);
     }
     finally
     {
         context2.RemoveStopReferral();
     }
     return str2;
 }
Exemplo n.º 10
0
        } // MoveItem

        /// <summary>
        /// Moves the item specified by path to the specified destination.
        /// </summary>
        /// 
        /// <param name="paths">
        /// The path(s) to the item(s) to be moved.
        /// </param>
        /// 
        /// <param name="destination">
        /// The path of the destination container.
        /// </param>
        /// 
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <returns>
        /// Nothing. All items that are moved are written into the context object.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// If the <paramref name="path"/> refers to a provider that could not be found.
        /// </exception>
        /// 
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="path"/> refers to a drive that could not be found.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="path"/> refers to does
        /// not support this operation.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider threw an exception.
        /// </exception>
        /// 
        /// <exception cref="ItemNotFoundException">
        /// If <paramref name="path"/> does not contain glob characters and
        /// could not be found.
        /// </exception>
        /// 
        internal void MoveItem(
            string[] paths,
            string destination,
            CmdletProviderContext context)
        {
            if (paths == null)
            {
                throw PSTraceSource.NewArgumentNullException("paths");
            }

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

            ProviderInfo provider = null;
            CmdletProvider providerInstance = null;

            Collection<PathInfo> providerDestinationPaths =
                Globber.GetGlobbedMonadPathsFromMonadPath(
                    destination,
                    true,
                    context,
                    out providerInstance);

            if (providerDestinationPaths.Count > 1)
            {
                ArgumentException argException =
                    PSTraceSource.NewArgumentException(
                        "destination",
                        SessionStateStrings.MoveItemOneDestination);

                context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destination));
            }
            else
            {
                foreach (string path in paths)
                {
                    if (path == null)
                    {
                        throw PSTraceSource.NewArgumentNullException("paths");
                    }

                    Collection<string> providerPaths =
                        Globber.GetGlobbedProviderPathsFromMonadPath(
                            path,
                            false,
                            context,
                            out provider,
                            out providerInstance);

                    // Check to be sure we resolved at least one item to move and that the
                    // destination is a container.

                    if (providerPaths.Count > 1 &&
                        providerDestinationPaths.Count > 0 &&
                        !IsItemContainer(providerDestinationPaths[0].Path))
                    {
                        ArgumentException argException =
                            PSTraceSource.NewArgumentException(
                                "path",
                                SessionStateStrings.MoveItemPathMultipleDestinationNotContainer);

                        context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, providerDestinationPaths[0]));
                    }
                    else
                    {
                        PSDriveInfo unusedPSDriveInfo = null;
                        ProviderInfo destinationProvider = null;

                        CmdletProviderContext destinationContext = new CmdletProviderContext(this.ExecutionContext);

                        string destinationProviderInternalPath = null;

                        if (providerDestinationPaths.Count > 0)
                        {
                            destinationProviderInternalPath =
                                Globber.GetProviderPath(
                                    providerDestinationPaths[0].Path,
                                    destinationContext,
                                    out destinationProvider,
                                    out unusedPSDriveInfo);
                        }
                        else
                        {
                            // Since the path doesn't exist, just convert it to a
                            // provider path and continue.

                            destinationProviderInternalPath =
                                Globber.GetProviderPath(
                                    destination,
                                    destinationContext,
                                    out destinationProvider,
                                    out unusedPSDriveInfo);
                        }

                        // Now verify the providers are the same.

                        if (!String.Equals(
                                provider.FullName,
                                destinationProvider.FullName,
                                StringComparison.OrdinalIgnoreCase))
                        {
                            ArgumentException argException =
                                PSTraceSource.NewArgumentException(
                                    "destination",
                                    SessionStateStrings.MoveItemSourceAndDestinationNotSameProvider);

                            context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, providerPaths));
                        }
                        else
                        {
                            foreach (string providerPath in providerPaths)
                            {
                                MoveItemPrivate(providerInstance, providerPath, destinationProviderInternalPath, context);
                            }
                        }
                    }
                }
            }
        } // MoveItem
Exemplo n.º 11
0
        private bool isValidSession(PSSession session, CmdletProviderContext context, out PSLanguageMode? languageMode)
        {
            // session == null is validated by the parameter binding
            if (session.Availability != RunspaceAvailability.Available)
            {
                context.WriteError(new ErrorRecord(
                                    new InvalidOperationException(
                                        String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                            SessionStateStrings.CopyItemSessionProperties,
                                            "Availability", session.Availability)),
                                            "SessionIsNotAvailable",
                                        ErrorCategory.InvalidOperation,
                                        session.Availability));

                languageMode = null;
                return false;
            }

            languageMode = session.Runspace.SessionStateProxy.LanguageMode;

            return true;
        }
Exemplo n.º 12
0
        } // CopyItemDynamicParameters

        // This function validates a remote path, and if it exists, it returns the root path.
        //
        private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession session, CmdletProviderContext context, PSLanguageMode? languageMode, bool sourceIsRemote)
        {
            Hashtable op = null;

            using (PowerShell ps = PowerShell.Create())
            {
                ps.Runspace = session.Runspace;

                // Check to see if the remote PSSession is running in constrained or no language mode and if so
                // then also if the path validation function already exists in the session (for the User drive
                // custom endpoint case).  Otherwise error out.
                if (languageMode.HasValue &&
                    (languageMode.Value == PSLanguageMode.ConstrainedLanguage || languageMode.Value == PSLanguageMode.NoLanguage))
                {
                    var psRemoteUtilsName = CopyFileRemoteUtils.PSCopyRemoteUtilsName;
                    ps.Runspace = session.Runspace;
                    ps.AddCommand("Get-Command").AddArgument(psRemoteUtilsName);
                    var result = ps.Invoke<bool>();

                    if (result.Count == 0)
                    {
                        context.WriteError(new ErrorRecord(
                            new InvalidOperationException(
                                String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    SessionStateStrings.CopyItemSessionProperties,
                                    "LanguageMode",
                                    session.Runspace.SessionStateProxy.LanguageMode)
                                ),
                                "SessionIsNotInFullLanguageMode",
                                ErrorCategory.InvalidOperation,
                                session.Availability
                            )
                        );

                        return null;
                    }

                    ps.Commands.Clear();
                    ps.Streams.ClearStreams();
                    ps.AddCommand(psRemoteUtilsName);
                }
                else
                {
                    string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition;
                    ps.AddScript(remoteScript);
                }

                ps.AddParameter("pathToValidate", path);

                if (sourceIsRemote)
                {
                    ps.AddParameter("sourceIsRemote", true);
                }

                op = Microsoft.PowerShell.Commands.SafeInvokeCommand.Invoke(ps, null, context);
            }

            if (op == null)
            {
                context.WriteError(new ErrorRecord(
                                new InvalidOperationException(
                                    String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture, SessionStateStrings.CopyItemValidateRemotePath, path)),
                                    "FailedToValidateRemotePath",
                                    ErrorCategory.InvalidOperation,
                                    path));
                return null;
            }

            // If the remote path is not absolute, display an error to the user.
            if (op["IsAbsolute"] != null)
            {
                bool isAbsolute = (bool)op["IsAbsolute"];
                if (!isAbsolute)
                {
                    context.WriteError(new ErrorRecord(
                                        new ArgumentException(
                                            String.Format(
                                            System.Globalization.CultureInfo.InvariantCulture, SessionStateStrings.CopyItemRemotelyPathIsNotAbsolute, path)),
                                            "RemotePathIsNotAbsolute",
                                            ErrorCategory.InvalidArgument,
                                            path));
                    return null;
                }
            }

            bool pathExist = false;
            string root = null;

            if (op["Exists"] != null)
                pathExist = (bool)op["Exists"];

            if (op["Root"] != null)
                root = (string)op["Root"];

            // Here there are two scenarios:
            // 1) If the source is remote and the path does not exist, error out.
            bool invalidRemoteSource = (sourceIsRemote && (!pathExist));

            // 2) For a remote destination, if the root does not exist, error out.
            bool invalidRemoteDestination = (root == null);

            if (invalidRemoteSource || invalidRemoteDestination)
            {
                context.WriteError(new ErrorRecord(
                                            new ArgumentException(
                                                String.Format(
                                                System.Globalization.CultureInfo.InvariantCulture, SessionStateStrings.PathNotFound, path)),
                                                "RemotePathNotFound",
                                                ErrorCategory.InvalidArgument,
                                                path));
                return null;
            }

            return root;
        }
Exemplo n.º 13
0
        } // CopyItem

        /// <summary>
        /// Copies an item at the specified path to an item at the <paramref name="copyPath" />.
        /// </summary>
        /// 
        /// <param name="paths">
        /// The path(s) of the item(s) to copy.
        /// </param>
        /// 
        /// <param name="copyPath">
        /// The path of the item to copy to.
        /// </param>
        /// 
        /// <param name="recurse">
        /// Tells the provider to recurse sub-containers when copying.
        /// </param>
        /// 
        /// <param name="copyContainers">
        /// Determines how the source container is used in the copy operation.
        /// </param>
        ///
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// If the <paramref name="path"/> refers to a provider that could not be found.
        /// </exception>
        /// 
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="path"/> refers to a drive that could not be found.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="path"/> refers to does
        /// not support this operation.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider threw an exception.
        /// </exception>
        /// 
        /// <exception cref="ItemNotFoundException">
        /// If <paramref name="path"/> does not contain glob characters and
        /// could not be found.
        /// </exception>
        /// 
        internal void CopyItem(
            string[] paths,
            string copyPath,
            bool recurse,
            CopyContainers copyContainers,
            CmdletProviderContext context)
        {
            if (paths == null)
            {
                throw PSTraceSource.NewArgumentNullException("paths");
            }

            if (copyPath == null)
            {
                copyPath = String.Empty;
            }

            // Get the provider specific path for the destination

            PSDriveInfo unusedDrive = null;
            ProviderInfo destinationProvider = null;
            Microsoft.PowerShell.Commands.CopyItemDynamicParameters dynamicParams = context.DynamicParameters as Microsoft.PowerShell.Commands.CopyItemDynamicParameters;
            bool destinationIsRemote = false;
            bool sourceIsRemote = false;
            string providerDestinationPath;
            Runspaces.PSSession session = null;

            if (dynamicParams != null)
            {
                if (dynamicParams.FromSession != null)
                {
                    sourceIsRemote = true;
                    session = dynamicParams.FromSession;
                }
                if (dynamicParams.ToSession != null)
                {
                    destinationIsRemote = true;
                    session = dynamicParams.ToSession;
                }
            }

            if (sourceIsRemote && destinationIsRemote)
            {
                context.WriteError(new ErrorRecord(
                           new ArgumentException(
                               String.Format(System.Globalization.CultureInfo.InvariantCulture, SessionStateStrings.CopyItemFromSessionToSession, "FromSession", "ToSession")),
                               "InvalidInput",
                                ErrorCategory.InvalidArgument,
                                dynamicParams));
                return;
            }

            // Validate that the session is available and the language mode is not set to ConstrainedLanguage or NoLanguage.
            PSLanguageMode? remoteLanguageMode = null;
            if (sourceIsRemote || destinationIsRemote)
            {
                if (!isValidSession(session, context, out remoteLanguageMode))
                {
                    return;
                }
            }

            if (!destinationIsRemote)
            {
                providerDestinationPath =
                   Globber.GetProviderPath(
                       copyPath,
                       context,
                       out destinationProvider,
                       out unusedDrive);
            }
            else
            {
                // Validate remote destination path
                providerDestinationPath = copyPath;
                if (String.IsNullOrEmpty(providerDestinationPath))
                {
                    context.WriteError(new ErrorRecord(
                                            new ArgumentNullException(
                                                    String.Format(
                                                    System.Globalization.CultureInfo.InvariantCulture,
                                                    SessionStateStrings.CopyItemRemotelyPathIsNullOrEmpty,
                                                    "Destination")),
                                            "CopyItemRemoteDestinationIsNullOrEmpty",
                                            ErrorCategory.InvalidArgument,
                                            providerDestinationPath));
                    return;
                }

                string root = ValidateRemotePathAndGetRoot(providerDestinationPath, session, context, remoteLanguageMode, false);
                if (root == null)
                {
                    return;
                }
            }

            s_tracer.WriteLine("providerDestinationPath = {0}", providerDestinationPath);

            ProviderInfo provider = null;
            CmdletProvider providerInstance = null;

            foreach (string path in paths)
            {
                if (path == null)
                {
                    throw PSTraceSource.NewArgumentNullException("paths");
                }

                Collection<string> providerPaths;

                if (sourceIsRemote)
                {
                    // Get the root for the remote path
                    string root = ValidateRemotePathAndGetRoot(path, session, context, remoteLanguageMode, true);
                    if (root == null)
                    {
                        return;
                    }

                    providerInstance = ExecutionContext.SessionState.Internal.GetProviderInstance("FileSystem");
                    providerPaths = new Collection<string>();
                    providerPaths.Add(path);
                }
                else
                {
                    providerPaths =
                    Globber.GetGlobbedProviderPathsFromMonadPath(
                        path,
                        false,
                        context,
                        out provider,
                        out providerInstance);
                }

                // Ensure that the source and destination are the same provider. Copying between
                // providers is not supported

                if (!sourceIsRemote && !destinationIsRemote && provider != destinationProvider)
                {
                    ArgumentException argException =
                        PSTraceSource.NewArgumentException(
                            "path",
                            SessionStateStrings.CopyItemSourceAndDestinationNotSameProvider);

                    context.WriteError(
                        new ErrorRecord(
                            argException,
                            "CopyItemSourceAndDestinationNotSameProvider",
                            ErrorCategory.InvalidArgument,
                            providerPaths));

                    return;
                }

                bool destinationIsContainer = false;

                if (!destinationIsRemote)
                {
                    destinationIsContainer = IsItemContainer(
                        providerInstance,
                        providerDestinationPath,
                        context);

                    s_tracer.WriteLine("destinationIsContainer = {0}", destinationIsContainer);
                }

                foreach (string providerPath in providerPaths)
                {
                    // Making sure to obey the StopProcessing.
                    if (context.Stopping)
                    {
                        return;
                    }

                    if (sourceIsRemote || destinationIsRemote)
                    {
                        CopyItem(
                            providerInstance,
                            providerPath,
                            providerDestinationPath,
                            recurse,
                            context);
                        continue;
                    }

                    bool sourceIsContainer =
                         IsItemContainer(
                            providerInstance,
                            providerPath,
                            context);

                    s_tracer.WriteLine("sourcIsContainer = {0}", sourceIsContainer);

                    if (sourceIsContainer)
                    {
                        if (destinationIsContainer)
                        {
                            if (!recurse && copyContainers == CopyContainers.CopyChildrenOfTargetContainer)
                            {
                                // Copying a container to a container without the -container or -recurse
                                // switch is an error.

                                Exception e =
                                    PSTraceSource.NewArgumentException(
                                        "path",
                                        SessionStateStrings.CopyContainerToContainerWithoutRecurseOrContainer);

                                context.WriteError(new ErrorRecord(
                                    e,
                                    "CopyContainerToContainerWithoutRecurseOrContainer",
                                    ErrorCategory.InvalidArgument,
                                    providerPath));
                            }
                            else if (recurse && copyContainers == CopyContainers.CopyChildrenOfTargetContainer)
                            {
                                // Copy all the leaf items to a single container

                                CopyRecurseToSingleContainer(
                                    providerInstance,
                                    providerPath,
                                    providerDestinationPath,
                                    context);
                            }
                            else
                            {
                                // Call the provider to do a recurse copy of all the items

                                CopyItem(
                                    providerInstance,
                                    providerPath,
                                    providerDestinationPath,
                                    recurse,
                                    context);
                            }
                        }
                        else
                        {
                            // Since we know the destination isn't a container, check to 
                            // see if it exists.

                            if (ItemExists(providerInstance, providerDestinationPath, context))
                            {
                                // Since the item exists and is not a container it must
                                // be a leaf. Copying a container to a leaf is an error

                                Exception e =
                                    PSTraceSource.NewArgumentException(
                                        "path",
                                        SessionStateStrings.CopyContainerItemToLeafError);

                                context.WriteError(new ErrorRecord(
                                    e,
                                    "CopyContainerItemToLeafError",
                                    ErrorCategory.InvalidArgument,
                                    providerPath));
                            }
                            else
                            {
                                // Copy the container to a non-existing path

                                CopyItem(
                                    providerInstance,
                                    providerPath,
                                    providerDestinationPath,
                                    recurse,
                                    context);
                            }
                        }
                    }
                    else
                    {
                        // Copy a leaf to the destination

                        CopyItem(
                            providerInstance,
                            providerPath,
                            providerDestinationPath,
                            recurse,
                            context);
                    }
                }
            }
        } // CopyItem
Exemplo n.º 14
0
        } // RenameItem

        /// <summary>
        /// Renames the item at the specified path to the new name provided.
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the item to rename.
        /// </param>
        /// 
        /// <param name="newName">
        /// The name to which the item should be renamed. This name should always be 
        /// relative to the parent container.
        /// </param>
        /// 
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <returns>
        /// Nothing. All items that are renamed are written into the context object.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> or <paramref name="propertyToClear"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// If the <paramref name="path"/> refers to a provider that could not be found.
        /// </exception>
        /// 
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="path"/> refers to a drive that could not be found.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="path"/> refers to does
        /// not support this operation.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider threw an exception.
        /// </exception>
        /// 
        /// <exception cref="ItemNotFoundException">
        /// If <paramref name="path"/> does not contain glob characters and
        /// could not be found.
        /// </exception>
        /// 
        internal void RenameItem(
            string path,
            string newName,
            CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            ProviderInfo provider = null;
            CmdletProvider providerInstance = null;

            Collection<string> providerPaths =
                Globber.GetGlobbedProviderPathsFromMonadPath(
                    path,
                    false,
                    context,
                    out provider,
                    out providerInstance);

            // Can only rename one item at a time, so if we glob more than 
            // one item write out an error.

            if (providerPaths.Count == 1)
            {
                RenameItem(providerInstance, providerPaths[0], newName, context);
            }
            else
            {
                ArgumentException argException =
                    PSTraceSource.NewArgumentException(
                        "path",
                        SessionStateStrings.RenameMultipleItemError);

                context.WriteError(
                    new ErrorRecord(
                        argException,
                        "RenameMultipleItemError",
                        ErrorCategory.InvalidArgument,
                        providerPaths));
            }
        } // RenameItem
Exemplo n.º 15
0
 internal void WriteErrorsToContext(CmdletProviderContext errorContext)
 {
     if (errorContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("errorContext");
     }
     if (this.HasErrors())
     {
         foreach (ErrorRecord record in this.GetAccumulatedErrorObjects())
         {
             errorContext.WriteError(record);
         }
     }
 }
Exemplo n.º 16
0
 internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext context)
 {
     if (drive == null)
     {
         throw PSTraceSource.NewArgumentNullException("drive");
     }
     if (context == null)
     {
         throw PSTraceSource.NewArgumentNullException("context");
     }
     if (!IsValidDriveName(drive.Name))
     {
         throw PSTraceSource.NewArgumentException("drive.Name", "SessionStateStrings", "DriveNameIllegalCharacters", new object[0]);
     }
     PSDriveInfo newDrive = this.ValidateDriveWithProvider(drive, context, true);
     if (newDrive != null)
     {
         if (string.Compare(newDrive.Name, drive.Name, true, Thread.CurrentThread.CurrentCulture) != 0)
         {
             throw this.NewProviderInvocationException("NewDriveProviderFailed", SessionStateStrings.NewDriveProviderFailed, drive.Provider, drive.Root, PSTraceSource.NewArgumentException("root"));
         }
         try
         {
             SessionStateScope currentScope = this.currentScope;
             if (!string.IsNullOrEmpty(scopeID))
             {
                 currentScope = this.GetScopeByID(scopeID);
             }
             currentScope.NewDrive(newDrive);
         }
         catch (ArgumentException exception2)
         {
             context.WriteError(new ErrorRecord(exception2, "NewDriveError", ErrorCategory.InvalidArgument, newDrive));
             return;
         }
         catch (SessionStateException)
         {
             throw;
         }
         if (this.ProvidersCurrentWorkingDrive[drive.Provider] == null)
         {
             this.ProvidersCurrentWorkingDrive[drive.Provider] = drive;
         }
         context.WriteObject(newDrive);
     }
 }
Exemplo n.º 17
0
        } //NormalizeRelativePath

        /// <summary>
        /// Normalizes the path that was passed in and returns the normalized path
        /// as a relative path to the basePath that was passed.
        /// </summary>
        /// 
        /// <param name="path">
        /// An MSH path to an item. The item should exist
        /// or the provider should write out an error.
        /// </param>
        /// 
        /// <param name="basePath">
        /// The path that the return value should be relative to.
        /// </param>
        /// 
        /// <param name="context">
        /// The context under which the command is running.
        /// </param>
        /// 
        /// <returns>
        /// A normalized path that is relative to the basePath that was passed. 
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the <paramref name="providerInstance"/> does not support this operation.
        /// </exception>
        /// 
        /// <exception cref="PipelineStoppedException">
        /// If the pipeline is being stopped while executing the command.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider threw an exception.
        /// </exception>
        /// 
        internal string NormalizeRelativePath(
            string path,
            string basePath,
            CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            CmdletProviderContext getProviderPathContext =
                new CmdletProviderContext(context);

            try
            {
                PSDriveInfo drive = null;
                ProviderInfo provider = null;

                string workingPath = Globber.GetProviderPath(
                     path,
                     getProviderPathContext,
                     out provider,
                     out drive);

                if (getProviderPathContext.HasErrors())
                {
                    getProviderPathContext.WriteErrorsToContext(context);
                    return null;
                }

                if (workingPath == null ||
                    provider == null)
                {
                    // Since the provider didn't write an error, and we didn't get any
                    // results ourselves, we need to write out our own error.

                    Exception e = PSTraceSource.NewArgumentException("path");
                    context.WriteError(new ErrorRecord(e, "NormalizePathNullResult", ErrorCategory.InvalidArgument, path));
                    return null;
                }

                if (basePath != null)
                {
                    PSDriveInfo baseDrive = null;
                    ProviderInfo baseProvider = null;

                    Globber.GetProviderPath(
                         basePath,
                         getProviderPathContext,
                         out baseProvider,
                         out baseDrive);

                    if (drive != null && baseDrive != null)
                    {
                        if (!drive.Name.Equals(baseDrive.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            // Make sure they are from physically different drives
                            // Doing StartsWith from both directions covers the following cases
                            // C:\ and C:\Temp
                            // C:\Temp and C:\
                            if (!(drive.Root.StartsWith(baseDrive.Root, StringComparison.OrdinalIgnoreCase) ||
                                (baseDrive.Root.StartsWith(drive.Root, StringComparison.OrdinalIgnoreCase))))
                            {
                                // In this case, no normalization is necessary
                                return path;
                            }
                        }
                    }
                }

                if (drive != null)
                {
                    context.Drive = drive;

                    // Detect if the original path was already a
                    // provider path. This happens when a drive doesn't
                    // have a rooted root -- such as HKEY_LOCAL_MACHINE instead of
                    // \\HKEY_LOCAL_MACHINE
                    if (
                        (GetProviderInstance(provider) is NavigationCmdletProvider) &&
                        (!String.IsNullOrEmpty(drive.Root)) &&
                        (path.StartsWith(drive.Root, StringComparison.OrdinalIgnoreCase)))
                    {
                        //
                        // If the drive root doesn't end with a path separator then there is a chance the
                        // path starts with the drive root name but doesn't actually refer to it.  For example,
                        // (see Win8 bug 922001) consider drive with root HKEY_LOCAL_MACHINE named 
                        // HKEY_LOCAL_MACHINE_foo.  The path would start with the drive root but is not a provider
                        // path.
                        //
                        // We will remediate this by only considering this a provider path if 
                        // 1.  The drive root ends with a path separator.
                        // OR
                        // 2.  The path starts with the drive root followed by a path separator
                        // OR
                        // 3.  The path exactly matches the drive root.
                        // 

                        // 1. Test for the drive root ending with a path separator.
                        bool driveRootEndsWithPathSeparator = IsPathSeparator(drive.Root[drive.Root.Length - 1]);


                        // 2. Test for the path starting with the drive root followed by a path separator
                        int indexAfterDriveRoot = drive.Root.Length;
                        bool pathStartsWithDriveRootAndPathSeparator = indexAfterDriveRoot < path.Length && IsPathSeparator(path[indexAfterDriveRoot]);


                        // 3. Test for the drive root exactly matching the path.
                        //    Since we know the path starts with the drive root then they are equal if the lengths are equal.
                        bool pathEqualsDriveRoot = drive.Root.Length == path.Length;


                        if (driveRootEndsWithPathSeparator || pathStartsWithDriveRootAndPathSeparator || pathEqualsDriveRoot)
                        {
                            workingPath = path;
                        }
                    }
                }

                return NormalizeRelativePath(provider, workingPath, basePath, context);
            }
            finally
            {
                getProviderPathContext.RemoveStopReferral();
            }
        } // NormalizeRelativePath
Exemplo n.º 18
0
 internal void RemoveDrive(PSDriveInfo drive, bool force, string scopeID, CmdletProviderContext context)
 {
     bool flag = false;
     try
     {
         flag = this.CanRemoveDrive(drive, context);
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         throw;
     }
     catch (ProviderInvocationException)
     {
         if (!force)
         {
             throw;
         }
     }
     if (flag || force)
     {
         if (!string.IsNullOrEmpty(scopeID))
         {
             this.GetScopeByID(scopeID).RemoveDrive(drive);
             if (this.ProvidersCurrentWorkingDrive[drive.Provider] == drive)
             {
                 this.ProvidersCurrentWorkingDrive[drive.Provider] = null;
             }
         }
         else
         {
             SessionStateScopeEnumerator enumerator = new SessionStateScopeEnumerator(this.CurrentScope);
             foreach (SessionStateScope scope in (IEnumerable<SessionStateScope>) enumerator)
             {
                 try
                 {
                     PSDriveInfo info = scope.GetDrive(drive.Name);
                     if (info != null)
                     {
                         scope.RemoveDrive(drive);
                         if (this.ProvidersCurrentWorkingDrive[drive.Provider] == info)
                         {
                             this.ProvidersCurrentWorkingDrive[drive.Provider] = null;
                         }
                         break;
                     }
                 }
                 catch (ArgumentException)
                 {
                 }
             }
         }
     }
     else
     {
         PSInvalidOperationException replaceParentContainsErrorRecordException = PSTraceSource.NewInvalidOperationException("SessionStateStrings", "DriveRemovalPreventedByProvider", new object[] { drive.Name, drive.Provider });
         context.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
     }
 }
Exemplo n.º 19
0
        } // RemoveDrive

        /// <summary>
        /// Removes the specified drive.
        /// </summary>
        /// 
        /// <param name="drive">
        /// The drive to be removed.
        /// </param>
        /// 
        /// <param name="force">
        /// Determines whether drive should be forcefully removed even if there was errors.
        /// </param>
        ///
        /// <param name="scopeID">
        /// The ID of the scope from which to remove the drive.
        /// If the scope ID is null or empty, the scope hierarchy will be searched
        /// starting at the current scope through all the parent scopes to the
        /// global scope until a drive of the given name is found to remove.
        /// </param>
        /// 
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        /// 
        internal void RemoveDrive(
            PSDriveInfo drive,
            bool force,
            string scopeID,
            CmdletProviderContext context)
        {
            // Make sure that the CanRemoveDrive is called even if we are forcing
            // the removal because we want the provider to have a chance to
            // cleanup.

            bool canRemove = false;

            try
            {
                canRemove = CanRemoveDrive(drive, context);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (ProviderInvocationException)
            {
                if (!force)
                {
                    throw;
                }
            }

            // Now remove the drive if there was no error or we are forcing the removal

            if (canRemove || force)
            {
                // The scope ID wasn't defined or wasn't recognizable
                // so do a search through the scopes looking for the
                // drive.

                if (String.IsNullOrEmpty(scopeID))
                {
                    SessionStateScopeEnumerator scopeEnumerator =
                        new SessionStateScopeEnumerator(CurrentScope);

                    foreach (SessionStateScope scope in scopeEnumerator)
                    {
                        try
                        {
                            PSDriveInfo result = scope.GetDrive(drive.Name);
                            if (result != null)
                            {
                                scope.RemoveDrive(drive);

                                // If the drive is the current drive for the provider, remove
                                // it from the current drive list.

                                if (ProvidersCurrentWorkingDrive[drive.Provider] == result)
                                {
                                    ProvidersCurrentWorkingDrive[drive.Provider] = null;
                                }
                                break;
                            }
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                }
                else
                {
                    SessionStateScope scope = GetScopeByID(scopeID);
                    scope.RemoveDrive(drive);


                    // If the drive is the current drive for the provider, remove
                    // it from the current drive list.

                    if (ProvidersCurrentWorkingDrive[drive.Provider] == drive)
                    {
                        ProvidersCurrentWorkingDrive[drive.Provider] = null;
                    }
                }
            }
            else
            {
                PSInvalidOperationException e =
                    (PSInvalidOperationException)
                    PSTraceSource.NewInvalidOperationException(
                        SessionStateStrings.DriveRemovalPreventedByProvider,
                        drive.Name,
                        drive.Provider);

                context.WriteError(
                    new ErrorRecord(
                        e.ErrorRecord,
                        e));
            }
        } // RemoveDrive
Exemplo n.º 20
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);
         }
     }
 }
Exemplo n.º 21
0
        } // NewDrive

        /// <summary>
        /// Adds a drive to the PowerShell namespace.
        /// </summary>
        /// 
        /// <param name="drive">
        /// The new drive to be added.
        /// </param>
        /// 
        /// <param name="scopeID">
        /// The ID for the scope to add the drive to. The scope ID can be any of the
        /// "special" scope identifiers like "global", "local", or "private" or it
        /// can be a numeric identifier that is a count of the number of parent
        /// scopes up from the current scope to put the drive in.
        /// If this parameter is null or empty the drive will be placed in the
        /// current scope.
        /// </param>
        /// 
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="drive"/> or <paramref name="context"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ArgumentException">
        /// If the drive already exists
        /// or
        /// If <paramref name="drive"/>.Name contains one or more invalid characters; ~ / \\ . :
        /// </exception>
        /// 
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider is not a DriveCmdletProvider.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// The provider for the <paramref name="drive"/> could not be found.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider threw an exception or returned null.
        /// </exception>
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If creating the drive will overflow the MaximumDriveCount limit.
        /// </exception>
        /// 
        internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext context)
        {
            if (drive == null)
            {
                throw PSTraceSource.NewArgumentNullException("drive");
            }

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

            if (!IsValidDriveName(drive.Name))
            {
                ArgumentException e =
                    PSTraceSource.NewArgumentException(
                        "drive.Name",
                        SessionStateStrings.DriveNameIllegalCharacters);

                throw e;
            }

            // Allow the provider a chance to approve the drive and set
            // provider specific data

            PSDriveInfo result = ValidateDriveWithProvider(drive, context, true);

            // We assume that the provider wrote the error message as they
            // are suppose to.
            if (result == null)
            {
                return;
            }

            if (String.Compare(result.Name, drive.Name, StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                // Set the drive in the current scope.

                try
                {
                    SessionStateScope scope = _currentScope;

                    if (!String.IsNullOrEmpty(scopeID))
                    {
                        scope = GetScopeByID(scopeID);
                    }

                    scope.NewDrive(result);
                }
                catch (ArgumentException argumentException)
                {
                    // Wrap up the exception and write it to the error stream

                    context.WriteError(
                        new ErrorRecord(
                            argumentException,
                            "NewDriveError",
                            ErrorCategory.InvalidArgument,
                            result));
                    return;
                }
                catch (SessionStateException)
                {
                    // This should be a pipeline terminating condition
                    throw;
                }


                if (ProvidersCurrentWorkingDrive[drive.Provider] == null)
                {
                    // Set the new drive as the current
                    // drive for the provider since there isn't one set.

                    ProvidersCurrentWorkingDrive[drive.Provider] = drive;
                }

                // Upon success, write the drive to the pipeline

                context.WriteObject(result);
            }
            else
            {
                ProviderInvocationException e =
                    NewProviderInvocationException(
                        "NewDriveProviderFailed",
                        SessionStateStrings.NewDriveProviderFailed,
                        drive.Provider,
                        drive.Root,
                        PSTraceSource.NewArgumentException("root"));

                throw e;
            }
        } // NewDrive
Exemplo n.º 22
0
 private void SetSecurityDescriptor(CmdletProvider providerInstance, string path, ObjectSecurity securityDescriptor, CmdletProviderContext context)
 {
     GetPermissionProviderInstance(providerInstance);
     try
     {
         providerInstance.SetSecurityDescriptor(path, securityDescriptor, context);
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         throw;
     }
     catch (PrivilegeNotHeldException exception)
     {
         context.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.PermissionDenied, path));
     }
     catch (UnauthorizedAccessException exception2)
     {
         context.WriteError(new ErrorRecord(exception2, exception2.GetType().FullName, ErrorCategory.PermissionDenied, path));
     }
     catch (NotSupportedException exception3)
     {
         context.WriteError(new ErrorRecord(exception3, exception3.GetType().FullName, ErrorCategory.InvalidOperation, path));
     }
     catch (SystemException exception4)
     {
         CommandProcessorBase.CheckForSevereException(exception4);
         context.WriteError(new ErrorRecord(exception4, exception4.GetType().FullName, ErrorCategory.InvalidOperation, path));
     }
     catch (Exception exception5)
     {
         CommandProcessorBase.CheckForSevereException(exception5);
         throw this.NewProviderInvocationException("SetSecurityDescriptorProviderException", SessionStateStrings.SetSecurityDescriptorProviderException, providerInstance.ProviderInfo, path, exception5);
     }
 }
Exemplo n.º 23
0
        public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileSystemProvider fileSystemContext, CmdletProviderContext cmdletContext, bool shouldHaveOutput)
        {
            bool useFileSystemProviderContext = (cmdletContext == null);

            if (useFileSystemProviderContext)
            {
                Dbg.Diagnostics.Assert(fileSystemContext != null, "The caller should verify FileSystemProvider context.");
            }

            Collection<Hashtable> output;
            try
            {
                output = ps.Invoke<Hashtable>();
            }
            catch (Exception e)
            {
                if (useFileSystemProviderContext)
                {
                    fileSystemContext.WriteError(new ErrorRecord(e, "CopyFileRemoteExecutionError", ErrorCategory.InvalidOperation, ps));
                    ps.Commands.Clear();
                }
                else
                {
                    cmdletContext.WriteError(new ErrorRecord(e, "CopyFileRemoteExecutionError", ErrorCategory.InvalidOperation, ps));
                    ps.Commands.Clear();
                }
                return null;
            }

            if (ps.HadErrors)
            {
                foreach (var error in ps.Streams.Error)
                {
                    if (useFileSystemProviderContext)
                    {
                        fileSystemContext.WriteError(error);
                    }
                    else
                    {
                        cmdletContext.WriteError(error);
                    }
                }
            }

            ps.Commands.Clear();

            if (shouldHaveOutput)
            {
                if (output.Count != 1 || output[0].GetType() != typeof(Hashtable))
                {
                    // unexpected output 
                    Dbg.Diagnostics.Assert(output[0] != null, "Expected an output from the remote call.");
                    return null;
                }
                return (Hashtable)output[0];
            }

            return null;
        }
Exemplo n.º 24
0
 internal void CopyItem(string[] paths, string copyPath, bool recurse, CopyContainers copyContainers, CmdletProviderContext context)
 {
     if (paths == null)
     {
         throw PSTraceSource.NewArgumentNullException("paths");
     }
     if (copyPath == null)
     {
         copyPath = string.Empty;
     }
     PSDriveInfo drive = null;
     ProviderInfo info2 = null;
     string path = this.Globber.GetProviderPath(copyPath, context, out info2, out drive);
     tracer.WriteLine("providerDestinationPath = {0}", new object[] { path });
     ProviderInfo info3 = null;
     CmdletProvider providerInstance = null;
     foreach (string str2 in paths)
     {
         if (str2 == null)
         {
             throw PSTraceSource.NewArgumentNullException("paths");
         }
         Collection<string> targetObject = this.Globber.GetGlobbedProviderPathsFromMonadPath(str2, false, context, out info3, out providerInstance);
         if (info3 != info2)
         {
             ArgumentException exception = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "CopyItemSourceAndDestinationNotSameProvider", new object[0]);
             context.WriteError(new ErrorRecord(exception, "CopyItemSourceAndDestinationNotSameProvider", ErrorCategory.InvalidArgument, targetObject));
             break;
         }
         bool flag = this.IsItemContainer(providerInstance, path, context);
         tracer.WriteLine("destinationIsContainer = {0}", new object[] { flag });
         foreach (string str3 in targetObject)
         {
             if (context.Stopping)
             {
                 break;
             }
             bool flag2 = this.IsItemContainer(providerInstance, str3, context);
             tracer.WriteLine("sourcIsContainer = {0}", new object[] { flag2 });
             if (flag2)
             {
                 if (flag)
                 {
                     if (!recurse && (copyContainers == CopyContainers.CopyChildrenOfTargetContainer))
                     {
                         Exception exception2 = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "CopyContainerToContainerWithoutRecurseOrContainer", new object[0]);
                         context.WriteError(new ErrorRecord(exception2, "CopyContainerToContainerWithoutRecurseOrContainer", ErrorCategory.InvalidArgument, str3));
                     }
                     else if (recurse && (copyContainers == CopyContainers.CopyChildrenOfTargetContainer))
                     {
                         this.CopyRecurseToSingleContainer(providerInstance, str3, path, context);
                     }
                     else
                     {
                         this.CopyItem(providerInstance, str3, path, recurse, context);
                     }
                 }
                 else if (this.ItemExists(providerInstance, path, context))
                 {
                     Exception exception3 = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "CopyContainerItemToLeafError", new object[0]);
                     context.WriteError(new ErrorRecord(exception3, "CopyContainerItemToLeafError", ErrorCategory.InvalidArgument, str3));
                 }
                 else
                 {
                     this.CopyItem(providerInstance, str3, path, recurse, context);
                 }
             }
             else
             {
                 this.CopyItem(providerInstance, str3, path, recurse, context);
             }
         }
     }
 }
Exemplo n.º 25
0
        } // MoveProperty

        /// <summary>
        /// Moves the specified property on the specified item to the specified property
        /// on the destination item.  The source and destination items can be the same item.
        /// </summary>
        /// 
        /// <param name="sourcePaths">
        /// The path(s) to the item(s) to move the property from.
        /// </param>
        /// 
        /// <param name="sourceProperty">
        /// The name of the property to be moved.
        /// </param>
        ///
        /// <param name="destinationPath">
        /// The path to the item to move the property to.
        /// </param> 
        /// 
        /// <param name="destinationProperty">
        /// The name of the property to move the property to.
        /// </param>
        ///
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="sourcePath"/>, <paramref name="sourceProperty"/>,
        /// <paramref name="destinationPath"/>, or <paramref name="destinationProperty"/>
        ///  is null.
        /// </exception>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="destinationPath"/> resolves to more than one item.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// If the <paramref name="sourcePath"/> refers to a provider that could not be found.
        /// </exception>
        /// 
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="sourcePath"/> refers to a drive that could not be found.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="sourcePath"/> refers to does
        /// not support this operation.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider threw an exception.
        /// </exception>
        /// 
        /// <exception cref="ItemNotFoundException">
        /// If <paramref name="path"/> does not contain glob characters and
        /// could not be found.
        /// </exception>
        /// 
        internal void MoveProperty(
            string[] sourcePaths,
            string sourceProperty,
            string destinationPath,
            string destinationProperty,
            CmdletProviderContext context)
        {
            if (sourcePaths == null)
            {
                throw PSTraceSource.NewArgumentNullException("sourcePaths");
            }

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

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

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

            ProviderInfo provider = null;
            CmdletProvider providerInstance = null;

            // We shouldn't be filtering the destination path

            CmdletProviderContext destinationContext = new CmdletProviderContext(context);

            destinationContext.SetFilters(
                new Collection<string>(),
                new Collection<string>(),
                null);

            Collection<string> destinationProviderPaths =
                Globber.GetGlobbedProviderPathsFromMonadPath(
                    destinationPath,
                    false,
                    destinationContext,
                    out provider,
                    out providerInstance);

            if (destinationProviderPaths.Count > 1)
            {
                ArgumentException argException =
                    PSTraceSource.NewArgumentException(
                        "destinationPath",
                        SessionStateStrings.MovePropertyDestinationResolveToSingle);

                context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destinationProviderPaths));
            }
            else
            {
                foreach (string sourcePath in sourcePaths)
                {
                    if (sourcePath == null)
                    {
                        throw PSTraceSource.NewArgumentNullException("sourcePaths");
                    }

                    Collection<string> providerPaths =
                        Globber.GetGlobbedProviderPathsFromMonadPath(
                            sourcePath,
                            false,
                            context,
                            out provider,
                            out providerInstance);

                    foreach (string providerPath in providerPaths)
                    {
                        MoveProperty(providerInstance, providerPath, sourceProperty, destinationProviderPaths[0], destinationProperty, context);
                    }
                }
            }
        } // MoveProperty
Exemplo n.º 26
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
Exemplo n.º 27
0
 internal void MoveItem(string[] paths, string destination, CmdletProviderContext context)
 {
     if (paths == null)
     {
         throw PSTraceSource.NewArgumentNullException("paths");
     }
     if (destination == null)
     {
         throw PSTraceSource.NewArgumentNullException("destination");
     }
     ProviderInfo info = null;
     CmdletProvider providerInstance = null;
     Collection<PathInfo> collection = this.Globber.GetGlobbedMonadPathsFromMonadPath(destination, true, context, out providerInstance);
     if (collection.Count > 1)
     {
         ArgumentException exception = PSTraceSource.NewArgumentException("destination", "SessionStateStrings", "MoveItemOneDestination", new object[0]);
         context.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, destination));
     }
     else
     {
         foreach (string str in paths)
         {
             if (str == null)
             {
                 throw PSTraceSource.NewArgumentNullException("paths");
             }
             Collection<string> targetObject = this.Globber.GetGlobbedProviderPathsFromMonadPath(str, false, context, out info, out providerInstance);
             if (((targetObject.Count > 1) && (collection.Count > 0)) && !this.IsItemContainer(collection[0].Path))
             {
                 ArgumentException exception2 = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "MoveItemPathMultipleDestinationNotContainer", new object[0]);
                 context.WriteError(new ErrorRecord(exception2, exception2.GetType().FullName, ErrorCategory.InvalidArgument, collection[0]));
             }
             else
             {
                 PSDriveInfo drive = null;
                 ProviderInfo provider = null;
                 CmdletProviderContext context2 = new CmdletProviderContext(this.ExecutionContext);
                 string str2 = null;
                 if (collection.Count > 0)
                 {
                     str2 = this.Globber.GetProviderPath(collection[0].Path, context2, out provider, out drive);
                 }
                 else
                 {
                     str2 = this.Globber.GetProviderPath(destination, context2, out provider, out drive);
                 }
                 if (!string.Equals(info.FullName, provider.FullName, StringComparison.OrdinalIgnoreCase))
                 {
                     ArgumentException exception3 = PSTraceSource.NewArgumentException("destination", "SessionStateStrings", "MoveItemSourceAndDestinationNotSameProvider", new object[0]);
                     context.WriteError(new ErrorRecord(exception3, exception3.GetType().FullName, ErrorCategory.InvalidArgument, targetObject));
                 }
                 else
                 {
                     foreach (string str3 in targetObject)
                     {
                         this.MoveItemPrivate(providerInstance, str3, str2, context);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 28
0
 private Collection<PSObject> GetChildNamesInDir(string dir, string leafElement, bool getAllContainers, CmdletProviderContext context, bool dirIsProviderPath, PSDriveInfo drive, ContainerCmdletProvider provider, out string modifiedDirPath)
 {
     string updatedPath = null;
     string updatedFilter = null;
     Collection<PSObject> collection4;
     string filter = context.Filter;
     bool flag = provider.ConvertPath(leafElement, context.Filter, ref updatedPath, ref updatedFilter, context);
     if (flag)
     {
         tracer.WriteLine("Provider converted path and filter.", new object[0]);
         tracer.WriteLine("Original path: " + leafElement, new object[0]);
         tracer.WriteLine("Converted path: " + updatedPath, new object[0]);
         tracer.WriteLine("Original filter: " + context.Filter, new object[0]);
         tracer.WriteLine("Converted filter: " + updatedFilter, new object[0]);
         leafElement = updatedPath;
         context.Filter = updatedFilter;
     }
     ReturnContainers returnAllContainers = ReturnContainers.ReturnAllContainers;
     if (!getAllContainers)
     {
         returnAllContainers = ReturnContainers.ReturnMatchingContainers;
     }
     CmdletProviderContext context2 = new CmdletProviderContext(context);
     context2.SetFilters(new Collection<string>(), new Collection<string>(), context.Filter);
     try
     {
         string path = null;
         modifiedDirPath = null;
         if (dirIsProviderPath)
         {
             modifiedDirPath = path = context.SuppressWildcardExpansion ? dir : RemoveGlobEscaping(dir);
         }
         else
         {
             modifiedDirPath = GetMshQualifiedPath(dir, drive);
             ProviderInfo info = null;
             CmdletProvider providerInstance = null;
             Collection<string> collection = this.GetGlobbedProviderPathsFromMonadPath(modifiedDirPath, false, context2, out info, out providerInstance);
             modifiedDirPath = context.SuppressWildcardExpansion ? modifiedDirPath : RemoveGlobEscaping(modifiedDirPath);
             if (collection.Count > 0)
             {
                 path = collection[0];
             }
             else
             {
                 if (flag)
                 {
                     context.Filter = filter;
                 }
                 return new Collection<PSObject>();
             }
         }
         if (provider.HasChildItems(path, context2))
         {
             provider.GetChildNames(path, returnAllContainers, context2);
         }
         if (context2.HasErrors())
         {
             Collection<ErrorRecord> accumulatedErrorObjects = context2.GetAccumulatedErrorObjects();
             if ((accumulatedErrorObjects != null) && (accumulatedErrorObjects.Count > 0))
             {
                 foreach (ErrorRecord record in accumulatedErrorObjects)
                 {
                     context.WriteError(record);
                 }
             }
         }
         Collection<PSObject> accumulatedObjects = context2.GetAccumulatedObjects();
         if (flag)
         {
             context.Filter = filter;
         }
         collection4 = accumulatedObjects;
     }
     finally
     {
         context2.RemoveStopReferral();
     }
     return collection4;
 }
Exemplo n.º 29
0
 internal void MoveProperty(string[] sourcePaths, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext context)
 {
     if (sourcePaths == null)
     {
         throw PSTraceSource.NewArgumentNullException("sourcePaths");
     }
     if (sourceProperty == null)
     {
         throw PSTraceSource.NewArgumentNullException("sourceProperty");
     }
     if (destinationPath == null)
     {
         throw PSTraceSource.NewArgumentNullException("destinationPath");
     }
     if (destinationProperty == null)
     {
         throw PSTraceSource.NewArgumentNullException("destinationProperty");
     }
     ProviderInfo info = null;
     CmdletProvider providerInstance = null;
     CmdletProviderContext context2 = new CmdletProviderContext(context);
     context2.SetFilters(new Collection<string>(), new Collection<string>(), null);
     Collection<string> targetObject = this.Globber.GetGlobbedProviderPathsFromMonadPath(destinationPath, false, context2, out info, out providerInstance);
     if (targetObject.Count > 1)
     {
         ArgumentException exception = PSTraceSource.NewArgumentException("destinationPath", "SessionStateStrings", "MovePropertyDestinationResolveToSingle", new object[0]);
         context.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, targetObject));
     }
     else
     {
         foreach (string str in sourcePaths)
         {
             if (str == null)
             {
                 throw PSTraceSource.NewArgumentNullException("sourcePaths");
             }
             foreach (string str2 in this.Globber.GetGlobbedProviderPathsFromMonadPath(str, false, context, out info, out providerInstance))
             {
                 this.MoveProperty(providerInstance, str2, sourceProperty, targetObject[0], destinationProperty, context);
             }
         }
     }
 }
        private void SetSecurityDescriptor(
            CmdletProvider providerInstance,
            string path,
            ObjectSecurity securityDescriptor,
            CmdletProviderContext context)
        {
            // All parameters should have been validated by caller
            Diagnostics.Assert(
                providerInstance != null,
                "Caller should validate providerInstance before calling this method");

            Diagnostics.Assert(
                path != null,
                "Caller should validate path before calling this method");

            Diagnostics.Assert(
                securityDescriptor != null,
                "Caller should validate securityDescriptor before calling this method");

            Diagnostics.Assert(
                context != null,
                "Caller should validate context before calling this method");

            // This just verifies that the provider supports the interface.

            GetPermissionProviderInstance(providerInstance);

            try
            {
                providerInstance.SetSecurityDescriptor(path, securityDescriptor, context);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (PrivilegeNotHeldException e)
            {
                //
                // thrown if one tries to set SACL and does not have
                // SeSecurityPrivilege
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
            }
            catch (UnauthorizedAccessException e)
            {
                //
                // thrown if
                // -- owner or pri. group are invalid OR
                // -- marta returns ERROR_ACCESS_DENIED
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
            }
            catch (NotSupportedException e)
            {
                //
                // thrown if path points to an item that does not
                // support access control.
                //
                // for example, FAT or FAT32 file in case of file system provider
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path));
            }
            catch (SystemException e)
            {
                //
                // thrown if the CLR gets back unexpected error
                // from OS security or marta
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path));
            }
            catch (Exception e) // Catch-all OK, 3rd party callout.
            {
                throw NewProviderInvocationException(
                          "SetSecurityDescriptorProviderException",
                          SessionStateStrings.SetSecurityDescriptorProviderException,
                          providerInstance.ProviderInfo,
                          path,
                          e);
            }
        }
        } // SetSecurityDescriptor

        private void SetSecurityDescriptor(
            CmdletProvider providerInstance,
            string path,
            ObjectSecurity securityDescriptor,
            CmdletProviderContext context)
        {
            // All parameters should have been validated by caller
            Diagnostics.Assert(
                providerInstance != null,
                "Caller should validate providerInstance before calling this method");

            Diagnostics.Assert(
                path != null,
                "Caller should validate path before calling this method");

            Diagnostics.Assert(
                securityDescriptor != null,
                "Caller should validate securityDescriptor before calling this method");

            Diagnostics.Assert(
                context != null,
                "Caller should validate context before calling this method");

            // This just verifies that the provider supports the interface.

            GetPermissionProviderInstance(providerInstance);

            try
            {
                providerInstance.SetSecurityDescriptor(path, securityDescriptor, context);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (PrivilegeNotHeldException e)
            {
                //
                // thrown if one tries to set SACL and does not have
                // SeSecurityPrivilege
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
            }
            catch (UnauthorizedAccessException e)
            {
                //
                // thrown if
                // -- owner or pri. group are invalid OR
                // -- marta returns ERROR_ACCESS_DENIED
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
            }
            catch (NotSupportedException e)
            {
                //
                // thrown if path points to an item that does not
                // support access control.
                // 
                // for example, FAT or FAT32 file in case of file system provider
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path));
            }
            catch (SystemException e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                //
                // thrown if the CLR gets back unexpected error
                // from OS security or marta
                //
                context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path));
            }
            catch (Exception e) // Catch-all OK, 3rd party callout.
            {
                CommandProcessorBase.CheckForSevereException(e);
                throw NewProviderInvocationException(
                    "SetSecurityDescriptorProviderException",
                    SessionStateStrings.SetSecurityDescriptorProviderException,
                    providerInstance.ProviderInfo,
                    path,
                    e);
            }
        } // SetSecurityDescriptor