public VirtualDiskPSDriveInfo(PSDriveInfo toCopy, string root, VirtualDisk disk)
     : base(toCopy.Name, toCopy.Provider, root, toCopy.Description, toCopy.Credential)
 {
     _disk = disk;
     _volMgr = new VolumeManager(_disk);
     _fsCache = new Dictionary<string, DiscFileSystem>();
 }
        protected override PSDriveInfo NewDrive(PSDriveInfo drive)
        {
            if (drive == null)
            {
                WriteError(new ErrorRecord(
                           new ArgumentNullException("drive"),
                           "NullDrive",
                           ErrorCategory.InvalidArgument,
                           null));

                return null;
            }
            SFGAO attributes;
            SFGAO isContainerQuery = SFGAO.Browsable | SFGAO.Folder;
            IdList pidl = GetPidlFromPath(drive.Root, isContainerQuery, out attributes);
            if ((attributes & isContainerQuery) == SFGAO.None)
            {
                WriteError(new ErrorRecord(
                           new ArgumentException("drive.Root"),
                           "NotAContainer",
                           ErrorCategory.InvalidArgument,
                           null));
                return null;
            }

            return new ShellPSDriveInfo((ShellFolder)ShellItem.GetShellItem(pidl, new ShellItem.ShellItemKnownInfo()
            {
                LoadedAttributes = isContainerQuery,
                Attributes = attributes
            }), drive);
        }
Example #3
0
 internal ProviderInfo(SessionState sessionState, Type implementingType, string name, string description, string home, string helpFile, PSSnapInInfo psSnapIn)
 {
     this.helpFile = "";
     if (sessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("sessionState");
     }
     if (implementingType == null)
     {
         throw PSTraceSource.NewArgumentNullException("implementingType");
     }
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     this.sessionState = sessionState;
     this.name = name;
     this.description = description;
     this.home = home;
     this.implementingType = implementingType;
     this.helpFile = helpFile;
     this.pssnapin = psSnapIn;
     this.hiddenDrive = new PSDriveInfo(this.FullName, this, "", "", null);
     this.hiddenDrive.Hidden = true;
 }
Example #4
0
 protected override Collection<PSDriveInfo> InitializeDefaultDrives()
 {
     PSDriveInfo item = new PSDriveInfo("Env", ProviderInfo, string.Empty, string.Empty, null);
     Collection<PSDriveInfo> collection = new Collection<PSDriveInfo>();
     collection.Add(item);
     return collection;
 }
Example #5
0
        /// <summary>
        /// Initializes the specified VFS drive.
        /// </summary>
        /// <param name="drive">The drive to initialize.</param>
        /// <returns>The <see cref="VfsDriveInfo"/> object which represents the initialized drive.</returns>
        protected override VfsDriveInfo InitializeNewDrive(PSDriveInfo drive)
        {
            if (drive is OrchardDriveInfo)
            {
                return (VfsDriveInfo)drive;
            }

            var driveParameters = (OrchardDriveParameters)DynamicParameters;
            if (driveParameters == null)
            {
                return null;
            }

            if (!OrchardPsSnapIn.VerifyOrchardDirectory(driveParameters.OrchardRoot))
            {
                this.WriteError(
                    ThrowHelper.InvalidRootPathException(driveParameters.OrchardRoot),
                    ErrorIds.InvalidRootDirectory,
                    ErrorCategory.InvalidArgument,
                    drive);

                return null;
            }

            VfsDriveInfo orchardDrive = null;
            this.TryCritical(
                () => orchardDrive = this.InitializeOrchardDrive(drive, driveParameters),
                ErrorIds.OrchardInitFailed,
                ErrorCategory.OpenError);

            return orchardDrive;
        }
Example #6
0
		// NewDrive

		/// <summary>
		/// 	Removes a drive from the provider.
		/// </summary>
		/// <param name = "drive">The drive to remove.</param>
		/// <returns>The drive removed.</returns>
		protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
		{
			// check if drive object is null
			if (drive == null)
			{
				WriteError(new ErrorRecord(
				           	new ArgumentNullException("drive"),
				           	"NullDrive",
				           	ErrorCategory.InvalidArgument,
				           	drive)
					);

				return null;
			}

			// dispose database on drive
			var ravenDBPSDriveInfo = drive as RavenDBPSDriveInfo;

			if (ravenDBPSDriveInfo == null)
			{
				return null;
			}

			ravenDBPSDriveInfo.Database.Dispose();

			return ravenDBPSDriveInfo;
		}
Example #7
0
 protected virtual PSDriveInfo RemoveDrive(PSDriveInfo drive)
 {
     using (PSTransactionManager.GetEngineProtectionScope())
     {
         return drive;
     }
 }
 internal UpdatableHelpSystemDrive(PSCmdlet cmdlet, string path, PSCredential credential)
 {
     for (int i = 0; i < 6; i++)
     {
         this._driveName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
         this._cmdlet = cmdlet;
         if (path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase) || path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
         {
             path = path.Remove(path.Length - 1);
         }
         PSDriveInfo atScope = cmdlet.SessionState.Drive.GetAtScope(this._driveName, "local");
         if (atScope != null)
         {
             if (atScope.Root.Equals(path))
             {
                 return;
             }
             if (i < 5)
             {
                 continue;
             }
             cmdlet.SessionState.Drive.Remove(this._driveName, true, "local");
         }
         atScope = new PSDriveInfo(this._driveName, cmdlet.SessionState.Internal.GetSingleProvider("FileSystem"), path, string.Empty, credential);
         cmdlet.SessionState.Drive.New(atScope, "local");
         return;
     }
 }
Example #9
0
 public DriveInfo(PSDriveInfo driveInfo, NewDriveParameters parameters)
     : base(driveInfo)
 {
     if (parameters != null)
         Directory = parameters.Directory;
     EnsureDescription();
 }
Example #10
0
 internal PathInfo(PSDriveInfo drive, ProviderInfo provider, Path path, SessionState sessionState)
 {
     Drive = drive;
     Provider = provider;
     _path = path;
     _sessionState = sessionState;
 }
Example #11
0
 protected override void ProcessRecord()
 {
     var provider = SessionState.Provider.GetOne(PSProvider);
     var driveInfo = new PSDriveInfo(Name, provider, Root, Description, Credential);
     var realDrive = SessionState.Drive.New(driveInfo, Scope ?? "local", ProviderRuntime);
     WriteObject(realDrive);
 }
Example #12
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;
 }
Example #13
0
 public int CompareTo(PSDriveInfo drive)
 {
     if (drive == null)
     {
         throw PSTraceSource.NewArgumentNullException("drive");
     }
     return string.Compare(this.Name, drive.Name, true, CultureInfo.CurrentCulture);
 }
 protected override Collection<PSDriveInfo> InitializeDefaultDrives()
 {
     PSDriveInfo drive = new PSDriveInfo("Objects", this.ProviderInfo, @"\", "Object Manager Root Directory", null);
     PSDriveInfo session = new PSDriveInfo("SessionObjects", this.ProviderInfo, 
         String.Format(@"\Sessions\{0}\BaseNamedObjects", Process.GetCurrentProcess().SessionId), "Current Session Objects", null);
     Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>() { drive, session };
     return drives;
 }
Example #15
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);
 }
Example #16
0
 public static string MakePath(string path, PSDriveInfo drive)
 {
     string format = "{0}:" + '\\' + "{1}";
     if (path.StartsWith("\\"))
     {
         format = "{0}:{1}";
     }
     return string.Format(format, new object[] { drive.Name, path });
 }
Example #17
0
        protected override PSDriveInfo NewDrive(PSDriveInfo drive)
        {
            if( drive is DTEDrive )
            {
                return drive;
            }

            return new DTEDrive( drive, DTE2 );
        }
 protected override PSDriveInfo NewDrive(PSDriveInfo drive)
 {
     var sqlServerPsDriveInfo = new SqlServerPsDriveInfo(drive);
     if (!sqlServerPsDriveInfo.ItemExists(drive.Root))
     {
         ThrowTerminatingError(new ErrorRecord(null, "BadServer", ErrorCategory.InvalidArgument, drive.Root));
     }
     return sqlServerPsDriveInfo;
 }
Example #19
0
 protected PSDriveInfo(PSDriveInfo driveInfo)
 {
     Name = driveInfo.Name;
     Provider = driveInfo.Provider;
     Root = driveInfo.Root;
     Description = driveInfo.Description;
     Credential = driveInfo.Credential;
     CurrentLocation = driveInfo.CurrentLocation;
 }
Example #20
0
 public Context(CmdletProvider provider, string path, PSDriveInfo drive, IPathNodeProcessor pathProcessor, object dynamicParameters, Version topology, bool recurse)
 {
     _pathProcessor = pathProcessor;
     DynamicParameters = dynamicParameters;
     _provider = provider;
     _path = path;
     _drive = drive;
     _recurse = recurse;
     PathTopologyVersion = topology;
 }
Example #21
0
 public ProviderContext(CmdletProvider provider, string path, PSDriveInfo drive, IPathResolver pathProcessor, object dynamicParameters, Version topology, bool recurse)
 {
     this.pathProcessor = pathProcessor;
     DynamicParameters = dynamicParameters;
     this.provider = provider;
     this.path = path;
     this.drive = drive;
     this.recurse = recurse;
     PathTopologyVersion = topology;
 }
Example #22
0
        public SQLiteDrive(PSDriveInfo driveInfo, string connectionString, SQLiteProvider.DriveParams driveParams) : base(driveInfo)
        {
            _driveParams = driveParams ?? new SQLiteProvider.DriveParams();
            _driveParams.ConnectionString = Regex.Replace(connectionString, @"^\[(.+)\].*", "$1" );

            if( _driveParams.ConnectionString.ToLowerInvariant().Contains( InMemoryConnectionString ) )
            {
                _driveParams.PersistentConnection = new SwitchParameter( true );
            }
        }
Example #23
0
        protected override PSDriveInfo NewDrive(PSDriveInfo drive)
        {
            if (drive is GenericEntityContextDrive)
            {
                return drive;
            }

            var p = this.DynamicParameters as GenericEntityContextDrive.NewParams;
            return new GenericEntityContextDrive( p.ContextType, drive );
        }
Example #24
0
        protected override PSDriveInfo NewDrive(PSDriveInfo drive)
        {
            var bipsDrive = drive as BipsDrive;
            if (null != bipsDrive)
            {
                return bipsDrive;
            }

            return new BipsDrive( drive );
        }
Example #25
0
 protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
 {
     var testdrive = drive as TestDrive;
     if (testdrive == null)
     {
         throw new InvalidOperationException("Drive is not a TestDrive!");
     }
     testdrive.IsRemoved = true;
     return testdrive;
 }
        protected override PSDriveInfo NewDrive(PSDriveInfo drive)
        {
            if (drive is HuddleDocumentLibraryInfo)
            {
                return drive;
            }

            var libraryParams = this.DynamicParameters as DocumentLibraryParameters;
            return new HuddleDocumentLibraryInfo(driveInfo: drive, driveParams: libraryParams);
        }
Example #27
0
        protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
        {
            var ds = drive as DataSourceDrive;
            if( null != ds)
            {
                var sources = ds.DataSources.ToList();
                sources.ForEach(d=>d.Dispose());
                sources.ForEach( ds.Remove );
            }

            return base.RemoveDrive(drive);
        }
Example #28
0
        protected override PSDriveInfo NewDrive(PSDriveInfo drive)
        {
			var uri = new Uri(drive.Root);
			/* drive.Root.Replace('/', '\\') */
            var newDrive = new PSDriveInfo(
                drive.Name,
                drive.Provider,
				uri.Host,
                drive.Description,
                drive.Credential);
            return new ODataDrive(uri, newDrive );
        }
Example #29
0
 protected override System.Collections.ObjectModel.Collection<System.Management.Automation.PSDriveInfo> InitializeDefaultDrives()
 {
     var driveInfo = new PSDriveInfo(
         "Triggers",
         ProviderInfo,
         "",
         "Data Source Triggers",
         null
     );
     var drive = new TriggerDrive(driveInfo);
     return new Collection<PSDriveInfo> { drive };
 }
        internal Drive CreateCloudDrive(PSDriveInfo driveInfo, CloudDriveParameters parameters)
        {
            var rootName = CreateRootName(driveInfo);

            var asyncGateway = default(IAsyncCloudGateway);
            if (GatewayManager.TryGetAsyncCloudGatewayForSchema(rootName.Schema, out asyncGateway))
                return new AsyncCloudDrive(CreateDriveInfo(driveInfo), rootName, asyncGateway, parameters);

            var gateway = default(ICloudGateway);
            if (GatewayManager.TryGetCloudGatewayForSchema(rootName.Schema, out gateway))
                return new CloudDrive(CreateDriveInfo(driveInfo), rootName, gateway, parameters);

            throw new KeyNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.NoGatewayForSchema, rootName.Schema));
        }
Example #31
0
        /// <summary>
        /// Compares this instance to the specified object. The object must be a PSDriveInfo.
        /// </summary>
        /// <param name="obj">
        /// An object to compare.
        /// </param>
        /// <returns>
        /// A signed number indicating the relative values of this
        /// instance and object specified.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="obj"/> is not a PSDriveInfo instance.
        /// </exception>
        public int CompareTo(object obj)
        {
            PSDriveInfo drive = obj as PSDriveInfo;

            if (drive == null)
            {
                ArgumentException e =
                    PSTraceSource.NewArgumentException(
                        nameof(obj),
                        SessionStateStrings.OnlyAbleToComparePSDriveInfo);
                throw e;
            }

            return(CompareTo(drive));
        }
 internal CmdletProviderContext(PSCmdlet command, PSCredential credentials, PSDriveInfo drive)
 {
     this.command = command != null ? (Cmdlet)command : throw CmdletProviderContext.tracer.NewArgumentNullException(nameof(command));
     this._origin = command.CommandOrigin;
     if (credentials != null)
     {
         this.credentials = credentials;
     }
     this.drive = drive;
     if (command.Host == null)
     {
         throw CmdletProviderContext.tracer.NewArgumentException("command.Host");
     }
     this.executionContext = command.Context != null ? command.Context : throw CmdletProviderContext.tracer.NewArgumentException("command.Context");
     this.streamObjects    = true;
     this.streamErrors     = true;
 }
Example #33
0
 protected ProviderInfo(ProviderInfo providerInfo)
 {
     this.helpFile = "";
     if (providerInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("providerInfo");
     }
     this.name             = providerInfo.Name;
     this.implementingType = providerInfo.ImplementingType;
     this.capabilities     = providerInfo.capabilities;
     this.description      = providerInfo.description;
     this.hiddenDrive      = providerInfo.hiddenDrive;
     this.home             = providerInfo.home;
     this.helpFile         = providerInfo.helpFile;
     this.pssnapin         = providerInfo.pssnapin;
     this.sessionState     = providerInfo.sessionState;
 }
Example #34
0
        /// <summary>
        /// Constructs an instance of the class using an existing reference
        /// as a template.
        /// </summary>
        /// <param name="providerInfo">
        /// The provider information to copy to this instance.
        /// </param>
        /// <remarks>
        /// This constructor should be used by derived types to easily copying
        /// the base class members from an existing ProviderInfo.
        /// This is designed for use by a <see cref="System.Management.Automation.Provider.CmdletProvider"/>
        /// during calls to their <see cref="System.Management.Automation.Provider.CmdletProvider.Start(ProviderInfo)"/> method.
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="providerInfo"/> is null.
        /// </exception>
        protected ProviderInfo(ProviderInfo providerInfo)
        {
            if (providerInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("providerInfo");
            }

            Name = providerInfo.Name;
            ImplementingType = providerInfo.ImplementingType;
            _capabilities = providerInfo._capabilities;
            Description = providerInfo.Description;
            _hiddenDrive = providerInfo._hiddenDrive;
            Home = providerInfo.Home;
            HelpFile = providerInfo.HelpFile;
            PSSnapIn = providerInfo.PSSnapIn;
            _sessionState = providerInfo._sessionState;
            VolumeSeparatedByColon = providerInfo.VolumeSeparatedByColon;
        }
 internal CmdletProviderContext(CmdletProviderContext contextToCopyFrom)
 {
     this.executionContext = contextToCopyFrom != null ? contextToCopyFrom.ExecutionContext : throw CmdletProviderContext.tracer.NewArgumentNullException(nameof(contextToCopyFrom));
     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;
 }
Example #36
0
 internal PathInfo(PSDriveInfo drive, ProviderInfo provider, string path, SessionState sessionState)
 {
     if (provider == null)
     {
         throw PSTraceSource.NewArgumentNullException("provider");
     }
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     if (sessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("sessionState");
     }
     this.drive        = drive;
     this.provider     = provider;
     this.path         = path;
     this.sessionState = sessionState;
 }
 internal CmdletProviderContext(System.Management.Automation.ExecutionContext executionContext)
 {
     this.credentials             = PSCredential.Empty;
     this._origin                 = CommandOrigin.Internal;
     this.accumulatedObjects      = new Collection <PSObject>();
     this.accumulatedErrorObjects = new Collection <ErrorRecord>();
     this.stopReferrals           = new Collection <CmdletProviderContext>();
     if (executionContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("executionContext");
     }
     this.executionContext = executionContext;
     this._origin          = CommandOrigin.Internal;
     this.drive            = executionContext.EngineSessionState.CurrentDrive;
     if ((executionContext.CurrentCommandProcessor != null) && (executionContext.CurrentCommandProcessor.Command is Cmdlet))
     {
         this.command = (Cmdlet)executionContext.CurrentCommandProcessor.Command;
     }
 }
Example #38
0
 protected PSDriveInfo(PSDriveInfo driveInfo)
 {
     this.credentials = PSCredential.Empty;
     if (driveInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("driveInfo");
     }
     this.name                    = driveInfo.Name;
     this.provider                = driveInfo.Provider;
     this.credentials             = driveInfo.Credential;
     this.currentWorkingDirectory = driveInfo.CurrentLocation;
     this.description             = driveInfo.Description;
     this.driveBeingCreated       = driveInfo.driveBeingCreated;
     this.hidden                  = driveInfo.hidden;
     this.isAutoMounted           = driveInfo.isAutoMounted;
     this.root                    = driveInfo.root;
     this.persist                 = driveInfo.Persist;
     this.Trace();
 }
Example #39
0
        /// <summary>
        /// Constructs a new instance of the PSDriveInfo using another PSDriveInfo
        /// as a template.
        /// </summary>
        /// <param name="driveInfo">
        /// An existing PSDriveInfo object that should be copied to this instance.
        /// </param>
        /// <remarks>
        /// A protected constructor that derived classes can call with an instance
        /// of this class. This allows for easy creation of derived PSDriveInfo objects
        /// which can be created in CmdletProvider's NewDrive method using the PSDriveInfo
        /// that is passed in.
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="PSDriveInfo"/> is null.
        /// </exception>
        protected PSDriveInfo(PSDriveInfo driveInfo)
        {
            if (driveInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(driveInfo));
            }

            _name      = driveInfo.Name;
            _provider  = driveInfo.Provider;
            Credential = driveInfo.Credential;
            _currentWorkingDirectory = driveInfo.CurrentLocation;
            Description       = driveInfo.Description;
            this.MaximumSize  = driveInfo.MaximumSize;
            DriveBeingCreated = driveInfo.DriveBeingCreated;
            _hidden           = driveInfo._hidden;
            IsAutoMounted     = driveInfo.IsAutoMounted;
            _root             = driveInfo._root;
            Persist           = driveInfo.Persist;
            this.Trace();
        }
Example #40
0
        public static bool FinDriveFromPath(string path, ProviderInfo provider, out PSDriveInfo foundDrive)
        {
            PSDriveInfo info  = null;
            bool        found = false;

            foreach (var drive in provider.Drives.OrderByDescending(x => x.Name.Length))
            {
                if (path.StartsWith(drive.Name, StringComparison.OrdinalIgnoreCase))
                {
                    info  = drive;
                    found = true;
                    break;
                }
            }
            if (info == null)
            {
                info = provider.HiddenDrive;
            }
            foundDrive = info;
            return(found);
        }
Example #41
0
        internal static string ResolveFilePath(string filePath, PSCmdlet command)
        {
            string str;

            try
            {
                ProviderInfo        provider = (ProviderInfo)null;
                Collection <string> providerPathFromPsPath = command.SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider);
                if (!provider.NameEquals(command.Context.ProviderNames.FileSystem))
                {
                    PathUtils.ReportWrongProviderType((Cmdlet)command, provider.FullName);
                }
                if (providerPathFromPsPath.Count > 1)
                {
                    PathUtils.ReportMultipleFilesNotSupported((Cmdlet)command);
                }
                if (providerPathFromPsPath.Count == 0)
                {
                    PathUtils.ReportWildcardingFailure((Cmdlet)command, filePath);
                }
                str = providerPathFromPsPath[0];
            }
            catch (ItemNotFoundException ex)
            {
                str = (string)null;
            }
            if (string.IsNullOrEmpty(str))
            {
                CmdletProviderContext context  = new CmdletProviderContext((Cmdlet)command);
                ProviderInfo          provider = (ProviderInfo)null;
                PSDriveInfo           drive    = (PSDriveInfo)null;
                str = command.SessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath, context, out provider, out drive);
                context.ThrowFirstErrorOrDoNothing();
                if (!provider.NameEquals(command.Context.ProviderNames.FileSystem))
                {
                    PathUtils.ReportWrongProviderType((Cmdlet)command, provider.FullName);
                }
            }
            return(str);
        }
Example #42
0
        /// <summary>
        /// The constructor of the PathInfo object.
        /// </summary>
        /// <param name="drive">
        /// The drive that contains the path
        /// </param>
        /// <param name="provider">
        /// The provider that contains the path.
        /// </param>
        /// <param name="path">
        /// The path this object represents.
        /// </param>
        /// <param name="sessionState">
        /// The session state associated with the drive, provider, and path information.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="drive"/>, <paramref name="provider"/>,
        /// <paramref name="path"/>, or <paramref name="sessionState"/> is null.
        /// </exception>
        internal PathInfo(PSDriveInfo drive, ProviderInfo provider, string path, SessionState sessionState)
        {
            if (provider == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(provider));
            }

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

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

            _drive        = drive;
            _provider     = provider;
            _path         = path;
            _sessionState = sessionState;
        }
Example #43
0
        internal PSDriveInfo GetDrive(string name)
        {
            if (name == null)
            {
                throw PSTraceSource.NewArgumentNullException("name");
            }
            PSDriveInfo info = null;

            if (OSHelper.IsUnix && name == "Microsoft.PowerShell.Core\\FileSystem")
            {
                name = "/";
            }
            if (this.GetDrives().ContainsKey(name))
            {
                return(this.GetDrives()[name]);
            }
            if (this.GetAutomountedDrives().ContainsKey(name))
            {
                info = this.GetAutomountedDrives()[name];
            }
            return(info);
        }
Example #44
0
 internal void RemoveDrive(PSDriveInfo drive)
 {
     if (drive == null)
     {
         throw PSTraceSource.NewArgumentNullException("drive");
     }
     if (this._drives != null)
     {
         if (this.GetDrives().ContainsKey(drive.Name))
         {
             this.GetDrives().Remove(drive.Name);
         }
         else if (this.GetAutomountedDrives().ContainsKey(drive.Name))
         {
             this.GetAutomountedDrives()[drive.Name].IsAutoMountedManuallyRemoved = true;
             if (drive.IsNetworkDrive)
             {
                 this.GetAutomountedDrives().Remove(drive.Name);
             }
         }
     }
 }
Example #45
0
        /// <summary>
        /// Constructs the context under which the core command providers
        /// operate.
        /// </summary>
        /// <param name="command">
        /// The command object that is running.
        /// </param>
        /// <param name="credentials">
        /// The credentials the core command provider should use.
        /// </param>
        /// <param name="drive">
        /// The drive under which this context should operate.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="command"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="command"/> contains a null Host or Context reference.
        /// </exception>
        internal CmdletProviderContext(
            PSCmdlet command,
            PSCredential credentials,
            PSDriveInfo drive)
        {
            // verify the command parameter
            if (command == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(command));
            }

            _command = command;
            Origin   = command.CommandOrigin;

            if (credentials != null)
            {
                _credentials = credentials;
            }

            Drive = drive;

            if (command.Host == null)
            {
                throw PSTraceSource.NewArgumentException("command.Host");
            }

            if (command.Context == null)
            {
                throw PSTraceSource.NewArgumentException("command.Context");
            }

            ExecutionContext = command.Context;

            // Stream will default to true because command methods will be used.

            PassThru      = true;
            _streamErrors = true;
        }
Example #46
0
 public int CompareTo(PSDriveInfo drive)
 {
     return(string.Compare(Name, drive.Name, true, CultureInfo.CurrentUICulture));
 }
Example #47
0
 public bool Equals(PSDriveInfo drive)
 {
     return(CompareTo(drive) == 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 == 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 == 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 == 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);
        }
Example #49
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));
        }
Example #50
0
        /// <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("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(
                                "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);
        }
Example #51
0
        /// <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);
        }
Example #52
0
 internal PathInfo(PSDriveInfo drive, string path, SessionState sessionState)
 {
     Drive    = drive;
     Provider = drive == null ? null : drive.Provider;
     SetPathTypes(path, sessionState);
 }
Example #53
0
 public string GetUnresolvedProviderPathFromPSPath(string path, out ProviderInfo provider, out PSDriveInfo drive)
 {
     throw new NotImplementedException();
 }
        } // 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
        public PSDriveInfo New(PSDriveInfo drive, string scope)
        {
            var runtime = new ProviderRuntime(_scope.SessionState);

            return(New(drive, scope, runtime));
        }
 internal bool TryGet(string driveName, out PSDriveInfo info)
 {
     info = _scope.Get(driveName, false);
     return(info != null);
 }
 internal PSDriveInfo New(PSDriveInfo drive, string scope, ProviderRuntime providerRuntime)
 {
     // make sure the provider can intitalize this drive properly
     drive = GetProvider(drive).NewDrive(drive, providerRuntime);
     return(NewSkipInit(drive, scope));
 }
Example #58
0
 public PSDriveInfo New(PSDriveInfo drive, string scope)
 {
     using (DriveManagementIntrinsics.tracer.TraceMethod())
         return(this.sessionState.NewDrive(drive, scope));
 }
Example #59
0
        /// <summary>
        /// Resolves the specified path to PathInfo objects
        /// </summary>
        ///
        /// <param name="pathToResolve">
        /// The path 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="currentCommandContext">
        /// The context under which the command is running.
        /// </param>
        ///
        /// <returns>
        /// A string representing the resolved path.
        /// </returns>
        ///
        private PathInfo ResolvePath(
            string pathToResolve,
            bool allowNonexistingPaths,
            CmdletProviderContext currentCommandContext)
        {
            Collection <PathInfo> results = new Collection <PathInfo>();

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

                foreach (PathInfo pathInfo in pathInfos)
                {
                    results.Add(pathInfo);
                }
            }
            catch (PSNotSupportedException notSupported)
            {
                WriteError(
                    new ErrorRecord(
                        notSupported.ErrorRecord,
                        notSupported));
            }
            catch (System.Management.Automation.DriveNotFoundException driveNotFound)
            {
                WriteError(
                    new ErrorRecord(
                        driveNotFound.ErrorRecord,
                        driveNotFound));
            }
            catch (ProviderNotFoundException providerNotFound)
            {
                WriteError(
                    new ErrorRecord(
                        providerNotFound.ErrorRecord,
                        providerNotFound));
            }
            catch (ItemNotFoundException pathNotFound)
            {
                if (allowNonexistingPaths)
                {
                    ProviderInfo provider = null;
                    System.Management.Automation.PSDriveInfo drive = null;
                    string unresolvedPath =
                        SessionState.Path.GetUnresolvedProviderPathFromPSPath(
                            pathToResolve,
                            currentCommandContext,
                            out provider,
                            out drive);

                    PathInfo pathInfo =
                        new PathInfo(
                            drive,
                            provider,
                            unresolvedPath,
                            SessionState);
                    results.Add(pathInfo);
                }
                else
                {
                    WriteError(
                        new ErrorRecord(
                            pathNotFound.ErrorRecord,
                            pathNotFound));
                }
            }

            if (results.Count == 1)
            {
                return(results[0]);
            }
            else if (results.Count > 1)
            {
                Exception e = PSTraceSource.NewNotSupportedException();
                WriteError(
                    new ErrorRecord(e,
                                    "NotSupported",
                                    ErrorCategory.NotImplemented,
                                    results));
                return(null);
            }
            else
            {
                return(null);
            }
        } // ResolvePath
Example #60
0
 internal void New(PSDriveInfo drive, string scope, CmdletProviderContext context)
 {
     using (DriveManagementIntrinsics.tracer.TraceMethod())
         this.sessionState.NewDrive(drive, scope, context);
 }