예제 #1
0
 protected override void ProcessRecord()
 {
     foreach (string str in this.name)
     {
         bool wasFiltered = false;
         List<PSVariable> list = base.GetMatchingVariables(str, base.Scope, out wasFiltered, false);
         list.Sort((Comparison<PSVariable>) ((left, right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)));
         bool flag2 = false;
         foreach (PSVariable variable in list)
         {
             flag2 = true;
             if (this.valueOnly)
             {
                 base.WriteObject(variable.Value);
             }
             else
             {
                 base.WriteObject(variable);
             }
         }
         if (!flag2 && !wasFiltered)
         {
             ItemNotFoundException replaceParentContainsErrorRecordException = new ItemNotFoundException(str, "VariableNotFound", SessionStateStrings.VariableNotFound);
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
         }
     }
 }
예제 #2
0
 protected override void ProcessRecord()
 {
     foreach (string str in this.names)
     {
         bool wasFiltered = false;
         List<PSVariable> list = base.GetMatchingVariables(str, base.Scope, out wasFiltered, false);
         if ((list.Count == 0) && !wasFiltered)
         {
             ItemNotFoundException replaceParentContainsErrorRecordException = new ItemNotFoundException(str, "VariableNotFound", SessionStateStrings.VariableNotFound);
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
         }
         else
         {
             foreach (PSVariable variable in list)
             {
                 string clearVariableAction = VariableCommandStrings.ClearVariableAction;
                 string target = StringUtil.Format(VariableCommandStrings.ClearVariableTarget, variable.Name);
                 if (base.ShouldProcess(target, clearVariableAction))
                 {
                     PSVariable sendToPipeline = variable;
                     try
                     {
                         if (this.force && ((variable.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None))
                         {
                             variable.SetOptions(variable.Options & ~ScopedItemOptions.ReadOnly, true);
                             sendToPipeline = this.ClearValue(variable);
                             variable.SetOptions(variable.Options | ScopedItemOptions.ReadOnly, true);
                         }
                         else
                         {
                             sendToPipeline = this.ClearValue(variable);
                         }
                     }
                     catch (SessionStateException exception2)
                     {
                         base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
                         continue;
                     }
                     catch (PSArgumentException exception3)
                     {
                         base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
                         continue;
                     }
                     if (this.passThru)
                     {
                         base.WriteObject(sendToPipeline);
                     }
                 }
             }
         }
     }
 }
예제 #3
0
 protected override void ProcessRecord()
 {
     if (base.Scope == null)
     {
         base.Scope = "local";
     }
     foreach (string str in this.names)
     {
         bool wasFiltered = false;
         List<PSVariable> list = base.GetMatchingVariables(str, base.Scope, out wasFiltered, false);
         if ((list.Count == 0) && !wasFiltered)
         {
             ItemNotFoundException replaceParentContainsErrorRecordException = new ItemNotFoundException(str, "VariableNotFound", SessionStateStrings.VariableNotFound);
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
         }
         else
         {
             foreach (PSVariable variable in list)
             {
                 string removeVariableAction = VariableCommandStrings.RemoveVariableAction;
                 string target = StringUtil.Format(VariableCommandStrings.RemoveVariableTarget, variable.Name);
                 if (base.ShouldProcess(target, removeVariableAction))
                 {
                     try
                     {
                         if (string.IsNullOrEmpty(base.Scope))
                         {
                             base.SessionState.Internal.RemoveVariable(variable, this.force);
                         }
                         else
                         {
                             base.SessionState.Internal.RemoveVariableAtScope(variable, base.Scope, this.force);
                         }
                     }
                     catch (SessionStateException exception2)
                     {
                         base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
                     }
                     catch (PSArgumentException exception3)
                     {
                         base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
                     }
                 }
             }
         }
     }
 }
예제 #4
0
 internal Collection<PSTraceSource> GetMatchingTraceSource(string[] patternsToMatch, bool writeErrorIfMatchNotFound, out Collection<string> notMatched)
 {
     notMatched = new Collection<string>();
     Collection<PSTraceSource> collection = new Collection<PSTraceSource>();
     foreach (string str in patternsToMatch)
     {
         bool flag = false;
         if (string.IsNullOrEmpty(str))
         {
             notMatched.Add(str);
         }
         else
         {
             WildcardPattern pattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
             foreach (PSTraceSource source in PSTraceSource.TraceCatalog.Values)
             {
                 if (pattern.IsMatch(source.FullName))
                 {
                     flag = true;
                     collection.Add(source);
                 }
                 else if (pattern.IsMatch(source.Name))
                 {
                     flag = true;
                     collection.Add(source);
                 }
             }
             if (!flag)
             {
                 notMatched.Add(str);
                 if (writeErrorIfMatchNotFound && !WildcardPattern.ContainsWildcardCharacters(str))
                 {
                     ItemNotFoundException replaceParentContainsErrorRecordException = new ItemNotFoundException(str, "TraceSourceNotFound", SessionStateStrings.TraceSourceNotFound);
                     ErrorRecord errorRecord = new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException);
                     base.WriteError(errorRecord);
                 }
             }
         }
     }
     return collection;
 }
예제 #5
0
파일: Utils.cs 프로젝트: 40a/PowerShell
        ErrorRecord CreatePathNotFoundErrorRecord(string path,
                                                  string errorId)
        {
            ItemNotFoundException e =
                new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound);

            ErrorRecord er =
                new ErrorRecord(e,
                                errorId,
                                ErrorCategory.ObjectNotFound,
                                null);

            return er;
        }
예제 #6
0
        } // GetChildNames

        /// <summary>
        /// Gets names of the children of the specified path.
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the item from which to retrieve the child names.
        /// </param>
        /// 
        /// <param name="returnContainers">
        /// Determines if all containers should be returned or only those containers that match the
        /// filter(s).
        /// </param>
        /// 
        /// <param name="recurse">
        /// If true, gets all the relative paths of all the children 
        /// in all the sub-containers of the specified
        /// container. If false, only gets the immediate child names of the specified
        /// container.
        /// </param>
        ///
        /// <param name="depth">
        /// Limits the depth of recursion; uint.MaxValue performs full recursion.
        /// </param>
        /// 
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <returns>
        /// Nothing is returned, but all names should be written to the context object.
        /// </returns>
        /// 
        /// <remarks>
        /// The child names are the leaf portion of the path. Example, for the file system
        /// the name for the path c:\windows\system32\foo.dll would be foo.dll or for
        /// the directory c:\windows\system32 would be system32. For Active Directory the
        /// child names would be RDN values of the child objects of the container.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> or <paramref name="propertyToClear"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// If the <paramref name="path"/> refers to a provider that could not be found.
        /// </exception>
        /// 
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="path"/> refers to a drive that could not be found.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="path"/> refers to does
        /// not support this operation.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider threw an exception.
        /// </exception>
        /// 
        /// <exception cref="ItemNotFoundException">
        /// If <paramref name="path"/> does not contain glob characters and
        /// could not be found.
        /// </exception>
        /// 
        internal void GetChildNames(
            string path,
            ReturnContainers returnContainers,
            bool recurse,
            uint depth,
            CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            // Construct the include filter

            Collection<WildcardPattern> includeMatcher =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    context.Include,
                    WildcardOptions.IgnoreCase);


            // Construct the exclude filter

            Collection<WildcardPattern> excludeMatcher =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    context.Exclude,
                    WildcardOptions.IgnoreCase);

            if (LocationGlobber.ShouldPerformGlobbing(path, context))
            {
                ProviderInfo provider = null;
                CmdletProvider providerInstance = null;

                // We don't want to process include/exclude filters
                // when globbing the targets of the operation, so
                // copy the context without the filters.

                CmdletProviderContext resolvePathContext =
                    new CmdletProviderContext(context);
                resolvePathContext.SetFilters(
                    new Collection<string>(),
                    new Collection<string>(),
                    null);

                // Resolve the path

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

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

                bool pathContainsGlobCharacters = LocationGlobber.StringContainsGlobCharacters(path);
                foreach (string providerPath in providerPaths)
                {
                    // Making sure to obey the StopProcessing.
                    if (context.Stopping)
                    {
                        return;
                    }


                    if ((!pathContainsGlobCharacters || recurse) && IsItemContainer(providerInstance, providerPath, context))
                    {
                        // Since the path contained glob characters or we are recursing and the
                        // path is a container, do the name enumeration manually

                        DoGetChildNamesManually(
                            providerInstance,
                            providerPath,
                            String.Empty,
                            returnContainers,
                            includeMatcher,
                            excludeMatcher,
                            context,
                            recurse,
                            depth);
                    }
                    else
                    {
                        // Since the original path did not contain glob characters, 
                        // if the provider is a NavigationCmdletProvider, write
                        // out the child name, else write out the name as it
                        // was resolved.

                        if (providerInstance is NavigationCmdletProvider)
                        {
                            string childName =
                                GetChildName(
                                    providerInstance,
                                    providerPath,
                                    context, false);

                            bool isIncludeMatch =
                                SessionStateUtilities.MatchesAnyWildcardPattern(
                                    childName,
                                    includeMatcher,
                                    true);

                            bool isExcludeMatch =
                                SessionStateUtilities.MatchesAnyWildcardPattern(
                                    childName,
                                    excludeMatcher,
                                    false);

                            if (isIncludeMatch && !isExcludeMatch)
                            {
                                context.WriteObject(childName);
                            }
                        }
                        else
                        {
                            context.WriteObject(providerPath);
                        }
                    }
                }
            }
            else
            {
                // Figure out which provider to use

                ProviderInfo provider = null;
                PSDriveInfo drive = null;

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

                ContainerCmdletProvider providerInstance = GetContainerProviderInstance(provider);

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

                if (!providerInstance.ItemExists(providerPath, context))
                {
                    ItemNotFoundException pathNotFound =
                        new ItemNotFoundException(
                            providerPath,
                            "PathNotFound",
                            SessionStateStrings.PathNotFound);
                    throw pathNotFound;
                }

                if (recurse)
                {
                    // The path did not contain glob characters but recurse was specified
                    // so do the enumeration manually

                    DoGetChildNamesManually(
                        providerInstance,
                        providerPath,
                        String.Empty,
                        returnContainers,
                        includeMatcher,
                        excludeMatcher,
                        context,
                        recurse,
                        depth);
                }
                else
                {
                    // Since the path did not contain glob characters and recurse wasn't
                    // specified, we can have the provider write out the child names directly

                    GetChildNames(
                        providerInstance,
                        providerPath,
                        returnContainers,
                        context);
                }
            }
        } // GetChildNames
예제 #7
0
        internal string GetDriveRootRelativePathFromPSPath (string path, CmdletProviderContext context, bool escapeCurrentLocation, out PSDriveInfo workingDriveForPath, out CmdletProvider providerInstance)
		{
			if (path == null) {
				throw PSTraceSource.NewArgumentNullException ("path");
			}
			if (OSHelper.IsUnix) {
				int index = path.IndexOf ("::");
				if (index != -1)
				{
					path = path.Substring (index + 2);
				}
			}
            workingDriveForPath = null;
            string driveName = null;
            if (this.sessionState.Drive.Current != null)
            {
                driveName = this.sessionState.Drive.Current.Name;
            }
            bool flag = false;
            if (this.IsAbsolutePath(path, out driveName))
            {
                tracer.WriteLine("Drive Name: {0}", new object[] { driveName });
                try
                {
                    workingDriveForPath = this.sessionState.Drive.Get(driveName);
                }
                catch (DriveNotFoundException)
                {
                    if (this.sessionState.Drive.Current == null)
                    {
                        throw;
                    }
					if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
					{
						flag = path.StartsWith ("/", StringComparison.OrdinalIgnoreCase);
						workingDriveForPath = this.sessionState.Drive.Current;
					}
					else
					{
						string str2 = OSHelper.IsUnix ? this.sessionState.Drive.Current.Root : this.sessionState.Drive.Current.Root.Replace('/', '\\');
						string tempPath = OSHelper.IsUnix ? path : path.Replace('/', '\\');
	                    if ((str2.IndexOf(":", StringComparison.CurrentCulture) >= 0) && tempPath.StartsWith(str2, StringComparison.OrdinalIgnoreCase))
	                    {
	                        flag = true;
							if (!OSHelper.IsUnix) {
		                        path = path.Substring(str2.Length);
		                        path = path.TrimStart(new char[] { '\\' });
		                        path = '\\' + path;
							}
	                        workingDriveForPath = this.sessionState.Drive.Current;
	                    }
	                    if (!flag)
	                    {
	                        throw;
	                    }
					}
                }
				if (!flag) /* && !OSHelper.IsUnix */
                {
                    path = path.Substring(driveName.Length + 1);
                }
            }
            else
            {
                workingDriveForPath = this.sessionState.Drive.Current;
            }
            if (workingDriveForPath == null)
            {
                ItemNotFoundException exception = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound);
                pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { path });
                throw exception;
            }
            try
            {
                providerInstance = this.sessionState.Internal.GetContainerProviderInstance(workingDriveForPath.Provider);
                context.Drive = workingDriveForPath;
                return this.GenerateRelativePath(workingDriveForPath, path, escapeCurrentLocation, providerInstance, context);
            }
            catch (PSNotSupportedException)
            {
                providerInstance = null;
                return "";
            }
        }
예제 #8
0
 private Collection<PathInfo> ResolveDriveQualifiedPath(string path, CmdletProviderContext context, bool allowNonexistingPaths, out CmdletProvider providerInstance)
 {
     providerInstance = null;
     PSDriveInfo workingDriveForPath = null;
     Collection<PathInfo> collection = new Collection<PathInfo>();
     pathResolutionTracer.WriteLine("Path is DRIVE-QUALIFIED", new object[0]);
     string str = this.GetDriveRootRelativePathFromPSPath(path, context, true, out workingDriveForPath, out providerInstance);
     pathResolutionTracer.WriteLine("DRIVE-RELATIVE path: {0}", new object[] { str });
     pathResolutionTracer.WriteLine("Drive: {0}", new object[] { workingDriveForPath.Name });
     pathResolutionTracer.WriteLine("Provider: {0}", new object[] { workingDriveForPath.Provider });
     context.Drive = workingDriveForPath;
     providerInstance = this.sessionState.Internal.GetContainerProviderInstance(workingDriveForPath.Provider);
     ContainerCmdletProvider provider = providerInstance as ContainerCmdletProvider;
     ItemCmdletProvider provider2 = providerInstance as ItemCmdletProvider;
     ProviderInfo providerInfo = providerInstance.ProviderInfo;
     string item = null;
     string providerPath = null;
     if (workingDriveForPath.Hidden)
     {
         item = GetProviderQualifiedPath(str, providerInfo);
         providerPath = str;
     }
     else
     {
         item = GetDriveQualifiedPath(str, workingDriveForPath);
         providerPath = this.GetProviderPath(path, context);
     }
     pathResolutionTracer.WriteLine("PROVIDER path: {0}", new object[] { providerPath });
     Collection<string> collection2 = new Collection<string>();
     if (!context.SuppressWildcardExpansion)
     {
         if (CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.ExpandWildcards, providerInfo))
         {
             pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider.", new object[0]);
             if ((provider2 != null) && WildcardPattern.ContainsWildcardCharacters(str))
             {
                 foreach (string str4 in provider2.ExpandPath(providerPath, context))
                 {
                     collection2.Add(this.GetDriveRootRelativePathFromProviderPath(str4, workingDriveForPath, context));
                 }
             }
             else
             {
                 collection2.Add(this.GetDriveRootRelativePathFromProviderPath(providerPath, workingDriveForPath, context));
             }
         }
         else
         {
             pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine.", new object[0]);
             collection2 = this.ExpandMshGlobPath(str, allowNonexistingPaths, workingDriveForPath, provider, context);
         }
     }
     else if (provider2 != null)
     {
         if (allowNonexistingPaths || provider2.ItemExists(providerPath, context))
         {
             collection2.Add(item);
         }
     }
     else
     {
         collection2.Add(item);
     }
     if ((((!allowNonexistingPaths && (collection2.Count < 1)) && !WildcardPattern.ContainsWildcardCharacters(path)) && ((context.Include == null) || (context.Include.Count == 0))) && ((context.Exclude == null) || (context.Exclude.Count == 0)))
     {
         ItemNotFoundException exception = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound);
         pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { path });
         throw exception;
     }
     foreach (string str5 in collection2)
     {
         if (context.Stopping)
         {
             throw new PipelineStoppedException();
         }
         item = null;
         if (workingDriveForPath.Hidden)
         {
             if (IsProviderDirectPath(str5))
             {
                 item = str5;
             }
             else
             {
                 item = GetProviderQualifiedPath(str5, providerInfo);
             }
         }
         else
         {
             item = GetDriveQualifiedPath(str5, workingDriveForPath);
         }
         collection.Add(new PathInfo(workingDriveForPath, providerInfo, item, this.sessionState));
         pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { item });
     }
     return collection;
 }
예제 #9
0
        private Collection<string> ExpandMshGlobPath(string path, bool allowNonexistingPaths, PSDriveInfo drive, ContainerCmdletProvider provider, CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }
            if (provider == null)
            {
                throw PSTraceSource.NewArgumentNullException("provider");
            }
            if (drive == null)
            {
                throw PSTraceSource.NewArgumentNullException("drive");
            }
            tracer.WriteLine("path = {0}", new object[] { path });
            NavigationCmdletProvider provider2 = provider as NavigationCmdletProvider;
            Collection<string> collection = new Collection<string>();
            using (pathResolutionTracer.TraceScope("EXPANDING WILDCARDS", new object[0]))
            {
                if (ShouldPerformGlobbing(path, context))
                {
                    StringCollection currentDirs = new StringCollection();
                    Stack<string> stack = new Stack<string>();
                    using (pathResolutionTracer.TraceScope("Tokenizing path", new object[0]))
                    {
                        while (StringContainsGlobCharacters(path))
                        {
                            if (context.Stopping)
                            {
                                throw new PipelineStoppedException();
                            }
                            string childName = path;
                            if (provider2 != null)
                            {
                                childName = provider2.GetChildName(path, context);
                            }
                            if (string.IsNullOrEmpty(childName))
                            {
                                break;
                            }
                            tracer.WriteLine("Pushing leaf element: {0}", new object[] { childName });
                            pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { childName });
                            stack.Push(childName);
                            if (provider2 != null)
                            {
                                string a = provider2.GetParentPath(path, drive.Root, context);
                                if (string.Equals(a, path, StringComparison.OrdinalIgnoreCase))
                                {
                                    throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "ProviderImplementationInconsistent", new object[] { provider.ProviderInfo.Name, path });
                                }
                                path = a;
                            }
                            else
                            {
                                path = string.Empty;
                            }
                            tracer.WriteLine("New path: {0}", new object[] { path });
                            pathResolutionTracer.WriteLine("Parent path: {0}", new object[] { path });
                        }
                        tracer.WriteLine("Base container path: {0}", new object[] { path });
                        if (stack.Count == 0)
                        {
                            string str3 = path;
                            if (provider2 != null)
                            {
                                str3 = provider2.GetChildName(path, context);
                                if (!string.IsNullOrEmpty(str3))
                                {
                                    path = provider2.GetParentPath(path, null, context);
                                }
                            }
                            else
                            {
                                path = string.Empty;
                            }
                            stack.Push(str3);
                            pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { str3 });
                        }
                        pathResolutionTracer.WriteLine("Root path of resolution: {0}", new object[] { path });
                    }
                    currentDirs.Add(path);
                    while (stack.Count > 0)
                    {
                        if (context.Stopping)
                        {
                            throw new PipelineStoppedException();
                        }
                        string leafElement = stack.Pop();
                        currentDirs = this.GenerateNewPSPathsWithGlobLeaf(currentDirs, drive, leafElement, stack.Count == 0, provider, context);
                        if (stack.Count > 0)
                        {
                            using (pathResolutionTracer.TraceScope("Checking matches to ensure they are containers", new object[0]))
                            {
                                int index = 0;
                                while (index < currentDirs.Count)
                                {
                                    if (context.Stopping)
                                    {
                                        throw new PipelineStoppedException();
                                    }
                                    string mshQualifiedPath = GetMshQualifiedPath(currentDirs[index], drive);
                                    if ((provider2 != null) && !this.sessionState.Internal.IsItemContainer(mshQualifiedPath, context))
                                    {
                                        tracer.WriteLine("Removing {0} because it is not a container", new object[] { currentDirs[index] });
                                        pathResolutionTracer.WriteLine("{0} is not a container", new object[] { currentDirs[index] });
                                        currentDirs.RemoveAt(index);
                                    }
                                    else if (provider2 != null)
                                    {
                                        pathResolutionTracer.WriteLine("{0} is a container", new object[] { currentDirs[index] });
                                        index++;
                                    }
                                }
                                continue;
                            }
                        }
                    }
                    foreach (string str6 in currentDirs)
                    {
                        pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str6 });
                        collection.Add(str6);
                    }
                    return collection;
                }
                string str7 = context.SuppressWildcardExpansion ? path : RemoveGlobEscaping(path);
				string format = OSHelper.IsUnix && provider.GetType () == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) ? (str7.StartsWith ("/") ? "{1}" : "{0}/{1}") : "{0}:" + '\\' + "{1}";
                if (drive.Hidden)
                {
                    if (IsProviderDirectPath(str7))
                    {
                        format = "{1}";
                    }
                    else
                    {
                        format = "{0}::{1}";
                    }
                }
                else
                {
					char ch = OSHelper.IsUnix && provider.GetType () == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) ? '/' : '\\';
                    if (path.StartsWith(ch.ToString(), StringComparison.Ordinal))
                    {
						format = OSHelper.IsUnix && provider.GetType () == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) ? "{1}" : "{0}:{1}";
                    }
                }
                string str9 = string.Format(CultureInfo.InvariantCulture, format, new object[] { drive.Name, str7 });
                if (allowNonexistingPaths || provider.ItemExists(this.GetProviderPath(str9, context), context))
                {
                    pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str9 });
                    collection.Add(str9);
                    return collection;
                }
                ItemNotFoundException exception2 = new ItemNotFoundException(str9, "PathNotFound", SessionStateStrings.PathNotFound);
                pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { path });
                throw exception2;
            }
        }
예제 #10
0
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        /// 
        protected override void ProcessRecord()
        {
            // First get the alias table (from the proper scope if necessary)
            IDictionary<string, AliasInfo> aliasTable = null;

            if (!String.IsNullOrEmpty(Scope))
            {
                // This can throw PSArgumentException and PSArgumentOutOfRangeException
                // but just let them go as this is terminal for the pipeline and the
                // exceptions are already properly adorned with an ErrorRecord.

                aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope);
            }
            else
            {
                aliasTable = SessionState.Internal.GetAliasTable();
            }

            foreach (string aliasName in _names)
            {
                bool resultFound = false;

                // Create the name pattern

                WildcardPattern namePattern =
                    WildcardPattern.Get(
                        aliasName,
                        WildcardOptions.IgnoreCase);

                // Now loop through the table and write out any aliases that
                // match the name and don't match the exclude filters and are
                // visible to the caller...
                CommandOrigin origin = MyInvocation.CommandOrigin;
                foreach (KeyValuePair<string, AliasInfo> tableEntry in aliasTable)
                {
                    if (!namePattern.IsMatch(tableEntry.Key))
                    {
                        continue;
                    }

                    if (SessionState.IsVisible(origin, tableEntry.Value))
                    {
                        resultFound = true;
                        _matchingAliases.Add(tableEntry.Value);
                    }
                }

                if (!resultFound &&
                    !WildcardPattern.ContainsWildcardCharacters(aliasName))
                {
                    // Need to write an error if the user tries to get an alias
                    // that doesn't exist and they are not globbing.

                    ItemNotFoundException itemNotFound =
                        new ItemNotFoundException(
                            aliasName,
                            "AliasNotFound",
                            SessionStateStrings.AliasNotFound);

                    WriteError(
                        new ErrorRecord(
                            itemNotFound.ErrorRecord,
                            itemNotFound));
                }
            }
        } // ProcessRecord
예제 #11
0
파일: Var.cs 프로젝트: 40a/PowerShell
        /// <summary>
        /// The implementation of the Clear-Variable command
        /// </summary>
        /// 
        protected override void ProcessRecord()
        {
            foreach (string varName in Name)
            {
                bool wasFiltered = false;

                List<PSVariable> matchingVariables =
                    GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false);

                if (matchingVariables.Count == 0 && !wasFiltered)
                {
                    // Since the variable wasn't found and no glob
                    // characters were specified, write an error.

                    ItemNotFoundException itemNotFound =
                        new ItemNotFoundException(
                            varName,
                            "VariableNotFound",
                            SessionStateStrings.VariableNotFound);

                    WriteError(
                        new ErrorRecord(
                            itemNotFound.ErrorRecord,
                            itemNotFound));

                    continue;
                }

                foreach (PSVariable matchingVariable in matchingVariables)
                {
                    // Since the variable doesn't exist or -Force was specified,
                    // Call should process to validate the set with the user.

                    string action = VariableCommandStrings.ClearVariableAction;

                    string target = StringUtil.Format(VariableCommandStrings.ClearVariableTarget, matchingVariable.Name);

                    if (ShouldProcess(target, action))
                    {
                        PSVariable result = matchingVariable;

                        try
                        {
                            if (_force &&
                                (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0)
                            {
                                // Remove the ReadOnly bit to set the value and then reapply

                                matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true);

                                result = ClearValue(matchingVariable);

                                matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true);
                            }
                            else
                            {
                                result = ClearValue(matchingVariable);
                            }
                        }
                        catch (SessionStateException sessionStateException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    sessionStateException.ErrorRecord,
                                    sessionStateException));
                            continue;
                        }
                        catch (PSArgumentException argException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    argException.ErrorRecord,
                                    argException));
                            continue;
                        }

                        if (_passThru)
                        {
                            WriteObject(result);
                        }
                    }
                }
            }
        } // ProcessRecord
예제 #12
0
        } // LocationStack

        /// <summary>
        /// Sets the default stack ID to the specified stack ID
        /// </summary>
        ///
        /// <param name="stackName">
        /// The stack ID to be used as the default.
        /// </param>
        ///
        /// <returns>
        /// The PathInfoStack for the new default stack or null if the
        /// stack does not exist yet.
        /// </returns>
        ///
        /// <exception cref="ItemNotFoundException">
        /// If <paramref name="stackName"/> does not exist as a location stack.
        /// </exception>
        /// 
        internal PathInfoStack SetDefaultLocationStack(string stackName)
        {
            if (String.IsNullOrEmpty(stackName))
            {
                stackName = startingDefaultStackName;
            }

            if (!_workingLocationStack.ContainsKey(stackName))
            {
                if (String.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase))
                {
                    // Since the "default" stack must always exist, create it here
                    return new PathInfoStack(startingDefaultStackName, new Stack<PathInfo>());
                }

                ItemNotFoundException itemNotFound =
                    new ItemNotFoundException(
                        stackName,
                        "StackNotFound",
                        SessionStateStrings.PathNotFound);

                throw itemNotFound;
            }

            _defaultStackName = stackName;

            Stack<PathInfo> locationStack = _workingLocationStack[_defaultStackName];

            if (locationStack != null)
            {
                return new PathInfoStack(_defaultStackName, locationStack);
            }
            return null;
        } // SetDefaultLocationStack
예제 #13
0
        } // ProcessRecord
        #endregion Command code

        private void WriteMatches(string value, string parametersetname)
        {
            // First get the alias table (from the proper scope if necessary)
            IDictionary<string, AliasInfo> aliasTable = null;

            //get the command origin
            CommandOrigin origin = MyInvocation.CommandOrigin;
            string displayString = "name";
            if (!String.IsNullOrEmpty(Scope))
            {
                // This can throw PSArgumentException and PSArgumentOutOfRangeException
                // but just let them go as this is terminal for the pipeline and the
                // exceptions are already properly adorned with an ErrorRecord.

                aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope);
            }
            else
            {
                aliasTable = SessionState.Internal.GetAliasTable();
            }



            bool matchfound = false;
            bool ContainsWildcard = WildcardPattern.ContainsWildcardCharacters(value);
            WildcardPattern wcPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase);

            // excluding patter for Default paramset.
            Collection<WildcardPattern> excludePatterns =
                      SessionStateUtilities.CreateWildcardsFromStrings(
                          _excludes,
                          WildcardOptions.IgnoreCase);

            List<AliasInfo> results = new List<AliasInfo>();
            foreach (KeyValuePair<string, AliasInfo> tableEntry in aliasTable)
            {
                if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase))
                {
                    displayString = "definition";
                    if (!wcPattern.IsMatch(tableEntry.Value.Definition))
                    {
                        continue;
                    }
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Value.Definition, excludePatterns, false))
                    {
                        continue;
                    }
                }
                else
                {
                    if (!wcPattern.IsMatch(tableEntry.Key))
                    {
                        continue;
                    }
                    //excludes pattern
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Key, excludePatterns, false))
                    {
                        continue;
                    }
                }
                if (ContainsWildcard)
                {
                    // Only write the command if it is visible to the requestor
                    if (SessionState.IsVisible(origin, tableEntry.Value))
                    {
                        matchfound = true;
                        results.Add(tableEntry.Value);
                    }
                }
                else
                {
                    // For specifically named elements, generate an error for elements that aren't visible...
                    try
                    {
                        SessionState.ThrowIfNotVisible(origin, tableEntry.Value);
                        results.Add(tableEntry.Value);
                        matchfound = true;
                    }
                    catch (SessionStateException sessionStateException)
                    {
                        WriteError(
                            new ErrorRecord(
                                sessionStateException.ErrorRecord,
                                sessionStateException));
                        // Even though it resulted in an error, a result was found
                        // so we don't want to generate the nothing found error
                        // at the end...
                        matchfound = true;
                        continue;
                    }
                }
            }

            results.Sort(
                delegate (AliasInfo left, AliasInfo right)
                {
                    return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name);
                });
            foreach (AliasInfo alias in results)
            {
                this.WriteObject(alias);
            }

            if (!matchfound && !ContainsWildcard && (excludePatterns == null || excludePatterns.Count == 0))
            {
                // Need to write an error if the user tries to get an alias
                // tat doesn't exist and they are not globbing.

                ItemNotFoundException itemNotFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value));
                ErrorRecord er = new ErrorRecord(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value);
                WriteError(er);
            }
        }
예제 #14
0
 private void WriteMatches(string value, string parametersetname)
 {
     IDictionary<string, AliasInfo> aliasTableAtScope = null;
     CommandOrigin commandOrigin = base.MyInvocation.CommandOrigin;
     string str = "name";
     if (!string.IsNullOrEmpty(this.scope))
     {
         aliasTableAtScope = base.SessionState.Internal.GetAliasTableAtScope(this.scope);
     }
     else
     {
         aliasTableAtScope = base.SessionState.Internal.GetAliasTable();
     }
     bool flag = false;
     bool flag2 = WildcardPattern.ContainsWildcardCharacters(value);
     WildcardPattern pattern = new WildcardPattern(value, WildcardOptions.IgnoreCase);
     Collection<WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(this.excludes, WildcardOptions.IgnoreCase);
     List<AliasInfo> list = new List<AliasInfo>();
     foreach (KeyValuePair<string, AliasInfo> pair in aliasTableAtScope)
     {
         if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase))
         {
             str = "definition";
             if (pattern.IsMatch(pair.Value.Definition) && !SessionStateUtilities.MatchesAnyWildcardPattern(pair.Value.Definition, patterns, false))
             {
                 goto Label_00EE;
             }
             continue;
         }
         if (!pattern.IsMatch(pair.Key) || SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, patterns, false))
         {
             continue;
         }
     Label_00EE:
         if (flag2)
         {
             if (SessionState.IsVisible(commandOrigin, (CommandInfo) pair.Value))
             {
                 flag = true;
                 list.Add(pair.Value);
             }
         }
         else
         {
             try
             {
                 SessionState.ThrowIfNotVisible(commandOrigin, pair.Value);
                 list.Add(pair.Value);
                 flag = true;
             }
             catch (SessionStateException exception)
             {
                 base.WriteError(new ErrorRecord(exception.ErrorRecord, exception));
                 flag = true;
             }
         }
     }
     list.Sort((Comparison<AliasInfo>) ((left, right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)));
     foreach (AliasInfo info in list)
     {
         base.WriteObject(info);
     }
     if ((!flag && !flag2) && ((patterns == null) || (patterns.Count == 0)))
     {
         ItemNotFoundException exception2 = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, str, value));
         ErrorRecord errorRecord = new ErrorRecord(exception2, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value);
         base.WriteError(errorRecord);
     }
 }
예제 #15
0
 internal object SetVariable(VariablePath variablePath, object newValue, bool asValue, bool force, CommandOrigin origin)
 {
     if (variablePath == null)
     {
         throw PSTraceSource.NewArgumentNullException("variablePath");
     }
     CmdletProviderContext context = null;
     SessionStateScope currentScope = null;
     if (variablePath.IsVariable)
     {
         if (variablePath.IsLocal || variablePath.IsUnscopedVariable)
         {
             currentScope = this.currentScope;
         }
         else if (variablePath.IsScript)
         {
             currentScope = this.currentScope.ScriptScope;
         }
         else if (variablePath.IsGlobal)
         {
             currentScope = this._globalScope;
         }
         else if (variablePath.IsPrivate)
         {
             currentScope = this.currentScope;
         }
         PSVariable variable = currentScope.SetVariable(variablePath.QualifiedName, newValue, asValue, force, this, origin, false);
         if (variablePath.IsPrivate && (variable != null))
         {
             variable.Options |= ScopedItemOptions.Private;
         }
         return variable;
     }
     this.GetVariableValue(variablePath, out context, out currentScope);
     Collection<IContentWriter> contentWriter = null;
     try
     {
         if (context != null)
         {
             try
             {
                 CmdletProviderContext context2 = new CmdletProviderContext(context);
                 this.ClearContent(new string[] { variablePath.QualifiedName }, context2);
             }
             catch (NotSupportedException)
             {
             }
             catch (ItemNotFoundException)
             {
             }
             contentWriter = this.GetContentWriter(new string[] { variablePath.QualifiedName }, context);
             context.ThrowFirstErrorOrDoNothing(true);
         }
         else
         {
             try
             {
                 this.ClearContent(new string[] { variablePath.QualifiedName }, false, false);
             }
             catch (NotSupportedException)
             {
             }
             catch (ItemNotFoundException)
             {
             }
             contentWriter = this.GetContentWriter(new string[] { variablePath.QualifiedName }, false, false);
         }
     }
     catch (NotImplementedException exception)
     {
         ProviderInfo provider = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out provider);
         throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, provider, variablePath.QualifiedName, exception, false);
     }
     catch (NotSupportedException exception2)
     {
         ProviderInfo info2 = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out info2);
         throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, info2, variablePath.QualifiedName, exception2, false);
     }
     if ((contentWriter == null) || (contentWriter.Count == 0))
     {
         ItemNotFoundException exception3 = new ItemNotFoundException(variablePath.QualifiedName, "PathNotFound", SessionStateStrings.PathNotFound);
         throw exception3;
     }
     if (contentWriter.Count > 1)
     {
         foreach (IContentWriter writer in contentWriter)
         {
             writer.Close();
         }
         PSArgumentException e = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "VariablePathResolvedToMultiple", new object[] { variablePath.QualifiedName });
         ProviderInfo info3 = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out info3);
         throw this.NewProviderInvocationException("ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, info3, variablePath.QualifiedName, e);
     }
     IContentWriter writer2 = contentWriter[0];
     IList content = newValue as IList;
     if (content == null)
     {
         content = new object[] { newValue };
     }
     try
     {
         writer2.Write(content);
     }
     catch (Exception exception5)
     {
         ProviderInfo info4 = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out info4);
         CommandProcessorBase.CheckForSevereException(exception5);
         ProviderInvocationException exception6 = new ProviderInvocationException("ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, info4, variablePath.QualifiedName, exception5);
         throw exception6;
     }
     finally
     {
         writer2.Close();
     }
     return null;
 }
예제 #16
0
 internal PathInfoStack SetDefaultLocationStack(string stackName)
 {
     if (string.IsNullOrEmpty(stackName))
     {
         stackName = "default";
     }
     if (!this.workingLocationStack.ContainsKey(stackName))
     {
         if (string.Equals(stackName, "default", StringComparison.OrdinalIgnoreCase))
         {
             return new PathInfoStack("default", new Stack<PathInfo>());
         }
         ItemNotFoundException exception = new ItemNotFoundException(stackName, "StackNotFound", SessionStateStrings.PathNotFound);
         throw exception;
     }
     this.defaultStackName = stackName;
     Stack<PathInfo> locationStack = this.workingLocationStack[this.defaultStackName];
     if (locationStack != null)
     {
         return new PathInfoStack(this.defaultStackName, locationStack);
     }
     return null;
 }
예제 #17
0
 internal void GetChildNames(string path, ReturnContainers returnContainers, bool recurse, CmdletProviderContext context)
 {
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     Collection<WildcardPattern> includeMatcher = SessionStateUtilities.CreateWildcardsFromStrings(context.Include, WildcardOptions.IgnoreCase);
     Collection<WildcardPattern> excludeMatcher = SessionStateUtilities.CreateWildcardsFromStrings(context.Exclude, WildcardOptions.IgnoreCase);
     if (LocationGlobber.ShouldPerformGlobbing(path, context))
     {
         ProviderInfo info = null;
         CmdletProvider providerInstance = null;
         CmdletProviderContext context2 = new CmdletProviderContext(context);
         context2.SetFilters(new Collection<string>(), new Collection<string>(), null);
         Collection<string> collection3 = this.Globber.GetGlobbedProviderPathsFromMonadPath(path, false, context2, out info, out providerInstance);
         if (context2.Drive != null)
         {
             context.Drive = context2.Drive;
         }
         bool flag = LocationGlobber.StringContainsGlobCharacters(path);
         foreach (string str in collection3)
         {
             if (context.Stopping)
             {
                 break;
             }
             if ((!flag || recurse) && this.IsItemContainer(providerInstance, str, context))
             {
                 this.DoGetChildNamesManually(providerInstance, str, string.Empty, returnContainers, includeMatcher, excludeMatcher, context, recurse);
             }
             else if (providerInstance is NavigationCmdletProvider)
             {
                 string text = this.GetChildName(providerInstance, str, context, false);
                 bool flag2 = SessionStateUtilities.MatchesAnyWildcardPattern(text, includeMatcher, true);
                 bool flag3 = SessionStateUtilities.MatchesAnyWildcardPattern(text, excludeMatcher, false);
                 if (flag2 && !flag3)
                 {
                     context.WriteObject(text);
                 }
             }
             else
             {
                 context.WriteObject(str);
             }
         }
     }
     else
     {
         ProviderInfo provider = null;
         PSDriveInfo drive = null;
         string str3 = this.Globber.GetProviderPath(path, context, out provider, out drive);
         ContainerCmdletProvider containerProviderInstance = this.GetContainerProviderInstance(provider);
         if (drive != null)
         {
             context.Drive = drive;
         }
         if (!containerProviderInstance.ItemExists(str3, context))
         {
             ItemNotFoundException exception = new ItemNotFoundException(str3, "PathNotFound", SessionStateStrings.PathNotFound);
             throw exception;
         }
         if (recurse)
         {
             this.DoGetChildNamesManually(containerProviderInstance, str3, string.Empty, returnContainers, includeMatcher, excludeMatcher, context, recurse);
         }
         else
         {
             this.GetChildNames(containerProviderInstance, str3, returnContainers, context);
         }
     }
 }
예제 #18
0
 internal void GetChildItems(string path, bool recurse, CmdletProviderContext context)
 {
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     if (context == null)
     {
         throw PSTraceSource.NewArgumentNullException("context");
     }
     ProviderInfo info = null;
     if (recurse || LocationGlobber.ShouldPerformGlobbing(path, context))
     {
         bool flag = false;
         try
         {
             if ((recurse && ((context.Include == null) || (context.Include.Count == 0))) && (!string.IsNullOrEmpty(path) && !this.IsItemContainer(path)))
             {
                 string childName = this.GetChildName(path, context);
                 if (!string.Equals(childName, "*", StringComparison.OrdinalIgnoreCase) && (context.Include != null))
                 {
                     context.Include.Add(childName);
                     flag = true;
                 }
                 path = path.Substring(0, path.Length - childName.Length);
             }
             Collection<string> include = context.Include;
             Collection<string> exclude = context.Exclude;
             string filter = context.Filter;
             if (recurse)
             {
                 context.SetFilters(new Collection<string>(), new Collection<string>(), null);
             }
             CmdletProvider providerInstance = null;
             Collection<string> collection3 = null;
             try
             {
                 collection3 = this.Globber.GetGlobbedProviderPathsFromMonadPath(path, false, context, out info, out providerInstance);
             }
             finally
             {
                 context.SetFilters(include, exclude, filter);
             }
             if (recurse)
             {
                 this.GetContainerProviderInstance(info);
             }
             bool flag2 = !LocationGlobber.StringContainsGlobCharacters(path);
             if ((((recurse && !flag2) && ((include != null) && (include.Count == 0))) || ((include != null) && (include.Count > 0))) || ((exclude != null) && (exclude.Count > 0)))
             {
                 foreach (string str4 in collection3)
                 {
                     if (context.Stopping)
                     {
                         return;
                     }
                     this.DoManualGetChildItems(providerInstance, str4, recurse, context, false);
                 }
             }
             else
             {
                 foreach (string str5 in collection3)
                 {
                     if (context.Stopping)
                     {
                         return;
                     }
                     if ((flag2 || recurse) && this.IsItemContainer(providerInstance, str5, context))
                     {
                         this.GetChildItems(providerInstance, str5, recurse, context);
                     }
                     else
                     {
                         this.GetItemPrivate(providerInstance, str5, context);
                     }
                 }
             }
         }
         finally
         {
             if (flag)
             {
                 context.Include.Clear();
             }
         }
     }
     else
     {
         PSDriveInfo drive = null;
         path = this.Globber.GetProviderPath(path, context, out info, out drive);
         if (drive != null)
         {
             context.Drive = drive;
         }
         ContainerCmdletProvider containerProviderInstance = this.GetContainerProviderInstance(info);
         if ((path != null) && this.ItemExists(containerProviderInstance, path, context))
         {
             if (this.IsItemContainer(containerProviderInstance, path, context))
             {
                 this.GetChildItems(containerProviderInstance, path, recurse, context);
             }
             else
             {
                 this.GetItemPrivate(containerProviderInstance, path, context);
             }
         }
         else
         {
             ItemNotFoundException exception = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound);
             throw exception;
         }
     }
 }
예제 #19
0
파일: Var.cs 프로젝트: 40a/PowerShell
        /// <summary>
        /// Removes the matching variables from the specified scope
        /// </summary>
        /// 
        protected override void ProcessRecord()
        {
            // Removal of variables only happens in the local scope if the
            // scope wasn't explicitly specified by the user.

            if (Scope == null)
            {
                Scope = "local";
            }


            foreach (string varName in Name)
            {
                // First look for existing variables to set.
                bool wasFiltered = false;

                List<PSVariable> matchingVariables =
                    GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false);

                if (matchingVariables.Count == 0 && !wasFiltered)
                {
                    // Since the variable wasn't found and no glob
                    // characters were specified, write an error.

                    ItemNotFoundException itemNotFound =
                        new ItemNotFoundException(
                            varName,
                            "VariableNotFound",
                            SessionStateStrings.VariableNotFound);

                    WriteError(
                        new ErrorRecord(
                            itemNotFound.ErrorRecord,
                            itemNotFound));

                    continue;
                }

                foreach (PSVariable matchingVariable in matchingVariables)
                {
                    // Since the variable doesn't exist or -Force was specified,
                    // Call should process to validate the set with the user.

                    string action = VariableCommandStrings.RemoveVariableAction;

                    string target = StringUtil.Format(VariableCommandStrings.RemoveVariableTarget, matchingVariable.Name);

                    if (ShouldProcess(target, action))
                    {
                        try
                        {
                            if (String.IsNullOrEmpty(Scope))
                            {
                                SessionState.Internal.RemoveVariable(matchingVariable, _force);
                            }
                            else
                            {
                                SessionState.Internal.RemoveVariableAtScope(matchingVariable, Scope, _force);
                            }
                        }
                        catch (SessionStateException sessionStateException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    sessionStateException.ErrorRecord,
                                    sessionStateException));
                        }
                        catch (PSArgumentException argException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    argException.ErrorRecord,
                                    argException));
                        }
                    }
                }
            }
        } // ProcessRecord
예제 #20
0
        } // GetGlobbedMonadPathsFromMonadPath

        /// <summary>
        /// Converts a PowerShell path containing glob characters to PowerShell paths that match
        /// the glob string.
        /// </summary>
        /// 
        /// <param name="path">
        /// A PowerShell path containing glob characters.
        /// </param>
        /// 
        /// <param name="allowNonexistingPaths">
        /// If true, a ItemNotFoundException will not be thrown for non-existing
        /// paths. Instead an appropriate path will be returned as if it did exist.
        /// </param>
        /// 
        /// <param name="context">
        /// The context under which the command is running.
        /// </param>
        /// 
        /// <param name="providerInstance">
        /// The instance of the provider used to resolve the path.
        /// </param>
        /// 
        /// <returns>
        /// The PowerShell paths that match the glob string.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> or <paramref name="context"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ProviderNotFoundException">
        /// If <paramref name="path"/> is a provider-qualified path 
        /// and the specified provider does not exist.
        /// </exception>
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider throws an exception when its MakePath gets
        /// called.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider does not support multiple items.
        /// </exception>
        /// 
        /// <exception cref="InvalidOperationException">
        /// If the home location for the provider is not set and
        /// <paramref name="path"/> starts with a "~".
        /// </exception>
        /// 
        /// <exception cref="ItemNotFoundException">
        /// If <paramref name="path"/> does not contain glob characters and
        /// could not be found.
        /// </exception>
        /// 
        /// <exception cref="PipelineStoppedException">
        /// If <paramref name="context"/> has been signaled for
        /// StopProcessing.
        /// </exception>
        /// 
        internal Collection<PathInfo> GetGlobbedMonadPathsFromMonadPath(
            string path,
            bool allowNonexistingPaths,
            CmdletProviderContext context,
            out CmdletProvider providerInstance)
        {
            providerInstance = null;
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

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

            Collection<PathInfo> result;

            using (s_pathResolutionTracer.TraceScope("Resolving MSH path \"{0}\" to MSH path", path))
            {
                TraceFilters(context);

                // First check to see if the path starts with a ~ (home)

                if (IsHomePath(path))
                {
                    using (s_pathResolutionTracer.TraceScope("Resolving HOME relative path."))
                    {
                        path = GetHomeRelativePath(path);
                    }
                }

                // Now determine how to parse the path

                bool isProviderDirectPath = IsProviderDirectPath(path);
                bool isProviderQualifiedPath = IsProviderQualifiedPath(path);
                if (isProviderDirectPath || isProviderQualifiedPath)
                {
                    result =
                        ResolvePSPathFromProviderPath(
                            path,
                            context,
                            allowNonexistingPaths,
                            isProviderDirectPath,
                            isProviderQualifiedPath,
                            out providerInstance);
                }
                else
                {
                    result =
                        ResolveDriveQualifiedPath(
                            path,
                            context,
                            allowNonexistingPaths,
                            out providerInstance);
                }

                if (!allowNonexistingPaths &&
                    result.Count < 1 &&
                    !WildcardPattern.ContainsWildcardCharacters(path) &&
                    (context.Include == null || context.Include.Count == 0) &&
                    (context.Exclude == null || context.Exclude.Count == 0))
                {
                    // Since we are not globbing, throw an exception since
                    // the path doesn't exist

                    ItemNotFoundException pathNotFound =
                        new ItemNotFoundException(
                            path,
                            "PathNotFound",
                            SessionStateStrings.PathNotFound);

                    s_pathResolutionTracer.TraceError("Item does not exist: {0}", path);

                    throw pathNotFound;
                }
            }
            return result;
        } // GetGlobbedMonadPathsFromMonadPath
예제 #21
0
파일: Var.cs 프로젝트: 40a/PowerShell
        /// <summary>
        /// Implements ProcessRecord() method for get-variable's command.
        /// </summary>
        protected override void ProcessRecord()
        {
            foreach (string varName in _name)
            {
                bool wasFiltered = false;
                List<PSVariable> matchingVariables =
                    GetMatchingVariables(varName, Scope, out wasFiltered, /*quiet*/ false);

                matchingVariables.Sort(
                    delegate (PSVariable left, PSVariable right)
                    {
                        return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name);
                    });

                bool matchFound = false;
                foreach (PSVariable matchingVariable in matchingVariables)
                {
                    matchFound = true;
                    if (_valueOnly)
                    {
                        WriteObject(matchingVariable.Value);
                    }
                    else
                    {
                        WriteObject(matchingVariable);
                    }
                }

                if (!matchFound && !wasFiltered)
                {
                    ItemNotFoundException itemNotFound =
                        new ItemNotFoundException(
                            varName,
                            "VariableNotFound",
                            SessionStateStrings.VariableNotFound);

                    WriteError(
                        new ErrorRecord(
                            itemNotFound.ErrorRecord,
                            itemNotFound));
                }
            }
        }
예제 #22
0
        } // IsShellVirtualDrive

        /// <summary>
        /// Gets a provider specific path that represents the specified path and is relative
        /// to the root of the PowerShell drive.
        /// </summary>
        /// 
        /// <param name="path">
        /// Can be a relative or absolute path.
        /// </param>
        /// 
        /// <param name="context">
        /// The context which the core command is running.
        /// </param>
        /// 
        /// <param name="escapeCurrentLocation">
        /// Escape the wildcards in the current location.  Use when this path will be
        /// passed through globbing.
        /// </param>
        /// 
        /// <param name="workingDriveForPath">
        /// This out parameter returns the drive that was specified
        /// by the <paramref name="path" />. If <paramref name="path"/> is
        /// an absolute path this value may be something other than
        /// the current working drive.
        /// 
        /// If the path refers to a non-existent drive, this parameter is set to null, and an exception is thrown.
        /// 
        /// </param>
        /// 
        /// <param name="providerInstance">
        /// The provider instance that was used.
        /// </param>
        /// 
        /// <returns>
        /// A  provider specific relative path to the root of the drive.
        /// </returns>
        /// 
        /// <remarks>
        /// The path is parsed to determine if it is a relative path to the
        /// current working drive or if it is an absolute path. If
        /// it is a relative path the provider specific path is generated using the current
        /// working directory, the drive root, and the path specified.
        /// If the path is an absolute path the provider specific path is generated by stripping
        /// of anything before the : and using that to find the appropriate
        /// drive. The provider specific path is then generated the same as the
        /// relative path using the specified drive instead of the
        /// current working drive.
        /// 
        /// This is internal so that it can be called from SessionState
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path" /> is null.
        /// </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 specified by <paramref name="providerId"/> threw an
        /// exception when its GetParentPath or MakePath was called while
        /// processing the <paramref name="path"/>.
        /// </exception>
        /// 
        /// <exception cref="NotSupportedException">
        /// If the provider is not a NavigationCmdletProvider.
        /// </exception>
        /// 
        /// <exception cref="PipelineStoppedException">
        /// If <paramref name="context"/> has been signaled for
        /// StopProcessing.
        /// </exception>
        /// 
        internal string GetDriveRootRelativePathFromPSPath(
            string path,
            CmdletProviderContext context,
            bool escapeCurrentLocation,
            out PSDriveInfo workingDriveForPath,
            out CmdletProvider providerInstance)
        {
            // Verify parameters

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

            workingDriveForPath = null;
            string driveName = null;

            if (_sessionState.Drive.Current != null)
            {
                driveName = _sessionState.Drive.Current.Name;
            }

            // Check to see if the path is relative or absolute
            bool isPathForCurrentDrive = false;

            if (IsAbsolutePath(path, out driveName))
            {
                Dbg.Diagnostics.Assert(
                    driveName != null,
                    "IsAbsolutePath should be returning the drive name");

                s_tracer.WriteLine(
                    "Drive Name: {0}",
                    driveName);

                // This will resolve $GLOBAL, and $LOCAL as needed.
                // This throws DriveNotFoundException if a drive of the specified
                // name does not exist. Just let the exception propagate out.
                try
                {
                    workingDriveForPath = _sessionState.Drive.Get(driveName);
                }
                catch (DriveNotFoundException)
                {
                    // Check to see if it is a path relative to the
                    // current drive's root. This is true when a drive root
                    // appears to be a drive (like HTTP://). The drive will not
                    // actually exist, but this is not an absolute path.

                    if (_sessionState.Drive.Current == null)
                    {
                        throw;
                    }

                    string normalizedRoot = _sessionState.Drive.Current.Root.Replace(
                        StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);

                    if (normalizedRoot.IndexOf(":", StringComparison.CurrentCulture) >= 0)
                    {
                        string normalizedPath = path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
                        if (normalizedPath.StartsWith(normalizedRoot, StringComparison.OrdinalIgnoreCase))
                        {
                            isPathForCurrentDrive = true;
                            path = path.Substring(normalizedRoot.Length);
                            path = path.TrimStart(StringLiterals.DefaultPathSeparator);
                            path = StringLiterals.DefaultPathSeparator + path;
                            workingDriveForPath = _sessionState.Drive.Current;
                        }
                    }

                    if (!isPathForCurrentDrive)
                    {
                        throw;
                    }
                }

                // Now hack off the drive component of the path
                if (!isPathForCurrentDrive)
                {
                    // This functionality needs to respect if a drive uses a colon to separate the path
                    //
                    // what happens here is this:
                    // - path is assumed to be drive root relative, so on Windows it would start with a
                    //   \
                    // - on Linux, there is no difference between drive root relative, and absolute, they
                    //   are both the same, so we have to preserve the drive here in order to make
                    //   sure the path will continue being drive root relative
                    if (workingDriveForPath.VolumeSeparatedByColon)
                    {
                        // this is the default behavior for all windows drives, and all non-filesystem
                        // drives on non-windows
                        path = path.Substring(driveName.Length + 1);
                    }
                }
            }
            else
            {
                // it's a relative path, so the working drive is the current drive
                workingDriveForPath = _sessionState.Drive.Current;
            }

            if (workingDriveForPath == null)
            {
                ItemNotFoundException pathNotFound =
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);

                s_pathResolutionTracer.TraceError("Item does not exist: {0}", path);

                throw pathNotFound;
            }

            try
            {
                providerInstance =
                    _sessionState.Internal.GetContainerProviderInstance(workingDriveForPath.Provider);

                // Add the drive info to the context so that downstream methods
                // have access to it.
                context.Drive = workingDriveForPath;

                string relativePath =
                    GenerateRelativePath(
                        workingDriveForPath,
                        path,
                        escapeCurrentLocation,
                        providerInstance,
                        context);

                return relativePath;
            }
            catch (PSNotSupportedException)
            {
                // If it's really not a container provider, the relative path will
                // always be empty

                providerInstance = null;
                return "";
            }
        } // GetDriveRootRelativePathFromPSPath
예제 #23
0
 private Collection<string> ResolveProviderPathFromProviderPath(string providerPath, string providerId, bool allowNonexistingPaths, CmdletProviderContext context, out CmdletProvider providerInstance)
 {
     providerInstance = this.sessionState.Internal.GetProviderInstance(providerId);
     ContainerCmdletProvider containerProvider = providerInstance as ContainerCmdletProvider;
     ItemCmdletProvider provider2 = providerInstance as ItemCmdletProvider;
     Collection<string> collection = new Collection<string>();
     if (!context.SuppressWildcardExpansion)
     {
         if (CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.ExpandWildcards, providerInstance.ProviderInfo))
         {
             pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider.", new object[0]);
             if ((provider2 != null) && WildcardPattern.ContainsWildcardCharacters(providerPath))
             {
                 collection = new Collection<string>(provider2.ExpandPath(providerPath, context));
             }
             else
             {
                 collection.Add(providerPath);
             }
         }
         else
         {
             pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine.", new object[0]);
             if (containerProvider != null)
             {
                 collection = this.GetGlobbedProviderPathsFromProviderPath(providerPath, allowNonexistingPaths, containerProvider, context);
             }
             else
             {
                 collection.Add(providerPath);
             }
         }
     }
     else if (provider2 != null)
     {
         if (allowNonexistingPaths || provider2.ItemExists(providerPath, context))
         {
             collection.Add(providerPath);
         }
     }
     else
     {
         collection.Add(providerPath);
     }
     if (((allowNonexistingPaths || (collection.Count >= 1)) || WildcardPattern.ContainsWildcardCharacters(providerPath)) || ((context.Include != null) && (context.Include.Count != 0)))
     {
         return collection;
     }
     if ((context.Exclude != null) && (context.Exclude.Count != 0))
     {
         return collection;
     }
     ItemNotFoundException exception = new ItemNotFoundException(providerPath, "PathNotFound", SessionStateStrings.PathNotFound);
     pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { providerPath });
     throw exception;
 }
예제 #24
0
        } // GetGlobbedMonadPathsFromMonadPath

        private Collection<string> ResolveProviderPathFromProviderPath(
            string providerPath,
            string providerId,
            bool allowNonexistingPaths,
            CmdletProviderContext context,
            out CmdletProvider providerInstance
            )
        {
            // Check the provider capabilities before globbing
            providerInstance = _sessionState.Internal.GetProviderInstance(providerId);
            ContainerCmdletProvider containerCmdletProvider = providerInstance as ContainerCmdletProvider;
            ItemCmdletProvider itemProvider = providerInstance as ItemCmdletProvider;

            Collection<string> stringResult = new Collection<string>();

            if (!context.SuppressWildcardExpansion)
            {
                // See if the provider will expand the wildcard
                if (CmdletProviderManagementIntrinsics.CheckProviderCapabilities(
                        ProviderCapabilities.ExpandWildcards,
                        providerInstance.ProviderInfo))
                {
                    s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider.");

                    // Only do the expansion if the path actually contains wildcard
                    // characters.
                    if ((itemProvider != null) &&
                        (WildcardPattern.ContainsWildcardCharacters(providerPath)))
                    {
                        stringResult = new Collection<string>(itemProvider.ExpandPath(providerPath, context));
                    }
                    else
                    {
                        stringResult.Add(providerPath);
                    }
                }
                else
                {
                    s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine.");

                    if (containerCmdletProvider != null)
                    {
                        // Since it is really a provider-internal path, use provider-to-provider globbing
                        // and then add back on the provider ID.

                        stringResult =
                            GetGlobbedProviderPathsFromProviderPath(
                                providerPath,
                                allowNonexistingPaths,
                                containerCmdletProvider,
                                context);
                    }
                    else
                    {
                        // For simple CmdletProvider instances, we can't resolve the paths any
                        // further, so just return the providerPath
                        stringResult.Add(providerPath);
                    }
                }
            }
            // They are suppressing wildcard expansion
            else
            {
                if (itemProvider != null)
                {
                    if (allowNonexistingPaths || itemProvider.ItemExists(providerPath, context))
                    {
                        stringResult.Add(providerPath);
                    }
                }
                else
                {
                    stringResult.Add(providerPath);
                }
            }

            // Make sure this resolved to something
            if ((!allowNonexistingPaths) &&
                stringResult.Count < 1 &&
                !WildcardPattern.ContainsWildcardCharacters(providerPath) &&
                (context.Include == null || context.Include.Count == 0) &&
                (context.Exclude == null || context.Exclude.Count == 0))
            {
                ItemNotFoundException pathNotFound =
                    new ItemNotFoundException(
                        providerPath,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);

                s_pathResolutionTracer.TraceError("Item does not exist: {0}", providerPath);
                throw pathNotFound;
            }

            return stringResult;
        }
예제 #25
0
 internal Collection<string> ExpandGlobPath(string path, bool allowNonexistingPaths, ContainerCmdletProvider provider, CmdletProviderContext context)
 {
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     if (provider == null)
     {
         throw PSTraceSource.NewArgumentNullException("provider");
     }
     string updatedPath = null;
     string updatedFilter = null;
     string filter = context.Filter;
     bool flag = provider.ConvertPath(path, context.Filter, ref updatedPath, ref updatedFilter, context);
     if (flag)
     {
         tracer.WriteLine("Provider converted path and filter.", new object[0]);
         tracer.WriteLine("Original path: " + path, new object[0]);
         tracer.WriteLine("Converted path: " + updatedPath, new object[0]);
         tracer.WriteLine("Original filter: " + context.Filter, new object[0]);
         tracer.WriteLine("Converted filter: " + updatedFilter, new object[0]);
         path = updatedPath;
         filter = context.Filter;
     }
     NavigationCmdletProvider provider2 = provider as NavigationCmdletProvider;
     tracer.WriteLine("path = {0}", new object[] { path });
     Collection<string> collection = new Collection<string>();
     using (pathResolutionTracer.TraceScope("EXPANDING WILDCARDS", new object[0]))
     {
         if (ShouldPerformGlobbing(path, context))
         {
             StringCollection currentDirs = new StringCollection();
             Stack<string> stack = new Stack<string>();
             using (pathResolutionTracer.TraceScope("Tokenizing path", new object[0]))
             {
                 while (StringContainsGlobCharacters(path))
                 {
                     if (context.Stopping)
                     {
                         throw new PipelineStoppedException();
                     }
                     string childName = path;
                     if (provider2 != null)
                     {
                         childName = provider2.GetChildName(path, context);
                     }
                     if (string.IsNullOrEmpty(childName))
                     {
                         break;
                     }
                     tracer.WriteLine("Pushing leaf element: {0}", new object[] { childName });
                     pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { childName });
                     stack.Push(childName);
                     if (provider2 != null)
                     {
                         string root = string.Empty;
                         if (context != null)
                         {
                             PSDriveInfo drive = context.Drive;
                             if (drive != null)
                             {
                                 root = drive.Root;
                             }
                         }
                         string a = provider2.GetParentPath(path, root, context);
                         if (string.Equals(a, path, StringComparison.OrdinalIgnoreCase))
                         {
                             throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "ProviderImplementationInconsistent", new object[] { provider.ProviderInfo.Name, path });
                         }
                         path = a;
                     }
                     else
                     {
                         path = string.Empty;
                     }
                     tracer.WriteLine("New path: {0}", new object[] { path });
                     pathResolutionTracer.WriteLine("Parent path: {0}", new object[] { path });
                 }
                 tracer.WriteLine("Base container path: {0}", new object[] { path });
                 if (stack.Count == 0)
                 {
                     string str7 = path;
                     if (provider2 != null)
                     {
                         str7 = provider2.GetChildName(path, context);
                         if (!string.IsNullOrEmpty(str7))
                         {
                             path = provider2.GetParentPath(path, null, context);
                         }
                     }
                     else
                     {
                         path = string.Empty;
                     }
                     stack.Push(str7);
                     pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { str7 });
                 }
                 pathResolutionTracer.WriteLine("Root path of resolution: {0}", new object[] { path });
             }
             currentDirs.Add(path);
             while (stack.Count > 0)
             {
                 if (context.Stopping)
                 {
                     throw new PipelineStoppedException();
                 }
                 string leafElement = stack.Pop();
                 currentDirs = this.GenerateNewPathsWithGlobLeaf(currentDirs, leafElement, stack.Count == 0, provider, context);
                 if (stack.Count > 0)
                 {
                     using (pathResolutionTracer.TraceScope("Checking matches to ensure they are containers", new object[0]))
                     {
                         int index = 0;
                         while (index < currentDirs.Count)
                         {
                             if (context.Stopping)
                             {
                                 throw new PipelineStoppedException();
                             }
                             if ((provider2 != null) && !provider2.IsItemContainer(currentDirs[index], context))
                             {
                                 tracer.WriteLine("Removing {0} because it is not a container", new object[] { currentDirs[index] });
                                 pathResolutionTracer.WriteLine("{0} is not a container", new object[] { currentDirs[index] });
                                 currentDirs.RemoveAt(index);
                             }
                             else if (provider2 != null)
                             {
                                 pathResolutionTracer.WriteLine("{0} is a container", new object[] { currentDirs[index] });
                                 index++;
                             }
                         }
                         continue;
                     }
                 }
             }
             foreach (string str9 in currentDirs)
             {
                 pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str9 });
                 collection.Add(str9);
             }
         }
         else
         {
             string str10 = context.SuppressWildcardExpansion ? path : RemoveGlobEscaping(path);
             if (allowNonexistingPaths || provider.ItemExists(str10, context))
             {
                 pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str10 });
                 collection.Add(str10);
             }
             else
             {
                 ItemNotFoundException exception2 = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound);
                 pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { path });
                 throw exception2;
             }
         }
     }
     if (flag)
     {
         context.Filter = filter;
     }
     return collection;
 }
예제 #26
0
        } // GenerateNewPSPathsWithGlobLeaf

        /// <summary>
        /// Generates an array of provider specific paths from the single provider specific
        /// path using globing rules.
        /// </summary>
        /// 
        /// <param name="path">
        /// A path that may or may not contain globing characters.
        /// </param>
        /// 
        /// <param name="allowNonexistingPaths">
        /// If true, a ItemNotFoundException will not be thrown for non-existing
        /// paths. Instead an appropriate path will be returned as if it did exist.
        /// </param>
        /// 
        /// <param name="provider">
        /// The provider that implements the namespace for the path that we are globing over.
        /// </param>
        /// 
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        /// 
        /// <returns>
        /// An array of path strings that match the globing rules applied to the path parameter.
        /// </returns>
        /// 
        /// <remarks>
        /// First the path is checked to see if it contains any globing characters ('?' or '*').
        /// If it doesn't then the path is returned as the only element in the array.
        /// If it does, GetParentPath and GetLeafPathName is called on the path and each element
        /// is stored until the path doesn't contain any globing characters. At that point 
        /// GetChildPathNames() is called on the provider with the last parent path that doesn't
        /// contain a globing character. All the results are then matched against leaf element
        /// of that parent path (which did contain a glob character). We then walk out of the
        /// recursion and apply the same procedure to each leaf element that contained globing
        /// characters.
        /// 
        /// The procedure above allows us to match globing strings in multiple sub-containers
        /// in the namespace without having to have knowledge of the namespace paths, or
        /// their syntax.
        /// 
        /// Example:
        /// dir c:\foo\*\bar\*a??.cs
        /// 
        /// Calling this method for the path above would return all files that end in 'a' and
        /// any other two characters followed by ".cs" in all the subdirectories of
        /// foo that have a bar subdirectory.
        /// 
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> or <paramref name="provider"/> is null.
        /// </exception>
        /// 
        /// 
        /// <exception cref="ProviderInvocationException">
        /// If the provider used to build the path threw an exception.
        /// </exception>
        /// 
        /// <exception cref="InvalidOperationException">
        /// If the <paramref name="path"/> starts with "~" and the home location is not set for 
        /// the provider.
        /// or if the provider is implemented in such a way as to cause the globber to go
        /// into an infinite loop.
        /// </exception>
        /// 
        /// <exception cref="PipelineStoppedException">
        /// If <paramref name="context"/> has been signaled for
        /// StopProcessing.
        /// </exception>
        /// 
        /// <exception>
        /// Any exception can be thrown by the provider that is called to build
        /// the provider path.
        /// </exception>
        /// 
        internal Collection<string> ExpandGlobPath(
            string path,
            bool allowNonexistingPaths,
            ContainerCmdletProvider provider,
            CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

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

            // See if the provider wants to convert the path and filter
            string convertedPath = null;
            string convertedFilter = null;
            string originalFilter = context.Filter;
            bool changedPathOrFilter = provider.ConvertPath(path, context.Filter, ref convertedPath, ref convertedFilter, context);

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

                path = convertedPath;
                originalFilter = context.Filter;
            }

            NavigationCmdletProvider navigationProvider = provider as NavigationCmdletProvider;

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

            Collection<string> result = new Collection<string>();

            using (s_pathResolutionTracer.TraceScope("EXPANDING WILDCARDS"))
            {
                if (ShouldPerformGlobbing(path, context))
                {
                    // This collection contains the directories for which a leaf is being added.
                    // If the directories are being globed over as well, then there will be
                    // many directories in this collection which will have to be iterated over
                    // every time there is a child being added

                    List<string> dirs = new List<string>();

                    // Each leaf element that is pulled off the path is pushed on the stack in
                    // order such that we can generate the path again.

                    Stack<String> leafElements = new Stack<String>();

                    using (s_pathResolutionTracer.TraceScope("Tokenizing path"))
                    {
                        // If the path contains glob characters then iterate through pulling the
                        // leaf elements off and pushing them on to the leafElements stack until
                        // there are no longer any glob characters in the path.

                        while (StringContainsGlobCharacters(path))
                        {
                            // Make sure to obey StopProcessing
                            if (context.Stopping)
                            {
                                throw new PipelineStoppedException();
                            }

                            // Use the provider to get the leaf element string

                            string leafElement = path;

                            if (navigationProvider != null)
                            {
                                leafElement = navigationProvider.GetChildName(path, context);
                            }

                            if (String.IsNullOrEmpty(leafElement))
                            {
                                break;
                            }

                            s_tracer.WriteLine("Pushing leaf element: {0}", leafElement);

                            s_pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement);

                            // Push the leaf element onto the leaf element stack for future use

                            leafElements.Push(leafElement);

                            // Now use the parent path for the next iteration

                            if (navigationProvider != null)
                            {
                                // See if we can get the root from the context

                                string root = String.Empty;

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

                                    if (drive != null)
                                    {
                                        root = drive.Root;
                                    }
                                }

                                // Now call GetParentPath with the root

                                string newParentPath = navigationProvider.GetParentPath(path, root, context);

                                if (String.Equals(
                                        newParentPath,
                                        path,
                                        StringComparison.OrdinalIgnoreCase))
                                {
                                    // The provider is implemented in an inconsistent way. 
                                    // GetChildName returned a non-empty/non-null result but
                                    // GetParentPath with the same path returns the same path.
                                    // This would cause the globber to go into an infinite loop,
                                    // so instead an exception is thrown.

                                    PSInvalidOperationException invalidOperation =
                                        PSTraceSource.NewInvalidOperationException(
                                            SessionStateStrings.ProviderImplementationInconsistent,
                                            provider.ProviderInfo.Name,
                                            path);
                                    throw invalidOperation;
                                }
                                path = newParentPath;
                            }
                            else
                            {
                                // If the provider doesn't implement NavigationCmdletProvider then at most
                                // it can have only one segment in its path. So after removing
                                // the leaf all we have left is the empty string.

                                path = String.Empty;
                            }

                            s_tracer.WriteLine("New path: {0}", path);
                            s_pathResolutionTracer.WriteLine("Parent path: {0}", path);
                        }

                        s_tracer.WriteLine("Base container path: {0}", path);

                        // If no glob elements were found there must be an include and/or
                        // exclude specified. Use the parent path to iterate over to 
                        // resolve the include/exclude filters

                        if (leafElements.Count == 0)
                        {
                            string leafElement = path;

                            if (navigationProvider != null)
                            {
                                leafElement = navigationProvider.GetChildName(path, context);

                                if (!String.IsNullOrEmpty(leafElement))
                                {
                                    path = navigationProvider.GetParentPath(path, null, context);
                                }
                            }
                            else
                            {
                                path = String.Empty;
                            }
                            leafElements.Push(leafElement);
                            s_pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement);
                        }

                        s_pathResolutionTracer.WriteLine("Root path of resolution: {0}", path);
                    }
                    // Once the container path with no glob characters are found store it
                    // so that it's children can be iterated over.

                    dirs.Add(path);

                    // Reconstruct the path one leaf element at a time, expanding where-ever
                    // we encounter glob characters

                    while (leafElements.Count > 0)
                    {
                        // Make sure to obey StopProcessing
                        if (context.Stopping)
                        {
                            throw new PipelineStoppedException();
                        }

                        string leafElement = leafElements.Pop();

                        Dbg.Diagnostics.Assert(
                            leafElement != null,
                            "I am only pushing strings onto this stack so I should be able " +
                            "to cast any Pop to a string without failure.");

                        dirs =
                            GenerateNewPathsWithGlobLeaf(
                                dirs,
                                leafElement,
                                leafElements.Count == 0,
                                provider,
                                context);

                        // If there are more leaf elements in the stack we need
                        // to make sure that only containers where added to dirs
                        // in GenerateNewPathsWithGlobLeaf

                        if (leafElements.Count > 0)
                        {
                            using (s_pathResolutionTracer.TraceScope("Checking matches to ensure they are containers"))
                            {
                                int index = 0;

                                while (index < dirs.Count)
                                {
                                    // Make sure to obey StopProcessing
                                    if (context.Stopping)
                                    {
                                        throw new PipelineStoppedException();
                                    }

                                    // Check to see if the matching item is a container

                                    if (navigationProvider != null &&
                                        !navigationProvider.IsItemContainer(
                                            dirs[index],
                                            context))
                                    {
                                        // If not, remove it from the collection

                                        s_tracer.WriteLine(
                                            "Removing {0} because it is not a container",
                                            dirs[index]);

                                        s_pathResolutionTracer.WriteLine("{0} is not a container", dirs[index]);
                                        dirs.RemoveAt(index);
                                    }
                                    else if (navigationProvider == null)
                                    {
                                        Dbg.Diagnostics.Assert(
                                            navigationProvider != null,
                                            "The path in the dirs should never be a container unless " +
                                            "the provider implements the NavigationCmdletProvider interface. If it " +
                                            "doesn't, there should be no more leafElements in the stack " +
                                            "when this check is done");
                                    }
                                    else
                                    {
                                        s_pathResolutionTracer.WriteLine("{0} is a container", dirs[index]);

                                        // If so, leave it and move on to the next one

                                        ++index;
                                    }
                                }
                            }
                        }
                    } // while (leafElements.Count > 0)

                    Dbg.Diagnostics.Assert(
                        dirs != null,
                        "GenerateNewPathsWithGlobLeaf() should return the base path as an element " +
                        "even if there are no globing characters");

                    foreach (string dir in dirs)
                    {
                        s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", dir);
                        result.Add(dir);
                    }

                    Dbg.Diagnostics.Assert(
                        dirs.Count == result.Count,
                        "The result of copying the globed strings should be the same " +
                        "as from the collection");
                }
                else
                {
                    string unescapedPath = context.SuppressWildcardExpansion ? path : RemoveGlobEscaping(path);

                    if (allowNonexistingPaths ||
                        provider.ItemExists(unescapedPath, context))
                    {
                        s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", unescapedPath);
                        result.Add(unescapedPath);
                    }
                    else
                    {
                        ItemNotFoundException pathNotFound =
                            new ItemNotFoundException(
                                path,
                                "PathNotFound",
                                SessionStateStrings.PathNotFound);

                        s_pathResolutionTracer.TraceError("Item does not exist: {0}", path);

                        throw pathNotFound;
                    }
                }
            }
            Dbg.Diagnostics.Assert(
                result != null,
                "This method should at least return the path or more if it has glob characters");

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

            return result;
        } // ExpandGlobPath
예제 #27
0
        internal Collection<PathInfo> GetGlobbedMonadPathsFromMonadPath (string path, bool allowNonexistingPaths, CmdletProviderContext context, out CmdletProvider providerInstance)
		{
			providerInstance = null;
			if (path == null) {
				throw PSTraceSource.NewArgumentNullException ("path");
			}
			if (context == null) {
				throw PSTraceSource.NewArgumentNullException ("context");
			}
            Collection<PathInfo> collection = new Collection<PathInfo>();
            using (pathResolutionTracer.TraceScope("Resolving MSH path \"{0}\" to MSH path", new object[] { path }))
            {
                TraceFilters(context);
                if (IsHomePath(path))
                {
                    using (pathResolutionTracer.TraceScope("Resolving HOME relative path.", new object[0]))
                    {
                        path = this.GetHomeRelativePath(path);
                    }
                }
                bool isProviderDirectPath = IsProviderDirectPath(path);
                bool isProviderQualifiedPath = IsProviderQualifiedPath(path);
                if (isProviderDirectPath || isProviderQualifiedPath)
                {
                    collection = this.ResolvePSPathFromProviderPath(path, context, allowNonexistingPaths, isProviderDirectPath, isProviderQualifiedPath, out providerInstance);
                }
                else
                {
                    collection = this.ResolveDriveQualifiedPath(path, context, allowNonexistingPaths, out providerInstance);
                }
                if (((allowNonexistingPaths || (collection.Count >= 1)) || WildcardPattern.ContainsWildcardCharacters(path)) || ((context.Include != null) && (context.Include.Count != 0)))
                {
                    return collection;
                }
                if ((context.Exclude != null) && (context.Exclude.Count != 0))
                {
                    return collection;
                }
                ItemNotFoundException exception = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound);
                pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { path });
                throw exception;
            }
        }
예제 #28
0
        private Collection<PathInfo> ResolveDriveQualifiedPath(
            string path,
            CmdletProviderContext context,
            bool allowNonexistingPaths,
            out CmdletProvider providerInstance)
        {
            providerInstance = null;
            PSDriveInfo drive = null;

            Collection<PathInfo> result = new Collection<PathInfo>();

            s_pathResolutionTracer.WriteLine("Path is DRIVE-QUALIFIED");

            string relativePath = GetDriveRootRelativePathFromPSPath(path, context, true, out drive, out providerInstance);

            Dbg.Diagnostics.Assert(
                drive != null,
                "GetDriveRootRelativePathFromPSPath should always return a valid drive");

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

            s_pathResolutionTracer.WriteLine("DRIVE-RELATIVE path: {0}", relativePath);
            s_pathResolutionTracer.WriteLine("Drive: {0}", drive.Name);
            s_pathResolutionTracer.WriteLine("Provider: {0}", drive.Provider);

            // Associate the drive with the context

            context.Drive = drive;
            providerInstance = _sessionState.Internal.GetContainerProviderInstance(drive.Provider);
            ContainerCmdletProvider containerCmdletProvider = providerInstance as ContainerCmdletProvider;
            ItemCmdletProvider itemProvider = providerInstance as ItemCmdletProvider;

            ProviderInfo provider = providerInstance.ProviderInfo;

            string userPath = null;
            string itemPath = null;

            if (drive.Hidden)
            {
                userPath = GetProviderQualifiedPath(relativePath, provider);
                itemPath = relativePath;
            }
            else
            {
                userPath = GetDriveQualifiedPath(relativePath, drive);
                itemPath = GetProviderPath(path, context);
            }
            s_pathResolutionTracer.WriteLine("PROVIDER path: {0}", itemPath);

            Collection<string> stringResult = new Collection<string>();

            if (!context.SuppressWildcardExpansion)
            {
                // See if the provider will expand the wildcard
                if (CmdletProviderManagementIntrinsics.CheckProviderCapabilities(
                        ProviderCapabilities.ExpandWildcards,
                        provider))
                {
                    s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider.");

                    // Only do the expansion if the path actually contains wildcard
                    // characters.
                    if ((itemProvider != null) &&
                        (WildcardPattern.ContainsWildcardCharacters(relativePath)))
                    {
                        foreach (string pathResult in itemProvider.ExpandPath(itemPath, context))
                        {
                            stringResult.Add(
                                GetDriveRootRelativePathFromProviderPath(pathResult, drive, context));
                        }
                    }
                    else
                    {
                        stringResult.Add(GetDriveRootRelativePathFromProviderPath(itemPath, drive, context));
                    }
                }
                else
                {
                    s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine.");

                    // Now perform the globbing
                    stringResult =
                        ExpandMshGlobPath(
                            relativePath,
                            allowNonexistingPaths,
                            drive,
                            containerCmdletProvider,
                            context);
                }
            }
            // They are suppressing wildcard expansion
            else
            {
                if (itemProvider != null)
                {
                    if (allowNonexistingPaths || itemProvider.ItemExists(itemPath, context))
                    {
                        stringResult.Add(userPath);
                    }
                }
                else
                {
                    stringResult.Add(userPath);
                }
            }

            // Make sure this resolved to something
            if ((!allowNonexistingPaths) &&
                stringResult.Count < 1 &&
                !WildcardPattern.ContainsWildcardCharacters(path) &&
                (context.Include == null || context.Include.Count == 0) &&
                (context.Exclude == null || context.Exclude.Count == 0))
            {
                ItemNotFoundException pathNotFound =
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);

                s_pathResolutionTracer.TraceError("Item does not exist: {0}", path);
                throw pathNotFound;
            }

            // Now fix the paths
            foreach (string expandedPath in stringResult)
            {
                // Make sure to obey StopProcessing
                if (context.Stopping)
                {
                    throw new PipelineStoppedException();
                }

                // Add the drive back into the path
                userPath = null;

                if (drive.Hidden)
                {
                    if (IsProviderDirectPath(expandedPath))
                    {
                        userPath = expandedPath;
                    }
                    else
                    {
                        userPath =
                            LocationGlobber.GetProviderQualifiedPath(
                                expandedPath,
                                provider);
                    }
                }
                else
                {
                    userPath =
                        LocationGlobber.GetDriveQualifiedPath(
                                expandedPath,
                                drive);
                }

                result.Add(new PathInfo(drive, provider, userPath, _sessionState));
                s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", userPath);
            }

            return result;
        }
예제 #29
0
		internal static ErrorRecord CreatePathNotFoundErrorRecord(string path, string errorId)
		{
			ItemNotFoundException itemNotFoundException = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound);
			ErrorRecord errorRecord = new ErrorRecord(itemNotFoundException, errorId, ErrorCategory.ObjectNotFound, null);
			return errorRecord;
		}
예제 #30
0
 protected override void ProcessRecord()
 {
     IDictionary<string, AliasInfo> aliasTableAtScope = null;
     if (!string.IsNullOrEmpty(this.scope))
     {
         aliasTableAtScope = base.SessionState.Internal.GetAliasTableAtScope(this.scope);
     }
     else
     {
         aliasTableAtScope = base.SessionState.Internal.GetAliasTable();
     }
     foreach (string str in this.names)
     {
         bool flag = false;
         WildcardPattern pattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
         CommandOrigin commandOrigin = base.MyInvocation.CommandOrigin;
         foreach (KeyValuePair<string, AliasInfo> pair in aliasTableAtScope)
         {
             if (pattern.IsMatch(pair.Key) && SessionState.IsVisible(commandOrigin, (CommandInfo) pair.Value))
             {
                 flag = true;
                 this.matchingAliases.Add(pair.Value);
             }
         }
         if (!flag && !WildcardPattern.ContainsWildcardCharacters(str))
         {
             ItemNotFoundException replaceParentContainsErrorRecordException = new ItemNotFoundException(str, "AliasNotFound", SessionStateStrings.AliasNotFound);
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
         }
     }
 }