示例#1
0
 internal CmdletProviderContext(CmdletProviderContext contextToCopyFrom)
 {
     this.credentials = PSCredential.Empty;
     this._origin = CommandOrigin.Internal;
     this.accumulatedObjects = new Collection<PSObject>();
     this.accumulatedErrorObjects = new Collection<ErrorRecord>();
     this.stopReferrals = new Collection<CmdletProviderContext>();
     if (contextToCopyFrom == null)
     {
         throw PSTraceSource.NewArgumentNullException("contextToCopyFrom");
     }
     this.executionContext = contextToCopyFrom.ExecutionContext;
     this.command = contextToCopyFrom.command;
     if (contextToCopyFrom.Credential != null)
     {
         this.credentials = contextToCopyFrom.Credential;
     }
     this.drive = contextToCopyFrom.Drive;
     this.force = (bool) contextToCopyFrom.Force;
     this.CopyFilters(contextToCopyFrom);
     this.suppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion;
     this.dynamicParameters = contextToCopyFrom.DynamicParameters;
     this._origin = contextToCopyFrom._origin;
     this.stopping = contextToCopyFrom.Stopping;
     contextToCopyFrom.StopReferrals.Add(this);
     this.copiedContext = contextToCopyFrom;
 }
示例#2
0
 internal MamlCommandHelpInfo GetProviderSpecificHelpInfo(string helpItemName)
 {
     ProviderInfo info = null;
     PSDriveInfo drive = null;
     string str = null;
     CmdletProviderContext context = new CmdletProviderContext(this._executionContext);
     try
     {
         string str2 = this._requestedPath;
         if (string.IsNullOrEmpty(this._requestedPath))
         {
             str2 = this._pathIntrinsics.CurrentLocation.Path;
         }
         str = this._executionContext.LocationGlobber.GetProviderPath(str2, context, out info, out drive);
     }
     catch (ArgumentNullException)
     {
     }
     catch (ProviderNotFoundException)
     {
     }
     catch (DriveNotFoundException)
     {
     }
     catch (ProviderInvocationException)
     {
     }
     catch (NotSupportedException)
     {
     }
     catch (InvalidOperationException)
     {
     }
     catch (ItemNotFoundException)
     {
     }
     if (info == null)
     {
         return null;
     }
     CmdletProvider provider = info.CreateInstance();
     ICmdletProviderSupportsHelp help = provider as ICmdletProviderSupportsHelp;
     if (help == null)
     {
         return null;
     }
     if (str == null)
     {
         throw new ItemNotFoundException(this._requestedPath, "PathNotFound", SessionStateStrings.PathNotFound);
     }
     provider.Start(info, context);
     string path = str;
     string helpMaml = help.GetHelpMaml(helpItemName, path);
     if (string.IsNullOrEmpty(helpMaml))
     {
         return null;
     }
     return MamlCommandHelpInfo.Load(InternalDeserializer.LoadUnsafeXmlDocument(helpMaml, false, null).DocumentElement, HelpCategory.Provider);
 }
示例#3
0
 internal PSDriveInfo NewDrive(PSDriveInfo drive, CmdletProviderContext context)
 {
     base.Context = context;
     if (((drive.Credential != null) && (drive.Credential != PSCredential.Empty)) && !CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Credentials, base.ProviderInfo))
     {
         throw PSTraceSource.NewNotSupportedException("SessionStateStrings", "NewDriveCredentials_NotSupported", new object[0]);
     }
     return this.NewDrive(drive);
 }
示例#4
0
 internal void CopyProperty(string sourcePath, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext)
 {
     this.Context = cmdletProviderContext;
     IDynamicPropertyCmdletProvider provider = this as IDynamicPropertyCmdletProvider;
     if (provider == null)
     {
         throw PSTraceSource.NewNotSupportedException("SessionStateStrings", "IDynamicPropertyCmdletProvider_NotSupported", new object[0]);
     }
     provider.CopyProperty(sourcePath, sourceProperty, destinationPath, destinationProperty);
 }
示例#5
0
 internal object ClearPropertyDynamicParameters(string path, Collection<string> providerSpecificPickList, CmdletProviderContext cmdletProviderContext)
 {
     this.Context = cmdletProviderContext;
     IPropertyCmdletProvider provider = this as IPropertyCmdletProvider;
     if (provider == null)
     {
         return null;
     }
     return provider.ClearPropertyDynamicParameters(path, providerSpecificPickList);
 }
示例#6
0
 internal void ClearProperty(string path, Collection<string> propertyName, CmdletProviderContext cmdletProviderContext)
 {
     this.Context = cmdletProviderContext;
     IPropertyCmdletProvider provider = this as IPropertyCmdletProvider;
     if (provider == null)
     {
         throw PSTraceSource.NewNotSupportedException("SessionStateStrings", "IPropertyCmdletProvider_NotSupported", new object[0]);
     }
     provider.ClearProperty(path, propertyName);
 }
示例#7
0
 internal void ClearContent(string path, CmdletProviderContext cmdletProviderContext)
 {
     this.Context = cmdletProviderContext;
     IContentCmdletProvider provider = this as IContentCmdletProvider;
     if (provider == null)
     {
         throw PSTraceSource.NewNotSupportedException("SessionStateStrings", "IContentCmdletProvider_NotSupported", new object[0]);
     }
     provider.ClearContent(path);
 }
示例#8
0
 internal object ClearContentDynamicParameters(string path, CmdletProviderContext cmdletProviderContext)
 {
     this.Context = cmdletProviderContext;
     IContentCmdletProvider provider = this as IContentCmdletProvider;
     if (provider == null)
     {
         return null;
     }
     return provider.ClearContentDynamicParameters(path);
 }
示例#9
0
		internal override object GetDynamicParameters(CmdletProviderContext context)
		{
			if (!(this.Path != null & (int)this.Path.Length > 0))
			{
				return base.InvokeProvider.Property.CopyPropertyDynamicParameters(".", this.property, this.Destination, this.property, context);
			}
			else
			{
				return base.InvokeProvider.Property.CopyPropertyDynamicParameters(this.Path[0], this.property, this.Destination, this.property, context);
			}
		}
示例#10
0
		internal override object GetDynamicParameters(CmdletProviderContext context)
		{
			if (this.Path == null)
			{
				return base.InvokeProvider.Property.RenamePropertyDynamicParameters(".", this.Name, this.NewName, context);
			}
			else
			{
				return base.InvokeProvider.Property.RenamePropertyDynamicParameters(this.Path, this.Name, this.NewName, context);
			}
		}
示例#11
0
		internal override object GetDynamicParameters(CmdletProviderContext context)
		{
			if (base.Path == null || (int)base.Path.Length <= 0)
			{
				return base.InvokeProvider.Content.GetContentReaderDynamicParameters(".", context);
			}
			else
			{
				return base.InvokeProvider.Content.GetContentReaderDynamicParameters(base.Path[0], context);
			}
		}
示例#12
0
		internal override object GetDynamicParameters(CmdletProviderContext context)
		{
			if (this.Path == null || (int)this.Path.Length <= 0)
			{
				return base.InvokeProvider.Property.GetPropertyDynamicParameters(".", SessionStateUtilities.ConvertArrayToCollection<string>(this.property), context);
			}
			else
			{
				return base.InvokeProvider.Property.GetPropertyDynamicParameters(this.Path[0], SessionStateUtilities.ConvertArrayToCollection<string>(this.property), context);
			}
		}
示例#13
0
		internal override object GetDynamicParameters(CmdletProviderContext context)
		{
			Collection<string> strs = new Collection<string>();
			strs.Add(this.property);
			if (this.Path == null || (int)this.Path.Length <= 0)
			{
				return base.InvokeProvider.Property.ClearPropertyDynamicParameters(".", strs, context);
			}
			else
			{
				return base.InvokeProvider.Property.ClearPropertyDynamicParameters(this.Path[0], strs, context);
			}
		}
示例#14
0
		private string[] GetAcceptedPaths(string[] unfilteredPaths, CmdletProviderContext currentContext)
		{
			Collection<PathInfo> pathInfos = base.ResolvePaths(unfilteredPaths, true, false, currentContext);
			ArrayList arrayLists = new ArrayList();
			foreach (PathInfo pathInfo in pathInfos)
			{
				if (!this.CallShouldProcess(pathInfo.Path))
				{
					continue;
				}
				arrayLists.Add(pathInfo.Path);
			}
			return (string[])arrayLists.ToArray(typeof(string));
		}
示例#15
0
        /// <summary>
        /// Gets the path to the parent object for the given object
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the object to get the parent path from
        /// </param>
        /// 
        /// <param name="root">
        /// The root of the drive.
        /// </param>
        /// 
        /// <returns>
        /// The path to the parent object
        /// </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 GetParentPath(string path, string root)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);

            string result = GetParentPath(path, root, context);

            context.ThrowFirstErrorOrDoNothing();

            return result;
        } //GetParentPath
示例#16
0
 private PathInfo ResolvePath(string pathToResolve, bool isLiteralPath, bool allowNonexistingPaths, PSCmdlet cmdlet)
 {
     CmdletProviderContext context = new CmdletProviderContext(cmdlet) {
         SuppressWildcardExpansion = isLiteralPath
     };
     Collection<PathInfo> targetObject = new Collection<PathInfo>();
     try
     {
         foreach (PathInfo info in cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath(pathToResolve, context))
         {
             targetObject.Add(info);
         }
     }
     catch (PSNotSupportedException exception)
     {
         cmdlet.ThrowTerminatingError(new ErrorRecord(exception.ErrorRecord, exception));
     }
     catch (DriveNotFoundException exception2)
     {
         cmdlet.ThrowTerminatingError(new ErrorRecord(exception2.ErrorRecord, exception2));
     }
     catch (ProviderNotFoundException exception3)
     {
         cmdlet.ThrowTerminatingError(new ErrorRecord(exception3.ErrorRecord, exception3));
     }
     catch (ItemNotFoundException exception4)
     {
         if (allowNonexistingPaths)
         {
             ProviderInfo provider = null;
             PSDriveInfo drive = null;
             string path = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(pathToResolve, context, out provider, out drive);
             PathInfo item = new PathInfo(drive, provider, path, cmdlet.SessionState);
             targetObject.Add(item);
         }
         else
         {
             cmdlet.ThrowTerminatingError(new ErrorRecord(exception4.ErrorRecord, exception4));
         }
     }
     if (targetObject.Count == 1)
     {
         return targetObject[0];
     }
     Exception exception5 = PSTraceSource.NewNotSupportedException();
     cmdlet.ThrowTerminatingError(new ErrorRecord(exception5, "NotSupported", ErrorCategory.NotImplemented, targetObject));
     return null;
 }
示例#17
0
		internal override object GetDynamicParameters(CmdletProviderContext context)
		{
			string name = null;
			if (this.Name != null && (int)this.Name.Length > 0)
			{
				name = this.Name[0];
			}
			if (this.Path == null || (int)this.Path.Length <= 0)
			{
				return base.InvokeProvider.Property.RemovePropertyDynamicParameters(".", name, context);
			}
			else
			{
				return base.InvokeProvider.Property.RemovePropertyDynamicParameters(this.Path[0], name, context);
			}
		}
示例#18
0
		internal override object GetDynamicParameters(CmdletProviderContext context)
		{
			string empty = string.Empty;
			if (this.Name != null && (int)this.Name.Length > 0)
			{
				empty = this.Name[0];
			}
			if (this.Path == null || (int)this.Path.Length <= 0)
			{
				return base.InvokeProvider.Property.MovePropertyDynamicParameters(".", empty, this.Destination, empty, context);
			}
			else
			{
				return base.InvokeProvider.Property.MovePropertyDynamicParameters(this.Path[0], empty, this.Destination, empty, context);
			}
		}
示例#19
0
        /// <summary>
        /// Determines if the monad virtual namespace path exists.
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the object to determine if it exists.
        /// </param>
        /// 
        /// <param name="force">
        /// Passed on to providers to force operations.
        /// </param>
        /// 
        /// <param name="literalPath">
        /// If true, globbing is not done on paths.
        /// </param>
        /// 
        /// <returns>
        /// true if the object specified by path exists, false otherwise.
        /// </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>
        /// 
        internal bool ItemExists(string path, bool force, bool literalPath)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
            context.Force = force;
            context.SuppressWildcardExpansion = literalPath;

            bool result = ItemExists(path, context);

            context.ThrowFirstErrorOrDoNothing();

            return result;
        } // ItemExists
示例#20
0
        /// <summary>
        /// Internal wrapper for the NewDrive protected method. It is called instead
        /// of the protected method that is overridden by derived classes so that the
        /// context of the command can be set.
        /// </summary>
        /// 
        /// <param name="drive">
        /// The PSDriveInfo object the represents the drive to be mounted.
        /// </param>
        /// 
        /// <param name="context">
        /// The context under which this method is being called.
        /// </param>
        /// 
        /// <returns>
        /// The drive that was returned from the protected NewDrive method.
        /// </returns>
        /// 
        internal PSDriveInfo NewDrive(PSDriveInfo drive, CmdletProviderContext context)
        {
            Context = context;

            // Make sure the provider supports credentials if they were passed 
            // in the drive.

            if (drive.Credential != null &&
                drive.Credential != PSCredential.Empty &&
                !CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Credentials, ProviderInfo))
            {
                throw PSTraceSource.NewNotSupportedException(
                    SessionStateStrings.NewDriveCredentials_NotSupported);
            }

            return NewDrive(drive);
        } // NewDrive
示例#21
0
        /// <summary>
        /// Gets the content reader for the specified item.
        /// </summary>
        /// 
        /// <param name="paths">
        /// The path(s) to the item(s) to get the content reader for.
        /// </param>
        /// 
        /// <param name="force">
        /// Passed on to providers to force operations.
        /// </param>
        /// 
        /// <param name="literalPath">
        /// If true, globbing is not done on paths.
        /// </param>
        /// 
        /// <returns>
        /// The content readers for all items that the path resolves to.
        /// </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>
        /// 
        internal Collection<IContentReader> GetContentReader(string[] paths, bool force, bool literalPath)
        {
            if (paths == null)
            {
                throw PSTraceSource.NewArgumentNullException("paths");
            }

            CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
            context.Force = force;
            context.SuppressWildcardExpansion = literalPath;

            Collection<IContentReader> results = GetContentReader(paths, context);

            context.ThrowFirstErrorOrDoNothing();

            return results;
        } // GetContentReader
示例#22
0
        /// <summary>
        /// Called by the base class before the streams are open for the path.
        /// This override clears the content from the item. 
        /// </summary>
        /// 
        /// <param name="paths">
        /// The path to the items that will be opened for writing content.
        /// </param>
        /// 
        internal override void BeforeOpenStreams(string[] paths)
        {
            if (paths == null ||
                (paths != null && paths.Length == 0))
            {
                throw PSTraceSource.NewArgumentNullException("paths");
            }

            CmdletProviderContext context = new CmdletProviderContext(GetCurrentContext());

            foreach (string path in paths)
            {
                try
                {
                    InvokeProvider.Content.Clear(path, context);
                    context.ThrowFirstErrorOrDoNothing(true);
                }
                catch (PSNotSupportedException)
                {
                    // If the provider doesn't support clear, that is fine. Continue
                    // on with the setting of the content.
                    continue;
                }
                catch (DriveNotFoundException driveNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            driveNotFound.ErrorRecord,
                            driveNotFound));
                    continue;
                }
                catch (ProviderNotFoundException providerNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            providerNotFound.ErrorRecord,
                            providerNotFound));
                    continue;
                }
                catch (ItemNotFoundException)
                {
                    //If the item is not found then there is nothing to clear so ignore this exception.
                    continue;
                }
            }
        } // BeforeOpenStreams
示例#23
0
 /// <summary>
 /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets
 /// that require dynamic parameters should override this method and return the
 /// dynamic parameter object.
 /// </summary>
 /// 
 /// <param name="context">
 /// The context under which the command is running.
 /// </param>
 /// 
 /// <returns>
 /// An object representing the dynamic parameters for the cmdlet or null if there
 /// are none.
 /// </returns>
 /// 
 internal override object GetDynamicParameters(CmdletProviderContext context)
 {
     if (Path != null && Path.Length > 0)
     {
         return InvokeProvider.Property.CopyPropertyDynamicParameters(
             Path[0],
             Name,
             Destination,
             Name,
             context);
     }
     return InvokeProvider.Property.CopyPropertyDynamicParameters(
         ".",
         Name,
         Destination,
         Name,
         context);
 } // GetDynamicParameters
示例#24
0
		internal List<ContentCommandBase.ContentHolder> GetContentWriters(string[] writerPaths, CmdletProviderContext currentCommandContext)
		{
			Collection<PathInfo> pathInfos = base.ResolvePaths(writerPaths, true, false, currentCommandContext);
			List<ContentCommandBase.ContentHolder> contentHolders = new List<ContentCommandBase.ContentHolder>();
			foreach (PathInfo pathInfo in pathInfos)
			{
				Collection<IContentWriter> writer = null;
				try
				{
					writer = base.InvokeProvider.Content.GetWriter(pathInfo.Path, currentCommandContext);
				}
				catch (PSNotSupportedException pSNotSupportedException1)
				{
					PSNotSupportedException pSNotSupportedException = pSNotSupportedException1;
					base.WriteError(new ErrorRecord(pSNotSupportedException.ErrorRecord, pSNotSupportedException));
					continue;
				}
				catch (DriveNotFoundException driveNotFoundException1)
				{
					DriveNotFoundException driveNotFoundException = driveNotFoundException1;
					base.WriteError(new ErrorRecord(driveNotFoundException.ErrorRecord, driveNotFoundException));
					continue;
				}
				catch (ProviderNotFoundException providerNotFoundException1)
				{
					ProviderNotFoundException providerNotFoundException = providerNotFoundException1;
					base.WriteError(new ErrorRecord(providerNotFoundException.ErrorRecord, providerNotFoundException));
					continue;
				}
				catch (ItemNotFoundException itemNotFoundException1)
				{
					ItemNotFoundException itemNotFoundException = itemNotFoundException1;
					base.WriteError(new ErrorRecord(itemNotFoundException.ErrorRecord, itemNotFoundException));
					continue;
				}
				if (writer == null || writer.Count <= 0 || writer.Count != 1 || writer[0] == null)
				{
					continue;
				}
				ContentCommandBase.ContentHolder contentHolder = new ContentCommandBase.ContentHolder(pathInfo, null, writer[0]);
				contentHolders.Add(contentHolder);
			}
			return contentHolders;
		}
示例#25
0
        /// <summary>
        /// Gets the specified properties from the specified item.
        /// </summary>
        /// 
        /// <param name="paths">
        /// The path(s) to the item(s) to get the properties from.
        /// </param>
        /// 
        /// <param name="providerSpecificPickList">
        /// A list of the properties that the provider should return.
        /// </param>
        /// 
        /// <param name="literalPath">
        /// If true, globbing is not done on paths.
        /// </param>
        /// 
        /// <returns>
        /// A property table container the properties and their values.
        /// </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>
        /// 
        internal Collection<PSObject> GetProperty(
            string[] paths,
            Collection<string> providerSpecificPickList,
            bool literalPath)
        {
            if (paths == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
            context.SuppressWildcardExpansion = literalPath;

            GetProperty(paths, providerSpecificPickList, context);

            context.ThrowFirstErrorOrDoNothing();

            Collection<PSObject> results = context.GetAccumulatedObjects();

            return results;
        } // GetProperties
示例#26
0
        /// <summary>
        /// Gets the specified object
        /// </summary>
        /// 
        /// <param name="paths">
        /// The path(s) to the object(s). They can be either a relative (most common)
        /// or absolute path.
        /// </param>
        /// 
        /// <param name="force">
        /// Passed on to providers to force operations.
        /// </param>
        /// 
        /// <param name="literalPath">
        /// If true, globbing is not done on paths.
        /// </param>
        /// 
        /// <returns>
        /// The item at the specified path.
        /// </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>
        /// 
        internal Collection<PSObject> GetItem(string[] paths, bool force, bool literalPath)
        {
            if (paths == null)
            {
                throw PSTraceSource.NewArgumentNullException("paths");
            }

            CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
            context.Force = force;
            context.SuppressWildcardExpansion = literalPath;

            GetItem(paths, context);

            context.ThrowFirstErrorOrDoNothing();

            // Since there was not errors return the accumulated objects

            Collection<PSObject> results = context.GetAccumulatedObjects();

            return results;
        } // GetItem
示例#27
0
		internal override void BeforeOpenStreams(string[] paths)
		{
			if (paths == null || paths != null && (int)paths.Length == 0)
			{
				throw PSTraceSource.NewArgumentNullException("paths");
			}
			else
			{
				CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(base.GetCurrentContext());
				string[] strArrays = paths;
				for (int i = 0; i < (int)strArrays.Length; i++)
				{
					string str = strArrays[i];
					try
					{
						base.InvokeProvider.Content.Clear(str, cmdletProviderContext);
						cmdletProviderContext.ThrowFirstErrorOrDoNothing(true);
					}
					catch (PSNotSupportedException pSNotSupportedException)
					{
					}
					catch (DriveNotFoundException driveNotFoundException1)
					{
						DriveNotFoundException driveNotFoundException = driveNotFoundException1;
						base.WriteError(new ErrorRecord(driveNotFoundException.ErrorRecord, driveNotFoundException));
					}
					catch (ProviderNotFoundException providerNotFoundException1)
					{
						ProviderNotFoundException providerNotFoundException = providerNotFoundException1;
						base.WriteError(new ErrorRecord(providerNotFoundException.ErrorRecord, providerNotFoundException));
					}
					catch (ItemNotFoundException itemNotFoundException)
					{
					}
				}
				return;
			}
		}
 internal object GetChildItemsDynamicParameters(string path, bool recurse, CmdletProviderContext context)
 {
     return(this.sessionState.GetChildItemsDynamicParameters(path, recurse, context));
 }
示例#29
0
        /// <summary>
        /// Gets the IContentReaders for the current path(s)
        /// </summary>
        /// 
        /// <returns>
        /// An array of IContentReaders for the current path(s)
        /// </returns>
        /// 
        internal List<ContentHolder> GetContentReaders(
            string[] readerPaths,
            CmdletProviderContext currentCommandContext)
        {
            // Resolve all the paths into PathInfo objects

            Collection<PathInfo> pathInfos = ResolvePaths(readerPaths, false, true, currentCommandContext);

            // Create the results array

            List<ContentHolder> results = new List<ContentHolder>();

            foreach (PathInfo pathInfo in pathInfos)
            {
                // For each path, get the content writer

                Collection<IContentReader> readers = null;

                try
                {
                    string pathToProcess = WildcardPattern.Escape(pathInfo.Path);

                    if (currentCommandContext.SuppressWildcardExpansion)
                    {
                        pathToProcess = pathInfo.Path;
                    }

                    readers =
                        InvokeProvider.Content.GetReader(pathToProcess, currentCommandContext);
                }
                catch (PSNotSupportedException notSupported)
                {
                    WriteError(
                        new ErrorRecord(
                            notSupported.ErrorRecord,
                            notSupported));
                    continue;
                }
                catch (DriveNotFoundException driveNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            driveNotFound.ErrorRecord,
                            driveNotFound));
                    continue;
                }
                catch (ProviderNotFoundException providerNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            providerNotFound.ErrorRecord,
                            providerNotFound));
                    continue;
                }
                catch (ItemNotFoundException pathNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            pathNotFound.ErrorRecord,
                            pathNotFound));
                    continue;
                }

                if (readers != null && readers.Count > 0)
                {
                    if (readers.Count == 1 && readers[0] != null)
                    {
                        ContentHolder holder =
                            new ContentHolder(pathInfo, readers[0], null);

                        results.Add(holder);
                    }
                }
            } // foreach pathInfo in pathInfos

            return results;
        } // GetContentReaders
 /// <summary>
 /// Changes the current working directory to the path specified.
 /// </summary>
 /// <param name="path">
 /// The path of the new current working directory
 /// </param>
 /// <param name="context">
 /// The context the provider uses when performing the operation.
 /// </param>
 /// <returns>
 /// The PathInfo object representing the path of the location
 /// that was set.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="path"/> is null.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// If <paramref name="path"/> does not exist, is not a container, or
 /// resolved to multiple containers.
 /// </exception>
 /// <exception cref="ProviderNotFoundException">
 /// If <paramref name="path"/> refers to a provider that does not exist.
 /// </exception>
 /// <exception cref="DriveNotFoundException">
 /// If <paramref name="path"/> refers to a drive that does not exist.
 /// </exception>
 /// <exception cref="ProviderInvocationException">
 /// If the provider associated with <paramref name="path"/> threw an
 /// exception.
 /// </exception>
 /// <exception cref="ItemNotFoundException">
 /// If the <paramref name="path"/> could not be resolved.
 /// </exception>
 internal PathInfo SetLocation(string path, CmdletProviderContext context)
 {
     return(SetLocation(path, context, literalPath: false));
 }
 internal void GetNames(string path, ReturnContainers returnContainers, bool recurse, CmdletProviderContext context)
 {
     this.sessionState.GetChildNames(path, returnContainers, recurse, context);
 }
示例#32
0
 internal object RemovePropertyDynamicParameters(string path, string propertyName, CmdletProviderContext context)
 {
     return(this.sessionState.RemovePropertyDynamicParameters(path, propertyName, context));
 }
示例#33
0
 internal object RenamePropertyDynamicParameters(string path, string sourceProperty, string destinationProperty, CmdletProviderContext context)
 {
     return(this.sessionState.RenamePropertyDynamicParameters(path, sourceProperty, destinationProperty, context));
 }
示例#34
0
 internal string ParseChildName(string path, CmdletProviderContext context, bool useDefaultProvider)
 {
     return(this.sessionState.GetChildName(path, context, useDefaultProvider));
 }
示例#35
0
 internal object NewPropertyDynamicParameters(string path, string propertyName, string type, object value, CmdletProviderContext context)
 {
     return(this.sessionState.NewPropertyDynamicParameters(path, propertyName, type, value, context));
 }
示例#36
0
 internal string NormalizeRelativePath(string path, string basePath, CmdletProviderContext context)
 {
     return(this.sessionState.NormalizeRelativePath(path, basePath, context));
 }
示例#37
0
 internal string ParseChildName(string path, CmdletProviderContext context)
 {
     return(this.sessionState.GetChildName(path, context, false));
 }
示例#38
0
 internal bool IsValid(string path, CmdletProviderContext context)
 {
     return(this.sessionState.IsValidPath(path, context));
 }
示例#39
0
        /// <summary>
        /// Removes the current scope from the scope tree and
        /// changes the current scope to the parent scope.
        /// </summary>
        /// <param name="scope">
        /// The scope to cleanup and remove.
        /// </param>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// The global scope cannot be removed.
        /// </exception>
        internal void RemoveScope(SessionStateScope scope)
        {
            Diagnostics.Assert(
                _currentScope != null,
                "The currentScope should always be set.");

            if (scope == GlobalScope)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        StringLiterals.Global,
                        SessionStateCategory.Scope,
                        "GlobalScopeCannotRemove",
                        SessionStateStrings.GlobalScopeCannotRemove);

                throw e;
            }

            // Give the provider a chance to cleanup the drive data associated
            // with drives in this scope

            foreach (PSDriveInfo drive in scope.Drives)
            {
                if (drive == null)
                {
                    continue;
                }

                CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);

                // Call CanRemoveDrive to give the provider a chance to cleanup
                // but ignore the return value and exceptions

                try
                {
                    CanRemoveDrive(drive, context);
                }
                catch (LoopFlowException)
                {
                    throw;
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (ActionPreferenceStopException)
                {
                    throw;
                }
                catch (Exception) // Catch-all OK, 3rd party callout.
                {
                    // Ignore all exceptions from the provider as we are
                    // going to force the removal anyway
                }
            }

            scope.RemoveAllDrives();

            // If the scope being removed is the current scope,
            // then it must be removed from the tree.

            if (scope == _currentScope && _currentScope.Parent != null)
            {
                _currentScope = _currentScope.Parent;
            }

            scope.Parent = null;
        }
示例#40
0
 internal string GetUnresolvedProviderPathFromPSPath(string path, CmdletProviderContext context, out ProviderInfo provider, out PSDriveInfo drive)
 {
     return(this.PathResolver.GetProviderPath(path, context, out provider, out drive));
 }
示例#41
0
        /// <summary>
        /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets
        /// that require dynamic parameters should override this method and return the
        /// dynamic parameter object.
        /// </summary>
        /// 
        /// <param name="context">
        /// The context under which the command is running.
        /// </param>
        /// 
        /// <returns>
        /// An object representing the dynamic parameters for the cmdlet or null if there
        /// are none.
        /// </returns>
        /// 
        internal override object GetDynamicParameters(CmdletProviderContext context)
        {
            string propertyName = String.Empty;
            if (Name != null && Name.Length > 0)
            {
                propertyName = Name[0];
            }

            if (Path != null && Path.Length > 0)
            {
                return InvokeProvider.Property.MovePropertyDynamicParameters(Path[0], propertyName, Destination, propertyName, context);
            }
            return InvokeProvider.Property.MovePropertyDynamicParameters(
                ".",
                propertyName,
                Destination,
                propertyName,
                context);
        } // GetDynamicParameters
示例#42
0
 internal string ParseParent(string path, string root, CmdletProviderContext context)
 {
     return(this.sessionState.GetParentPath(path, root, context, false));
 }
示例#43
0
        } // SetLocation

        /// <summary>
        /// Determines if the specified path is the current working directory
        /// or a parent of the current working directory.
        /// </summary>
        ///
        /// <param name="path">
        /// A monad namespace absolute or relative path.
        /// </param>
        ///
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        ///
        /// <returns>
        /// true, if the path is the current working directory or a parent of the current
        /// working directory. false, otherwise.
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> 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 specified by <paramref name="providerId"/> threw an
        /// exception when its GetParentPath or MakePath was called while
        /// processing the <paramref name="path"/>.
        /// </exception>
        ///
        internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext context)
        {
            bool result = false;

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

            PSDriveInfo  drive    = null;
            ProviderInfo provider = null;

            string providerSpecificPath =
                Globber.GetProviderPath(
                    path,
                    context,
                    out provider,
                    out drive);

            if (drive != null)
            {
                s_tracer.WriteLine("Tracing drive");
                drive.Trace();
            }

            Dbg.Diagnostics.Assert(
                providerSpecificPath != null,
                "There should always be a way to generate a provider path for a " +
                "given path");

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

            // Check to see if the path that was specified is within the current
            // working drive

            if (drive == CurrentDrive)
            {
                // The path needs to be normalized to get rid of relative path tokens
                // so they don't interfere with our path comparisons below

                CmdletProviderContext normalizePathContext
                    = new CmdletProviderContext(context);

                try
                {
                    providerSpecificPath = NormalizeRelativePath(path, null, normalizePathContext);
                }
                catch (NotSupportedException)
                {
                    // Since the provider does not support normalizing the path, just
                    // use the path we currently have.
                }
                catch (LoopFlowException)
                {
                    throw;
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (ActionPreferenceStopException)
                {
                    throw;
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                if (normalizePathContext.HasErrors())
                {
                    normalizePathContext.ThrowFirstErrorOrDoNothing();
                }

                s_tracer.WriteLine("Provider path = {0}", providerSpecificPath);

                // Get the current working directory provider specific path

                PSDriveInfo  currentWorkingDrive  = null;
                ProviderInfo currentDriveProvider = null;

                string currentWorkingPath =
                    Globber.GetProviderPath(
                        ".",
                        context,
                        out currentDriveProvider,
                        out currentWorkingDrive);

                Dbg.Diagnostics.Assert(
                    currentWorkingDrive == CurrentDrive,
                    "The current working drive should be the CurrentDrive.");

                s_tracer.WriteLine(
                    "Current working path = {0}",
                    currentWorkingPath);

                // See if the path is the current working directory or a parent
                // of the current working directory

                s_tracer.WriteLine(
                    "Comparing {0} to {1}",
                    providerSpecificPath,
                    currentWorkingPath);

                if (String.Compare(providerSpecificPath, currentWorkingPath, StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    // The path is the current working directory so
                    // return true

                    s_tracer.WriteLine("The path is the current working directory");

                    result = true;
                }
                else
                {
                    // Check to see if the specified path is a parent
                    // of the current working directory

                    string lockedDirectory = currentWorkingPath;

                    while (lockedDirectory.Length > 0)
                    {
                        // We need to allow the provider to go as far up the tree
                        // as it can even if that means it has to traverse higher
                        // than the mount point for this drive. That is
                        // why we are passing the empty string as the root here.

                        lockedDirectory =
                            GetParentPath(
                                drive.Provider,
                                lockedDirectory,
                                String.Empty,
                                context);

                        s_tracer.WriteLine(
                            "Comparing {0} to {1}",
                            lockedDirectory,
                            providerSpecificPath);

                        if (String.Compare(lockedDirectory, providerSpecificPath, StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            // The path is a parent of the current working
                            // directory

                            s_tracer.WriteLine(
                                "The path is a parent of the current working directory: {0}",
                                lockedDirectory);

                            result = true;
                            break;
                        }
                    }
                }
            }
            else
            {
                s_tracer.WriteLine("Drives are not the same");
            }

            return(result);
        } // IsCurrentLocationOrAncestor
示例#44
0
 internal string ParseParent(string path, string root, CmdletProviderContext context, bool useDefaultProvider)
 {
     return(this.sessionState.GetParentPath(path, root, context, useDefaultProvider));
 }
示例#45
0
 internal void Remove(string path, string propertyName, CmdletProviderContext context)
 {
     this.sessionState.RemoveProperty(new string[] { path }, propertyName, context);
 }
示例#46
0
 internal PathInfo SetLocation(string path, CmdletProviderContext context)
 {
     return(this.sessionState.SetLocation(path, context));
 }
示例#47
0
 internal void Rename(string path, string sourceProperty, string destinationProperty, CmdletProviderContext context)
 {
     this.sessionState.RenameProperty(new string[] { path }, sourceProperty, destinationProperty, context);
 }
示例#48
0
 internal string Combine(string parent, string child, CmdletProviderContext context)
 {
     return(this.sessionState.MakePath(parent, child, context));
 }
        /// <summary>
        /// Changes the current working directory to the path specified.
        /// </summary>
        /// <param name="path">
        /// The path of the new current working directory.
        /// </param>
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        /// <param name="literalPath">
        /// Indicate if the path is a literal path.
        /// </param>
        /// <returns>
        /// The PathInfo object representing the path of the location
        /// that was set.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="path"/> does not exist, is not a container, or
        /// resolved to multiple containers.
        /// </exception>
        /// <exception cref="ProviderNotFoundException">
        /// If <paramref name="path"/> refers to a provider that does not exist.
        /// </exception>
        /// <exception cref="DriveNotFoundException">
        /// If <paramref name="path"/> refers to a drive that does not exist.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with <paramref name="path"/> threw an
        /// exception.
        /// </exception>
        /// <exception cref="ItemNotFoundException">
        /// If the <paramref name="path"/> could not be resolved.
        /// </exception>
        internal PathInfo SetLocation(string path, CmdletProviderContext context, bool literalPath)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(path));
            }

            PathInfo     current      = CurrentLocation;
            string       originalPath = path;
            string       driveName    = null;
            ProviderInfo provider     = null;
            string       providerId   = null;

            switch (originalPath)
            {
            case string originalPathSwitch when !literalPath && originalPathSwitch.Equals("-", StringComparison.Ordinal):
                if (_setLocationHistory.UndoCount <= 0)
                {
                    throw new InvalidOperationException(SessionStateStrings.LocationUndoStackIsEmpty);
                }

                path = _setLocationHistory.Undo(this.CurrentLocation).Path;
                break;

            case string originalPathSwitch when !literalPath && originalPathSwitch.Equals("+", StringComparison.Ordinal):
                if (_setLocationHistory.RedoCount <= 0)
                {
                    throw new InvalidOperationException(SessionStateStrings.LocationRedoStackIsEmpty);
                }

                path = _setLocationHistory.Redo(this.CurrentLocation).Path;
                break;

            default:
                var pushPathInfo = GetNewPushPathInfo();
                _setLocationHistory.Push(pushPathInfo);
                break;
            }

            PSDriveInfo previousWorkingDrive = CurrentDrive;

            // First check to see if the path is a home path
            if (LocationGlobber.IsHomePath(path))
            {
                path = Globber.GetHomeRelativePath(path);
            }

            if (LocationGlobber.IsProviderDirectPath(path))
            {
                // The path is a provider-direct path so use the current
                // provider and its hidden drive but don't modify the path
                // at all.
                provider     = CurrentLocation.Provider;
                CurrentDrive = provider.HiddenDrive;
            }
            else if (LocationGlobber.IsProviderQualifiedPath(path, out providerId))
            {
                provider     = GetSingleProvider(providerId);
                CurrentDrive = provider.HiddenDrive;
            }
            else
            {
                // See if the path is a relative or absolute
                // path.
                if (Globber.IsAbsolutePath(path, out driveName))
                {
                    // Since the path is an absolute path
                    // we need to change the current working
                    // drive
                    PSDriveInfo newWorkingDrive = GetDrive(driveName);
                    CurrentDrive = newWorkingDrive;

                    // If the path is simply a colon-terminated drive,
                    // not a slash-terminated path to the root of a drive,
                    // set the path to the current working directory of that drive.
                    string colonTerminatedVolume = CurrentDrive.Name + ':';
                    if (CurrentDrive.VolumeSeparatedByColon && (path.Length == colonTerminatedVolume.Length))
                    {
                        path = Path.Combine(colonTerminatedVolume + Path.DirectorySeparatorChar, CurrentDrive.CurrentLocation);
                    }

                    // Now that the current working drive is set,
                    // process the rest of the path as a relative path.
                }
            }

            if (context == null)
            {
                context = new CmdletProviderContext(this.ExecutionContext);
            }

            if (CurrentDrive != null)
            {
                context.Drive = CurrentDrive;
            }

            CmdletProvider providerInstance = null;

            Collection <PathInfo> workingPath = null;

            try
            {
                workingPath =
                    Globber.GetGlobbedMonadPathsFromMonadPath(
                        path,
                        false,
                        context,
                        out providerInstance);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception)
            {
                // Reset the drive to the previous drive and
                // then rethrow the error
                CurrentDrive = previousWorkingDrive;
                throw;
            }

            if (workingPath.Count == 0)
            {
                // Set the current working drive back to the previous
                // one in case it was changed.
                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // We allow globbing the location as long as it only resolves a single container.
            bool foundContainer                     = false;
            bool pathIsContainer                    = false;
            bool pathIsProviderQualifiedPath        = false;
            bool currentPathisProviderQualifiedPath = false;

            for (int index = 0; index < workingPath.Count; ++index)
            {
                CmdletProviderContext normalizePathContext =
                    new CmdletProviderContext(context);

                PathInfo resolvedPath = workingPath[index];
                string   currentPath  = path;
                try
                {
                    string providerName = null;
                    currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName);
                    if (currentPathisProviderQualifiedPath)
                    {
                        // The path should be the provider-qualified path without the provider ID
                        // or ::
                        string providerInternalPath = LocationGlobber.RemoveProviderQualifier(resolvedPath.Path);

                        try
                        {
                            currentPath = NormalizeRelativePath(GetSingleProvider(providerName), providerInternalPath, string.Empty, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception)
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error
                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }
                    else
                    {
                        try
                        {
                            currentPath = NormalizeRelativePath(resolvedPath.Path, CurrentDrive.Root, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception)
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error
                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }

                    // Now see if there was errors while normalizing the path
                    if (normalizePathContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        normalizePathContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                bool isContainer = false;

                CmdletProviderContext itemContainerContext =
                    new CmdletProviderContext(context);
                itemContainerContext.SuppressWildcardExpansion = true;

                try
                {
                    isContainer =
                        IsItemContainer(
                            resolvedPath.Path,
                            itemContainerContext);

                    if (itemContainerContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        itemContainerContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                catch (NotSupportedException)
                {
                    if (currentPath.Length == 0)
                    {
                        // Treat this as a container because providers that only
                        // support the ContainerCmdletProvider interface are really
                        // containers at their root.
                        isContainer = true;
                    }
                }
                finally
                {
                    itemContainerContext.RemoveStopReferral();
                }

                if (isContainer)
                {
                    if (foundContainer)
                    {
                        // The path resolved to more than one container
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        throw
                            PSTraceSource.NewArgumentException(
                                nameof(path),
                                SessionStateStrings.PathResolvedToMultiple,
                                originalPath);
                    }
                    else
                    {
                        // Set the path to use
                        path = currentPath;

                        // Mark it as a container
                        pathIsContainer = true;

                        // Mark whether or not it was provider-qualified
                        pathIsProviderQualifiedPath = currentPathisProviderQualifiedPath;

                        // Mark that we have already found one container. Finding additional
                        // should be an error
                        foundContainer = true;
                    }
                }
            }

            if (pathIsContainer)
            {
                // Remove the root slash since it is implied that the
                // current working directory is relative to the root.
                if (!LocationGlobber.IsProviderDirectPath(path) &&
                    path.StartsWith(StringLiterals.DefaultPathSeparator) &&
                    !pathIsProviderQualifiedPath)
                {
                    path = path.Substring(1);
                }

                s_tracer.WriteLine(
                    "New working path = {0}",
                    path);

                CurrentDrive.CurrentLocation = path;
            }
            else
            {
                // Set the current working drive back to the previous
                // one in case it was changed.
                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        originalPath,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // Now make sure the current drive is set in the provider's
            // current working drive hashtable
            ProvidersCurrentWorkingDrive[CurrentDrive.Provider] =
                CurrentDrive;

            // Set the $PWD variable to the new location
            this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal);

            // If an action has been defined for location changes, invoke it now.
            if (PublicSessionState.InvokeCommand.LocationChangedAction != null)
            {
                var eventArgs = new LocationChangedEventArgs(PublicSessionState, current, CurrentLocation);
                PublicSessionState.InvokeCommand.LocationChangedAction.Invoke(ExecutionContext.CurrentRunspace, eventArgs);
                s_tracer.WriteLine("Invoked LocationChangedAction");
            }

            return(this.CurrentLocation);
        }
示例#50
0
        internal Collection <string> GetResolvedProviderPathFromProviderPath(string path, string providerId, CmdletProviderContext context)
        {
            CmdletProvider providerInstance = null;

            return(this.PathResolver.GetGlobbedProviderPathsFromProviderPath(path, false, providerId, context, out providerInstance));
        }
 internal bool HasChild(string path, CmdletProviderContext context)
 {
     return(this.sessionState.HasChildItems(path, context));
 }
示例#52
0
        internal Collection <PathInfo> GetResolvedPSPathFromPSPath(string path, CmdletProviderContext context)
        {
            CmdletProvider providerInstance = null;

            return(this.PathResolver.GetGlobbedMonadPathsFromMonadPath(path, false, context, out providerInstance));
        }
 internal object GetChildNamesDynamicParameters(string path, CmdletProviderContext context)
 {
     return(this.sessionState.GetChildNamesDynamicParameters(path, context));
 }
示例#54
0
        /// <summary>
        /// Get provider specific help info.
        /// </summary>
        internal MamlCommandHelpInfo GetProviderSpecificHelpInfo(string helpItemName)
        {
            if (InternalTestHooks.BypassOnlineHelpRetrieval)
            {
                // By returning null, we force get-help to return generic help
                // which includes a helpUri that points to the fwlink defined in the cmdlet code.
                return(null);
            }

            // Get the provider.
            ProviderInfo          providerInfo          = null;
            PSDriveInfo           driveInfo             = null;
            string                resolvedProviderPath  = null;
            CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(_executionContext);

            try
            {
                string psPath = _requestedPath;
                if (string.IsNullOrEmpty(_requestedPath))
                {
                    psPath = _pathIntrinsics.CurrentLocation.Path;
                }

                resolvedProviderPath = _executionContext.LocationGlobber.GetProviderPath(
                    psPath,
                    cmdletProviderContext,
                    out providerInfo,
                    out driveInfo);
            }
            // ignore exceptions caused by provider resolution
            catch (ArgumentNullException)
            {
            }
            catch (ProviderNotFoundException)
            {
            }
            catch (DriveNotFoundException)
            {
            }
            catch (ProviderInvocationException)
            {
            }
            catch (NotSupportedException)
            {
            }
            catch (InvalidOperationException)
            {
            }
            catch (ItemNotFoundException)
            {
            }

            if (providerInfo is null)
            {
                return(null);
            }

            // Does the provider know how to generate MAML.
            CmdletProvider cmdletProvider        = providerInfo.CreateInstance();
            ICmdletProviderSupportsHelp provider = cmdletProvider as ICmdletProviderSupportsHelp;

            // Under JEA sessions the resolvedProviderPath will be null, we should allow get-help to continue.
            if (provider is null)
            {
                return(null);
            }

            bool isJEASession = false;

            if (this._executionContext.InitialSessionState != null && this._executionContext.InitialSessionState.Providers != null && providerInfo != null)
            {
                foreach (
                    Runspaces.SessionStateProviderEntry sessionStateProvider in
                    this._executionContext.InitialSessionState.Providers[providerInfo.Name])
                {
                    if (sessionStateProvider.Visibility == SessionStateEntryVisibility.Private)
                    {
                        isJEASession = true;
                        break;
                    }
                }
            }

            if (resolvedProviderPath is null)
            {
                if (isJEASession)
                {
                    return(null);
                }
                else
                {
                    throw new ItemNotFoundException(_requestedPath, "PathNotFound", SessionStateStrings.PathNotFound);
                }
            }

            // ok we have path and valid provider that supplys content..initialize the provider
            // and get the help content for the path.
            cmdletProvider.Start(providerInfo, cmdletProviderContext);
            // There should be exactly one resolved path.
            string providerPath = resolvedProviderPath;
            // Get the MAML help info. Don't catch exceptions thrown by provider.
            string mamlXmlString = provider.GetHelpMaml(helpItemName, providerPath);

            if (string.IsNullOrEmpty(mamlXmlString))
            {
                return(null);
            }
            // process the MAML content only if it is non-empty.
            XmlDocument mamlDoc = InternalDeserializer.LoadUnsafeXmlDocument(
                mamlXmlString,
                false, /* ignore whitespace, comments, etc. */
                null); /* default maxCharactersInDocument */
            MamlCommandHelpInfo providerSpecificHelpInfo = MamlCommandHelpInfo.Load(mamlDoc.DocumentElement, HelpCategory.Provider);

            return(providerSpecificHelpInfo);
        }
 internal void Get(string path, bool recurse, CmdletProviderContext context)
 {
     this.sessionState.GetChildItems(path, recurse, 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);
            }
        }
示例#57
0
        } // GetContentReaders

        /// <summary>
        /// Resolves the specified paths to PathInfo objects
        /// </summary>
        /// 
        /// <param name="pathsToResolve">
        /// The paths to be resolved. Each path may contain glob characters.
        /// </param>
        /// 
        /// <param name="allowNonexistingPaths">
        /// If true, resolves the path even if it doesn't exist.
        /// </param>
        /// 
        /// <param name="allowEmptyResult">
        /// If true, allows a wildcard that returns no results.
        /// </param>
        /// 
        /// <param name="currentCommandContext">
        /// The context under which the command is running.
        /// </param>
        /// 
        /// <returns>
        /// An array of PathInfo objects that are the resolved paths for the
        /// <paramref name="pathsToResolve"/> parameter.
        /// </returns>
        /// 
        internal Collection<PathInfo> ResolvePaths(
            string[] pathsToResolve,
            bool allowNonexistingPaths,
            bool allowEmptyResult,
            CmdletProviderContext currentCommandContext)
        {
            Collection<PathInfo> results = new Collection<PathInfo>();

            foreach (string path in pathsToResolve)
            {
                bool pathNotFound = false;
                bool filtersHidPath = false;

                ErrorRecord pathNotFoundErrorRecord = null;

                try
                {
                    // First resolve each of the paths
                    Collection<PathInfo> pathInfos =
                        SessionState.Path.GetResolvedPSPathFromPSPath(
                            path,
                            currentCommandContext);

                    if (pathInfos.Count == 0)
                    {
                        pathNotFound = true;

                        // If the item simply did not exist,
                        // we would have got an ItemNotFoundException.
                        // If we get here, it's because the filters
                        // excluded the file.
                        if (!currentCommandContext.SuppressWildcardExpansion)
                        {
                            filtersHidPath = true;
                        }
                    }

                    foreach (PathInfo pathInfo in pathInfos)
                    {
                        results.Add(pathInfo);
                    }
                }
                catch (PSNotSupportedException notSupported)
                {
                    WriteError(
                        new ErrorRecord(
                            notSupported.ErrorRecord,
                            notSupported));
                }
                catch (DriveNotFoundException driveNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            driveNotFound.ErrorRecord,
                            driveNotFound));
                }
                catch (ProviderNotFoundException providerNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            providerNotFound.ErrorRecord,
                            providerNotFound));
                }
                catch (ItemNotFoundException pathNotFoundException)
                {
                    pathNotFound = true;
                    pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException);
                }

                if (pathNotFound)
                {
                    if (allowNonexistingPaths &&
                        (!filtersHidPath) &&
                        (currentCommandContext.SuppressWildcardExpansion ||
                        (!WildcardPattern.ContainsWildcardCharacters(path))))
                    {
                        ProviderInfo provider = null;
                        PSDriveInfo drive = null;
                        string unresolvedPath =
                            SessionState.Path.GetUnresolvedProviderPathFromPSPath(
                                path,
                                currentCommandContext,
                                out provider,
                                out drive);

                        PathInfo pathInfo =
                            new PathInfo(
                                drive,
                                provider,
                                unresolvedPath,
                                SessionState);
                        results.Add(pathInfo);
                    }
                    else
                    {
                        if (pathNotFoundErrorRecord == null)
                        {
                            // Detect if the path resolution failed to resolve to a file.
                            String error = StringUtil.Format(NavigationResources.ItemNotFound, Path);
                            Exception e = new Exception(error);

                            pathNotFoundErrorRecord = new ErrorRecord(
                                e,
                                "ItemNotFound",
                                ErrorCategory.ObjectNotFound,
                                Path);
                        }

                        WriteError(pathNotFoundErrorRecord);
                    }
                }
            }

            return results;
        } // ResolvePaths
示例#58
0
 internal void New(string path, string propertyName, string type, object value, CmdletProviderContext context)
 {
     this.sessionState.NewProperty(new string[] { path }, propertyName, type, value, context);
 }
示例#59
0
 internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext context)
 {
     return(this.sessionState.IsCurrentLocationOrAncestor(path, context));
 }
示例#60
0
        } // SetLocation

        /// <summary>
        /// Changes the current working directory to the path specified
        /// </summary>
        ///
        /// <param name="path">
        /// The path of the new current working directory
        /// </param>
        ///
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        ///
        /// <returns>
        /// The PathInfo object representing the path of the location
        /// that was set.
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        ///
        /// <exception cref="ArgumentException">
        /// If <paramref name="path"/> does not exist, is not a container, or
        /// resolved to multiple containers.
        /// </exception>
        ///
        /// <exception cref="ProviderNotFoundException">
        /// If <paramref name="path"/> refers to a provider that does not exist.
        /// </exception>
        ///
        /// <exception cref="DriveNotFoundException">
        /// If <paramref name="path"/> refers to a drive that does not exist.
        /// </exception>
        ///
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with <paramref name="path"/> threw an
        /// exception.
        /// </exception>
        ///
        /// <exception cref="ItemNotFoundException">
        /// If the <paramref name="path"/> could not be resolved.
        /// </exception>
        ///
        internal PathInfo SetLocation(string path, CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            string       originalPath = path;
            string       driveName    = null;
            ProviderInfo provider     = null;
            string       providerId   = null;

            PSDriveInfo previousWorkingDrive = CurrentDrive;

            // First check to see if the path is a home path

            if (LocationGlobber.IsHomePath(path))
            {
                path = Globber.GetHomeRelativePath(path);
            }

            if (LocationGlobber.IsProviderDirectPath(path))
            {
                // The path is a provider-direct path so use the current
                // provider and its hidden drive but don't modify the path
                // at all.

                provider     = CurrentLocation.Provider;
                CurrentDrive = provider.HiddenDrive;
            }
            else if (LocationGlobber.IsProviderQualifiedPath(path, out providerId))
            {
                provider     = GetSingleProvider(providerId);
                CurrentDrive = provider.HiddenDrive;
            }
            else
            {
                // See if the path is a relative or absolute
                // path.

                if (Globber.IsAbsolutePath(path, out driveName))
                {
                    // Since the path is an absolute path
                    // we need to change the current working
                    // drive

                    PSDriveInfo newWorkingDrive = GetDrive(driveName);
                    CurrentDrive = newWorkingDrive;

                    // Now that the current working drive is set,
                    // process the rest of the path as a relative path.
                }
            }

            if (context == null)
            {
                context = new CmdletProviderContext(this.ExecutionContext);
            }

            if (CurrentDrive != null)
            {
                context.Drive = CurrentDrive;
            }

            CmdletProvider providerInstance = null;

            Collection <PathInfo> workingPath = null;

            try
            {
                workingPath =
                    Globber.GetGlobbedMonadPathsFromMonadPath(
                        path,
                        false,
                        context,
                        out providerInstance);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception) // Catch-all OK, 3rd party callout
            {
                // Reset the drive to the previous drive and
                // then rethrow the error

                CurrentDrive = previousWorkingDrive;
                throw;
            }

            if (workingPath.Count == 0)
            {
                // Set the current working drive back to the previous
                // one in case it was changed.

                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // We allow globbing the location as long as it only resolves a single container.

            bool foundContainer                     = false;
            bool pathIsContainer                    = false;
            bool pathIsProviderQualifiedPath        = false;
            bool currentPathisProviderQualifiedPath = false;

            for (int index = 0; index < workingPath.Count; ++index)
            {
                CmdletProviderContext normalizePathContext =
                    new CmdletProviderContext(context);

                PathInfo resolvedPath = workingPath[index];
                string   currentPath  = path;
                try
                {
                    string providerName = null;
                    currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName);
                    if (currentPathisProviderQualifiedPath)
                    {
                        // The path should be the provider-qualified path without the provider ID
                        // or ::

                        string providerInternalPath = LocationGlobber.RemoveProviderQualifier(resolvedPath.Path);

                        try
                        {
                            currentPath = NormalizeRelativePath(GetSingleProvider(providerName), providerInternalPath, String.Empty, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception) // Catch-all OK, 3rd party callout
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error

                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }
                    else
                    {
                        try
                        {
                            currentPath = NormalizeRelativePath(resolvedPath.Path, CurrentDrive.Root, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception) // Catch-all OK, 3rd party callout
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error

                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }

                    // Now see if there was errors while normalizing the path

                    if (normalizePathContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        normalizePathContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                // Check to see if the path is a container

                bool isContainer = false;

                CmdletProviderContext itemContainerContext =
                    new CmdletProviderContext(context);
                itemContainerContext.SuppressWildcardExpansion = true;

                try
                {
                    isContainer =
                        IsItemContainer(
                            resolvedPath.Path,
                            itemContainerContext);

                    if (itemContainerContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        itemContainerContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                catch (NotSupportedException)
                {
                    if (currentPath.Length == 0)
                    {
                        // Treat this as a container because providers that only
                        // support the ContainerCmdletProvider interface are really
                        // containers at their root.

                        isContainer = true;
                    }
                }
                finally
                {
                    itemContainerContext.RemoveStopReferral();
                }

                if (isContainer)
                {
                    if (foundContainer)
                    {
                        // The path resolved to more than one container

                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        throw
                            PSTraceSource.NewArgumentException(
                                "path",
                                SessionStateStrings.PathResolvedToMultiple,
                                originalPath);
                    }
                    else
                    {
                        // Set the path to use
                        path = currentPath;

                        // Mark it as a container
                        pathIsContainer = true;

                        // Mark whether or not it was provider-qualified
                        pathIsProviderQualifiedPath = currentPathisProviderQualifiedPath;

                        // Mark that we have already found one container. Finding additional
                        // should be an error
                        foundContainer = true;
                    }
                }
            }

            if (pathIsContainer)
            {
                // Remove the root slash since it is implied that the
                // current working directory is relative to the root.

                if (!LocationGlobber.IsProviderDirectPath(path) &&
                    path.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.CurrentCulture) &&
                    !pathIsProviderQualifiedPath)
                {
                    path = path.Substring(1);
                }

                s_tracer.WriteLine(
                    "New working path = {0}",
                    path);

                CurrentDrive.CurrentLocation = path;
            }
            else
            {
                // Set the current working drive back to the previous
                // one in case it was changed.

                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        originalPath,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // Now make sure the current drive is set in the provider's
            // current working drive hashtable

            ProvidersCurrentWorkingDrive[CurrentDrive.Provider] =
                CurrentDrive;

            // Set the $PWD variable to the new location

            this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal);
            return(this.CurrentLocation);
        } // SetLocation