/// <summary> /// Sets the specified properties on the specified item. /// </summary> /// <param name="paths"> /// The path(s) to the item(s) to set the properties on. /// </param> /// <param name="property"> /// A PSObject containing the properties to be changed. /// </param> /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// <returns> /// An array of PSObjects representing the properties that were set on each item. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> or <paramref name="property"/> is null. /// </exception> /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal Collection <PSObject> SetProperty(string[] paths, PSObject property, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } if (property == null) { throw PSTraceSource.NewArgumentNullException("properties"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; SetProperty(paths, property, context); context.ThrowFirstErrorOrDoNothing(); Collection <PSObject> results = context.GetAccumulatedObjects(); return(results); }
/// <summary> /// Clears the specified object. Depending on the provider that the path /// maps to, this could mean the properties and/or content and/or value is /// cleared. /// </summary> /// <param name="paths"> /// The path(s) to the object. It can be either a relative (most common) /// or absolute path. /// </param> /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// <returns> /// The items that were cleared. /// </returns> /// <remarks> /// If an error occurs that error will be thrown. /// </remarks> /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal Collection <PSObject> ClearItem(string[] paths, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; ClearItem(paths, context); context.ThrowFirstErrorOrDoNothing(); return(context.GetAccumulatedObjects()); }
/// <summary> /// Gets the security descriptor from the specified item. /// </summary> /// <param name="path"> /// The path to the item to retrieve the security descriptor from. /// </param> /// <param name="sections"> /// Specifies the parts of a security descriptor to retrieve. /// </param> /// <returns> /// The security descriptor for the item at the specified path. /// </returns> internal Collection <PSObject> GetSecurityDescriptor(string path, AccessControlSections sections) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); GetSecurityDescriptor(path, sections, context); context.ThrowFirstErrorOrDoNothing(); Collection <PSObject> contextResults = context.GetAccumulatedObjects() ?? new Collection <PSObject>(); return(contextResults); }
/// <summary> /// Gets the specified properties from the specified item. /// </summary> /// /// <param name="paths"> /// The path(s) to the item(s) to get the properties from. /// </param> /// /// <param name="providerSpecificPickList"> /// A list of the properties that the provider should return. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// A property table container the properties and their values. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal Collection<PSObject> GetProperty( string[] paths, Collection<string> providerSpecificPickList, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("path"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.SuppressWildcardExpansion = literalPath; GetProperty(paths, providerSpecificPickList, context); context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> results = context.GetAccumulatedObjects(); return results; } // GetProperties
/// <summary> /// Gets the specified properties from the specified item. /// </summary> /// <param name="paths"> /// The path(s) to the item(s) to get the properties from. /// </param> /// <param name="providerSpecificPickList"> /// A list of the properties that the provider should return. /// </param> /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// <returns> /// A property table container the properties and their values. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal Collection<PSObject> GetProperty( string[] paths, Collection<string> providerSpecificPickList, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("path"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.SuppressWildcardExpansion = literalPath; GetProperty(paths, providerSpecificPickList, context); context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> results = context.GetAccumulatedObjects(); return results; }
/// <summary> /// Gets the specified object /// </summary> /// /// <param name="paths"> /// The path(s) to the object(s). They can be either a relative (most common) /// or absolute path. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// The item at the specified path. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal Collection<PSObject> GetItem(string[] paths, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; GetItem(paths, context); context.ThrowFirstErrorOrDoNothing(); // Since there was not errors return the accumulated objects Collection<PSObject> results = context.GetAccumulatedObjects(); return results; } // GetItem
/// <summary> /// Sets the security descriptor on the specified item. /// </summary> /// <param name="path"> /// The path to the item to set the security descriptor on. /// </param> /// <param name="securityDescriptor"> /// The security descriptor to set on the item at the specified path. /// </param> /// <returns> /// The security descriptor that was set on the item at the specified path. /// </returns> internal Collection <PSObject> SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException("securityDescriptor"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); SetSecurityDescriptor(path, securityDescriptor, context); context.ThrowFirstErrorOrDoNothing(); // Return an empty array instead of null Collection <PSObject> contextResults = context.GetAccumulatedObjects() ?? new Collection <PSObject>(); return(contextResults); }
internal Collection<PSObject> RenameItem(string path, string newName, bool force) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Force = force }; this.RenameItem(path, newName, context); context.ThrowFirstErrorOrDoNothing(); return context.GetAccumulatedObjects(); }
internal Collection<PSObject> NewItem(string[] paths, string name, string type, object content, bool force) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Force = force }; this.NewItem(paths, name, type, content, context); context.ThrowFirstErrorOrDoNothing(); return context.GetAccumulatedObjects(); }
} // GetVariable /// <summary> /// Get a variable out of session state. This interface supports /// the "namespace:name" syntax so you can do things like /// "env:PATH" or "global:foobar" /// </summary> /// /// <param name="name"> /// name of variable to look up /// </param> /// /// <param name="scopeID"> /// The ID of the scope to lookup the variable in. /// </param> /// /// <returns> /// The value of the specified variable. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="name"/> is null. /// </exception> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="name"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="name"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="name"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal object GetVariableValueAtScope(string name, string scopeID) { if (name == null) { throw PSTraceSource.NewArgumentNullException("name"); } VariablePath variablePath = new VariablePath(name); SessionStateScope lookupScope = null; // The lookup scope from above is ignored and the scope is retrieved by // ID. lookupScope = GetScopeByID(scopeID); object resultItem = null; if (variablePath.IsVariable) { resultItem = lookupScope.GetVariable(variablePath.QualifiedName); } else { PSDriveInfo drive = lookupScope.GetDrive(variablePath.DriveName); if (drive != null) { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Drive = drive; #if true // PSVariable get/set is the get/set of content in the provider Collection<IContentReader> readers = null; try { readers = GetContentReader(new string[] { variablePath.QualifiedName }, context); } // If the item is not found we just return null like the normal // variable semantics. catch (ItemNotFoundException) { return null; } catch (DriveNotFoundException) { return null; } catch (ProviderNotFoundException) { return null; } catch (NotImplementedException notImplemented) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notImplemented, false); } catch (NotSupportedException notSupported) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notSupported, false); } if (readers == null || readers.Count == 0) { // The drive was found but the path was wrong or something so return null. // We don't want to continue searching if the provider didn't support content // or the path wasn't found. // Any errors should have been written to the error pipeline. return null; } if (readers.Count > 1) { foreach (IContentReader closeReader in readers) { closeReader.Close(); } // Since more than one path was resolved, this is an error. PSArgumentException argException = PSTraceSource.NewArgumentException( "path", SessionStateStrings.VariablePathResolvedToMultiple, name); // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, providerInfo, variablePath.QualifiedName, argException); } IContentReader reader = readers[0]; try { // Read all the content IList resultList = reader.Read(-1); if (resultList != null) { if (resultList.Count == 0) { resultItem = null; } else if (resultList.Count == 1) { resultItem = resultList[0]; } else { resultItem = resultList; } } } catch (Exception e) // Third-party callout, catch-all OK { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); CommandProcessorBase.CheckForSevereException(e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, providerInfo, variablePath.QualifiedName, e); throw providerException; } finally { reader.Close(); } #else GetItem (variablePath.LookupPath.ToString (), context); Collection<PSObject> results = context.GetAccumulatedObjects (); if (results != null & results.Count > 0) { // Only return the first value. If the caller wants globbing // they need to call the GetItem method directly. if (!results[0].basObjectIsEmpty) { resultItem = results[0].BaseObject; } else { resultItem = results[0]; } } #endif } } // If we get a PSVariable or DictionaryEntry returned then we have to // grab the value from it and return that instead. if (resultItem != null) { PSVariable variable = resultItem as PSVariable; if (variable != null) { resultItem = variable.Value; } else { try { DictionaryEntry entry = (DictionaryEntry)resultItem; resultItem = entry.Value; } catch (InvalidCastException) { } } } // if resultItem != null return resultItem; } // GetVariableValueAtScope
} // GetSecurityDescriptor #endregion GetSecurityDescriptor #region SetSecurityDescriptor /// <summary> /// Sets the security descriptor on the specified item. /// </summary> /// /// <param name="path"> /// The path to the item to set the security descriptor on. /// </param> /// /// <param name="securityDescriptor"> /// The security descriptor to set on the item at the specified path. /// </param> /// /// <returns> /// The security descriptor that was set on the item at the specified path. /// </returns> /// internal Collection<PSObject> SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException("securityDescriptor"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); SetSecurityDescriptor(path, securityDescriptor, context); context.ThrowFirstErrorOrDoNothing(); // Return an empty array instead of null Collection<PSObject> contextResults = context.GetAccumulatedObjects() ?? new Collection<PSObject>(); return contextResults; } // SetSecurityDescriptor
} // GetPermissionProviderInstance #endregion private methods #region GetSecurityDescriptor /// <summary> /// Gets the security descriptor from the specified item. /// </summary> /// /// <param name="path"> /// The path to the item to retrieve the security descriptor from. /// </param> /// /// <param name="sections"> /// Specifies the parts of a security descriptor to retrieve. /// </param> /// /// <returns> /// The security descriptor for the item at the specified path. /// </returns> /// internal Collection<PSObject> GetSecurityDescriptor(string path, AccessControlSections sections) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); GetSecurityDescriptor(path, sections, context); context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> contextResults = context.GetAccumulatedObjects() ?? new Collection<PSObject>(); return contextResults; } // GetSecurityDescriptor
} // GenerateNewPathsWithGlobLeaf /// <summary> /// Gets the child names in the specified path by using the provider /// </summary> /// /// <param name="dir"> /// The path of the directory to get the child names from. If this is an Msh Path, /// dirIsProviderPath must be false, If this is a provider-internal path, /// dirIsProviderPath must be true. /// </param> /// /// <param name="leafElement"> /// The element that we are ultimately looking for. Used to set filters on the context /// if desired. /// </param> /// /// <param name="getAllContainers"> /// Determines if the GetChildNames call should get all containers even if they don't /// match the filter. /// </param> /// /// <param name="context"> /// The context to be used for the command. The context is copied to a new context, the /// results are accumulated and then returned. /// </param> /// /// <param name="dirIsProviderPath"> /// Specifies whether the dir parameter is a provider-internal path (true) or Msh Path (false). /// </param> /// /// <param name="drive"> /// The drive to use to qualify the Msh path if dirIsProviderPath is false. /// </param> /// /// <param name="provider"> /// The provider to use to get the child names. /// </param> /// /// <param name="modifiedDirPath"> /// Returns the modified dir path. If dirIsProviderPath is true, this is the unescaped dir path. /// If dirIsProviderPath is false, this is the unescaped resolved provider path. /// </param> /// /// <returns> /// A collection of PSObjects whose BaseObject is a string that contains the name of the child. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="dir"/> or <paramref name="drive"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the path is a provider-qualified path for a provider that is /// not loaded into the system. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider used to build the path threw an exception. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> represents is not a NavigationCmdletProvider /// or ContainerCmdletProvider. /// </exception> /// /// <exception cref="InvalidOperationException"> /// If the <paramref name="path"/> starts with "~" and the home location is not set for /// the provider. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider associated with the <paramref name="path"/> threw an /// exception when its GetParentPath or MakePath was called while /// processing the <paramref name="path"/>. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If <paramref name="context"/> has been signaled for /// StopProcessing. /// </exception> /// /// <exception> /// Any exception can be thrown by the provider that is called to build /// the provider path. /// </exception> /// private Collection<PSObject> GetChildNamesInDir( string dir, string leafElement, bool getAllContainers, CmdletProviderContext context, bool dirIsProviderPath, PSDriveInfo drive, ContainerCmdletProvider provider, out string modifiedDirPath) { // See if the provider wants to convert the path and filter string convertedPath = null; string convertedFilter = null; string originalFilter = context.Filter; bool changedPathOrFilter = provider.ConvertPath(leafElement, context.Filter, ref convertedPath, ref convertedFilter, context); if (changedPathOrFilter) { if (s_tracer.IsEnabled) { s_tracer.WriteLine("Provider converted path and filter."); s_tracer.WriteLine("Original path: {0}", leafElement); s_tracer.WriteLine("Converted path: {0}", convertedPath); s_tracer.WriteLine("Original filter: {0}", context.Filter); s_tracer.WriteLine("Converted filter: {0}", convertedFilter); } leafElement = convertedPath; context.Filter = convertedFilter; } ReturnContainers returnContainers = ReturnContainers.ReturnAllContainers; if (!getAllContainers) { returnContainers = ReturnContainers.ReturnMatchingContainers; } CmdletProviderContext getChildNamesContext = new CmdletProviderContext(context); // Remove the include/exclude filters from the new context getChildNamesContext.SetFilters( new Collection<string>(), new Collection<string>(), context.Filter); try { // Use the provider to get the children string unescapedDir = null; modifiedDirPath = null; if (dirIsProviderPath) { modifiedDirPath = unescapedDir = context.SuppressWildcardExpansion ? dir : RemoveGlobEscaping(dir); } else { Dbg.Diagnostics.Assert( drive != null, "Caller should verify that drive is not null when dirIsProviderPath is false"); // If the directory is an MSH path we must resolve it before calling GetChildNames() // -- If the path is passed in by LiteralPath (context.SuppressWildcardExpansion == false), we surely should use 'dir' unchanged. // -- If the path is passed in by Path (context.SuppressWildcardExpansion == true), we still should use 'dir' unchanged, in case that the special character // in 'dir' is escaped modifiedDirPath = GetMshQualifiedPath(dir, drive); ProviderInfo providerIgnored = null; CmdletProvider providerInstanceIgnored = null; Collection<string> resolvedPaths = GetGlobbedProviderPathsFromMonadPath( modifiedDirPath, false, getChildNamesContext, out providerIgnored, out providerInstanceIgnored); // After resolving the path, we unescape the modifiedDirPath if necessary. modifiedDirPath = context.SuppressWildcardExpansion ? modifiedDirPath : RemoveGlobEscaping(modifiedDirPath); if (resolvedPaths.Count > 0) { unescapedDir = resolvedPaths[0]; } else { // If there were no results from globbing but no // exception was thrown, that means there was filtering. // So return an empty collection and let the caller deal // with it. if (changedPathOrFilter) { context.Filter = originalFilter; } return new Collection<PSObject>(); } } if (provider.HasChildItems(unescapedDir, getChildNamesContext)) { provider.GetChildNames( unescapedDir, returnContainers, getChildNamesContext); } // First check to see if there were any errors, and write them // to the real context if there are. if (getChildNamesContext.HasErrors()) { Collection<ErrorRecord> errors = getChildNamesContext.GetAccumulatedErrorObjects(); if (errors != null && errors.Count > 0) { foreach (ErrorRecord errorRecord in errors) { context.WriteError(errorRecord); } } } Collection<PSObject> childNamesObjectArray = getChildNamesContext.GetAccumulatedObjects(); if (changedPathOrFilter) { context.Filter = originalFilter; } return childNamesObjectArray; } finally { getChildNamesContext.RemoveStopReferral(); } } // GetChildNamesInDir
internal Collection<PSObject> CopyItem(string[] paths, string copyPath, bool recurse, CopyContainers copyContainers, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } if (copyPath == null) { copyPath = string.Empty; } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Force = force, SuppressWildcardExpansion = literalPath }; this.CopyItem(paths, copyPath, recurse, copyContainers, context); context.ThrowFirstErrorOrDoNothing(); return context.GetAccumulatedObjects(); }
/// <summary> /// Processes records from the input pipeline. /// For each input file, the command retrieves its /// corresponding security descriptor. /// </summary> protected override void ProcessRecord() { Collection<PSObject> sd = null; AccessControlSections sections = AccessControlSections.Owner | AccessControlSections.Group | AccessControlSections.Access; if (_audit) { sections |= AccessControlSections.Audit; } if (_inputObject != null) { PSMethodInfo methodInfo = _inputObject.Methods["GetSecurityDescriptor"]; if (methodInfo != null) { object customDescriptor = null; try { customDescriptor = PSObject.Base(methodInfo.Invoke()); if (!(customDescriptor is FileSystemSecurity)) { customDescriptor = new CommonSecurityDescriptor(false, false, customDescriptor.ToString()); } } catch (Exception e) { // Calling user code, Catch-all OK CommandProcessorBase.CheckForSevereException(e); ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.MethodInvokeFail, "GetAcl_OperationNotSupported" ); WriteError(er); return; } WriteObject(customDescriptor, true); } else { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.GetMethodNotFound, "GetAcl_OperationNotSupported" ); WriteError(er); } } else { foreach (string p in Path) { List<string> pathsToProcess = new List<string>(); string currentPath = null; try { if (_isLiteralPath) { pathsToProcess.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } else { Collection<PathInfo> resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext); foreach (PathInfo pi in resolvedPaths) { pathsToProcess.Add(pi.Path); } } foreach (string rp in pathsToProcess) { currentPath = rp; CmdletProviderContext context = new CmdletProviderContext(this.Context); context.SuppressWildcardExpansion = true; if (!InvokeProvider.Item.Exists(rp, false, _isLiteralPath)) { ErrorRecord er = SecurityUtils.CreatePathNotFoundErrorRecord( rp, "GetAcl_PathNotFound" ); WriteError(er); continue; } InvokeProvider.SecurityDescriptor.Get(rp, sections, context); sd = context.GetAccumulatedObjects(); if (sd != null) { AddBrokeredProperties( sd, _audit, AllCentralAccessPolicies); WriteObject(sd, true); } } } catch (NotSupportedException) { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.OperationNotSupportedOnPath, "GetAcl_OperationNotSupported", currentPath ); WriteError(er); } catch (ItemNotFoundException) { ErrorRecord er = SecurityUtils.CreatePathNotFoundErrorRecord( p, "GetAcl_PathNotFound_Exception" ); WriteError(er); continue; } } } }
/// <summary> /// Creates a new property on the specified item /// </summary> /// /// <param name="paths"> /// The path(s) to the item(s) on which the new property should be created. /// </param> /// /// <param name="property"> /// The name of the property that should be created. /// </param> /// /// <param name="type"> /// The type of the property that should be created. /// </param> /// /// <param name="value"> /// The new value of the property that should be created. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// A property table containing the properties and their values. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal Collection<PSObject> NewProperty( string[] paths, string property, string type, object value, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } if (property == null) { throw PSTraceSource.NewArgumentNullException("property"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; NewProperty(paths, property, type, value, context); context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> results = context.GetAccumulatedObjects(); return results; } // NewProperty
/// <summary> /// Adds the specified drive to the current scope. /// </summary> /// /// <param name="drive"> /// The drive to be added to the current scope. /// </param> /// /// <param name="scopeID"> /// The ID for the scope to add the drive to. The scope ID can be any of the /// "special" scope identifiers like "global", "local", or "private" or it /// can be a numeric identifier that is a count of the number of parent /// scopes up from the current scope to put the drive in. /// If this parameter is null or empty the drive will be placed in the /// current scope. /// </param> /// /// <returns> /// The drive that was added, if any. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="drive"/> is null. /// </exception> /// /// <exception cref="ArgumentException"> /// If the drive already exists, /// or /// If <paramref name="drive"/>.Name contains one or more invalid characters; ~ / \\ . : /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider is not a DriveCmdletProvider. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// The provider for the <paramref name="drive"/> could not be found. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception or returned null. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If creating the drive will overflow the MaximumDriveCount limit. /// </exception> /// internal PSDriveInfo NewDrive(PSDriveInfo drive, string scopeID) { if (drive == null) { throw PSTraceSource.NewArgumentNullException("drive"); } PSDriveInfo result = null; // Construct a CmdletProviderContext and call the override CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); NewDrive(drive, scopeID, context); context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> successObjects = context.GetAccumulatedObjects(); if (successObjects != null && successObjects.Count > 0) { Dbg.Diagnostics.Assert( successObjects.Count == 1, "NewDrive should only add one PSDriveInfo object to the pipeline"); // set the return value to the first drive (should only be one). if (!successObjects[0].immediateBaseObjectIsEmpty) { result = (PSDriveInfo)successObjects[0].BaseObject; } } return result; } // NewDrive
protected override void ProcessRecord() { AccessControlSections accessControlSection = AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group; if (this.audit) { accessControlSection = accessControlSection | AccessControlSections.Audit; } if (this.inputObject == null) { string[] path = this.Path; for (int i = 0; i < (int)path.Length; i++) { string str = path[i]; List<string> strs = new List<string>(); string str1 = null; try { if (!this.isLiteralPath) { Collection<PathInfo> resolvedPSPathFromPSPath = base.SessionState.Path.GetResolvedPSPathFromPSPath(str, base.CmdletProviderContext); foreach (PathInfo pathInfo in resolvedPSPathFromPSPath) { strs.Add(pathInfo.Path); } } else { strs.Add(base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(str)); } foreach (string str2 in strs) { str1 = str2; CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(base.Context); cmdletProviderContext.SuppressWildcardExpansion = true; if (base.InvokeProvider.Item.Exists(str2, false, this.isLiteralPath)) { base.InvokeProvider.SecurityDescriptor.Get(str2, accessControlSection, cmdletProviderContext); Collection<PSObject> accumulatedObjects = cmdletProviderContext.GetAccumulatedObjects(); if (accumulatedObjects == null) { continue; } SecurityDescriptorCommandsBase.AddBrokeredProperties(accumulatedObjects, this.audit, this.allCentralAccessPolicies); base.WriteObject(accumulatedObjects, true); } else { ErrorRecord errorRecord = SecurityUtils.CreatePathNotFoundErrorRecord(str2, "GetAcl_PathNotFound"); base.WriteError(errorRecord); } } } catch (NotSupportedException notSupportedException) { object[] objArray = new object[1]; objArray[0] = str1; ErrorRecord errorRecord1 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.OperationNotSupportedOnPath, "GetAcl_OperationNotSupported", objArray); base.WriteError(errorRecord1); } catch (ItemNotFoundException itemNotFoundException) { ErrorRecord errorRecord2 = SecurityUtils.CreatePathNotFoundErrorRecord(str, "GetAcl_PathNotFound_Exception"); base.WriteError(errorRecord2); } } } else { PSMethodInfo item = this.inputObject.Methods["GetSecurityDescriptor"]; if (item == null) { ErrorRecord errorRecord3 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.GetMethodNotFound, "GetAcl_OperationNotSupported", new object[0]); base.WriteError(errorRecord3); return; } else { object commonSecurityDescriptor = null; try { commonSecurityDescriptor = PSObject.Base(item.Invoke(new object[0])); if (commonSecurityDescriptor as FileSystemSecurity == null) { commonSecurityDescriptor = new CommonSecurityDescriptor(false, false, commonSecurityDescriptor.ToString()); } } catch (Exception exception1) { Exception exception = exception1; CommandProcessorBase.CheckForSevereException(exception); ErrorRecord errorRecord4 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.MethodInvokeFail, "GetAcl_OperationNotSupported", new object[0]); base.WriteError(errorRecord4); return; } base.WriteObject(commonSecurityDescriptor, true); return; } } }
} // GetChildNames /// <summary> /// Gets the child names of the item at the specified path by /// manually recursing through all the containers instead of /// allowing the provider to do the recursion. /// </summary> /// /// <param name="providerInstance"> /// The provider instance to use. /// </param> /// /// <param name="providerPath"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="relativePath"> /// The path the name is relative to. /// </param> /// /// <param name="recurse"> /// If true all names in the subtree should be returned. /// </param> /// /// <param name="depth"> /// Current depth of recursion; special case uint.MaxValue performs full recursion. /// </param> /// /// <param name="returnContainers"> /// Determines if all containers should be returned or only those containers that match the /// filter(s). /// </param> /// /// <param name="includeMatcher"> /// A set of filters that the names must match to be returned. /// </param> /// /// <param name="excludeMatcher"> /// A set of filters that the names cannot match to be returned. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private void DoGetChildNamesManually( CmdletProvider providerInstance, string providerPath, string relativePath, ReturnContainers returnContainers, Collection<WildcardPattern> includeMatcher, Collection<WildcardPattern> excludeMatcher, CmdletProviderContext context, bool recurse, uint depth) { Dbg.Diagnostics.Assert( providerInstance != null, "The providerInstance should have been verified by the caller"); Dbg.Diagnostics.Assert( providerPath != null, "The paths should have been verified by the caller"); Dbg.Diagnostics.Assert( context != null, "The context should have been verified by the caller"); string newProviderPath = MakePath( providerInstance, providerPath, relativePath, context); CmdletProviderContext childNamesContext = new CmdletProviderContext(context); try { // First get all children that match the filters and write them out GetChildNames( providerInstance, newProviderPath, ReturnContainers.ReturnMatchingContainers, childNamesContext); Collection<PSObject> results = childNamesContext.GetAccumulatedObjects(); foreach (PSObject result in results) { // Making sure to obey the StopProcessing. if (context.Stopping) { return; } string name = result.BaseObject as string; if (name == null) { continue; } bool isIncludeMatch = SessionStateUtilities.MatchesAnyWildcardPattern( name, includeMatcher, true); if (isIncludeMatch) { if (!SessionStateUtilities.MatchesAnyWildcardPattern( name, excludeMatcher, false)) { string resultPath = MakePath(providerInstance, relativePath, name, context); context.WriteObject(resultPath); } } } if (recurse) { // Now get all the children that are containers and recurse into them // Limiter for recursion if (depth > 0) // this includes special case 'depth == uint.MaxValue' for unlimited recursion { GetChildNames( providerInstance, newProviderPath, ReturnContainers.ReturnAllContainers, childNamesContext); results = childNamesContext.GetAccumulatedObjects(); foreach (PSObject result in results) { // Making sure to obey the StopProcessing. if (context.Stopping) { return; } string name = result.BaseObject as string; if (name == null) { continue; } // Generate the relative path from the provider path string resultRelativePath = MakePath( providerInstance, relativePath, name, context); // Generate the provider path for the child item to see // if it is a container string resultProviderPath = MakePath( providerInstance, providerPath, resultRelativePath, context); // If the item is a container recurse into it and output its // child names if (IsItemContainer(providerInstance, resultProviderPath, context)) { DoGetChildNamesManually( providerInstance, providerPath, resultRelativePath, returnContainers, includeMatcher, excludeMatcher, context, true, depth - 1); } } // foreach } // if } // recurse } finally { childNamesContext.RemoveStopReferral(); } } // DoGetChildNamesRecurseManually
} // GetChildItemsDynamicParameters #endregion GetChildItems #region GetChildNames /// <summary> /// Gets names of the children of the specified path. /// </summary> /// /// <param name="paths"> /// The paths to the items 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="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// An array of strings that contains the names of the children of the specified /// container. /// </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> /// internal Collection<string> GetChildNames( string[] paths, ReturnContainers returnContainers, bool recurse, uint depth, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; foreach (string path in paths) { if (path == null) { throw PSTraceSource.NewArgumentNullException("paths"); } GetChildNames(path, returnContainers, recurse, depth, context); } context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> objectResults = context.GetAccumulatedObjects(); Collection<string> results = new Collection<string>(); foreach (PSObject resultObject in objectResults) { results.Add(resultObject.BaseObject as string); } return results; } // GetChildNames
} // GetChildItems /// <summary> /// Since we can't do include and exclude filtering on items we have to /// do the recursion ourselves. We get each child name and see if it matches /// the include and exclude filters. If the child is a container we recurse /// into that container. /// </summary> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <param name="path"> /// The path to the item to get the children from. /// </param> /// /// <param name="recurse"> /// Recurse into sub-containers when getting children. /// </param> /// /// <param name="context"> /// The context under which the command is running. /// </param> /// /// <param name="childrenNotMatchingFilterCriteria"> /// The count of items that do not match any include/exclude criteria. /// </param> /// /// <param name="processMode">Indicates if this is a Enumerate/Remove operation</param> /// /// <param name="skipIsItemContainerCheck">a hint used to skip IsItemContainer checks</param> /// /// <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> /// private void ProcessPathItems( CmdletProvider providerInstance, string path, bool recurse, CmdletProviderContext context, out int childrenNotMatchingFilterCriteria, ProcessMode processMode = ProcessMode.Enumerate, bool skipIsItemContainerCheck = false) { ContainerCmdletProvider containerCmdletProvider = GetContainerProviderInstance(providerInstance); childrenNotMatchingFilterCriteria = 0; Dbg.Diagnostics.Assert( providerInstance != null, "The caller should have verified the providerInstance"); Dbg.Diagnostics.Assert( path != null, "The caller should have verified the path"); Dbg.Diagnostics.Assert( context != null, "The caller should have verified the context"); // 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 the item is a container we have to filter its children // Use a hint + lazy evaluation to skip a container check if (skipIsItemContainerCheck || IsItemContainer(providerInstance, path, context)) { CmdletProviderContext newContext = new CmdletProviderContext(context); Collection<PSObject> childNameObjects = null; System.Collections.Generic.Dictionary<string, bool> filteredChildNameDictionary = null; try { // Get all the child names GetChildNames( providerInstance, path, (recurse) ? ReturnContainers.ReturnAllContainers : ReturnContainers.ReturnMatchingContainers, newContext); newContext.WriteErrorsToContext(context); childNameObjects = newContext.GetAccumulatedObjects(); // The code above initially retrieves all of the containers so that it doesn't limit the recursion, // but then emits the non-matching container further down. The public API doesn't support a way to // differentiate the two, so we need to do a diff. // So if there was a filter, do it again to get the fully filtered items. if (recurse && (providerInstance.IsFilterSet())) { newContext.RemoveStopReferral(); newContext = new CmdletProviderContext(context); filteredChildNameDictionary = new System.Collections.Generic.Dictionary<string, bool>(); GetChildNames( providerInstance, path, ReturnContainers.ReturnMatchingContainers, newContext); var filteredChildNameObjects = newContext.GetAccumulatedObjects(); foreach (PSObject filteredChildName in filteredChildNameObjects) { string filteredName = filteredChildName.BaseObject as string; if (filteredName != null) { filteredChildNameDictionary[filteredName] = true; } } } } finally { newContext.RemoveStopReferral(); } // Now loop through all the child objects matching the filters and recursing // into containers for (int index = 0; index < childNameObjects.Count; ++index) { // Making sure to obey the StopProcessing. if (context.Stopping) { return; } string childName = childNameObjects[index].BaseObject as string; if (childName == null) { continue; } // Generate the provider path for the child string qualifiedPath = MakePath(providerInstance, path, childName, context); if (qualifiedPath == null) { continue; } bool isIncludeMatch = !context.SuppressWildcardExpansion && SessionStateUtilities.MatchesAnyWildcardPattern( childName, includeMatcher, true); if (isIncludeMatch) { if (!SessionStateUtilities.MatchesAnyWildcardPattern( childName, excludeMatcher, false)) { bool emitItem = true; if (filteredChildNameDictionary != null) { bool isChildNameInDictionary = false; emitItem = filteredChildNameDictionary.TryGetValue(childName, out isChildNameInDictionary); } if (emitItem) { if (processMode == ProcessMode.Delete) { containerCmdletProvider.RemoveItem(qualifiedPath, false, context); } else if (processMode != ProcessMode.Delete) { // The object is a match so get it and write it out. GetItemPrivate(providerInstance, qualifiedPath, context); } } } else { childrenNotMatchingFilterCriteria++; } } else { childrenNotMatchingFilterCriteria++; } // Now recurse if it is a container if (recurse && IsItemContainer(providerInstance, qualifiedPath, context)) { // Making sure to obey the StopProcessing. if (context.Stopping) { return; } // The item is a container so recurse into it. ProcessPathItems(providerInstance, qualifiedPath, recurse, context, out childrenNotMatchingFilterCriteria, processMode, skipIsItemContainerCheck: true); } } // for each childName } else { // The path is not a container so write it out if its name // matches the filter string childName = path; childName = GetChildName(providerInstance, path, context, true); // Write out the object if it is a match bool isIncludeMatch = SessionStateUtilities.MatchesAnyWildcardPattern( childName, includeMatcher, true); if (isIncludeMatch) { if (!SessionStateUtilities.MatchesAnyWildcardPattern( childName, excludeMatcher, false)) { if (processMode != ProcessMode.Delete) { // The object is a match so get it and write it out. GetItemPrivate(providerInstance, path, context); } else { // The object is a match so, remove it. containerCmdletProvider.RemoveItem(path, recurse, context); } } } } } // ProcessPathItems
internal Collection<PSObject> SetProperty(string[] paths, PSObject property, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } if (property == null) { throw PSTraceSource.NewArgumentNullException("properties"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Force = force, SuppressWildcardExpansion = literalPath }; this.SetProperty(paths, property, context); context.ThrowFirstErrorOrDoNothing(); return context.GetAccumulatedObjects(); }
internal Collection<PSObject> SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException("securityDescriptor"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); this.SetSecurityDescriptor(path, securityDescriptor, context); context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> accumulatedObjects = context.GetAccumulatedObjects(); if (accumulatedObjects == null) { accumulatedObjects = new Collection<PSObject>(); } return accumulatedObjects; }
private void DoGetChildNamesManually(CmdletProvider providerInstance, string providerPath, string relativePath, ReturnContainers returnContainers, Collection<WildcardPattern> includeMatcher, Collection<WildcardPattern> excludeMatcher, CmdletProviderContext context, bool recurse) { string path = this.MakePath(providerInstance, providerPath, relativePath, context); CmdletProviderContext context2 = new CmdletProviderContext(context); try { this.GetChildNames(providerInstance, path, ReturnContainers.ReturnMatchingContainers, context2); foreach (PSObject obj2 in context2.GetAccumulatedObjects()) { if (context.Stopping) { return; } string baseObject = obj2.BaseObject as string; if (((baseObject != null) && SessionStateUtilities.MatchesAnyWildcardPattern(baseObject, includeMatcher, true)) && !SessionStateUtilities.MatchesAnyWildcardPattern(baseObject, excludeMatcher, false)) { string str3 = this.MakePath(providerInstance, relativePath, baseObject, context); context.WriteObject(str3); } } if (recurse) { this.GetChildNames(providerInstance, path, ReturnContainers.ReturnAllContainers, context2); foreach (PSObject obj3 in context2.GetAccumulatedObjects()) { if (context.Stopping) { return; } string child = obj3.BaseObject as string; if (child != null) { string str5 = this.MakePath(providerInstance, relativePath, child, context); string str6 = this.MakePath(providerInstance, providerPath, str5, context); if (this.IsItemContainer(providerInstance, str6, context)) { this.DoGetChildNamesManually(providerInstance, providerPath, str5, returnContainers, includeMatcher, excludeMatcher, context, true); } } } } } finally { context2.RemoveStopReferral(); } }
internal Collection<PSObject> CopyProperty(string[] sourcePaths, string sourceProperty, string destinationPath, string destinationProperty, bool force, bool literalPath) { if (sourcePaths == null) { throw PSTraceSource.NewArgumentNullException("sourcePaths"); } if (sourceProperty == null) { throw PSTraceSource.NewArgumentNullException("sourceProperty"); } if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException("destinationPath"); } if (destinationProperty == null) { throw PSTraceSource.NewArgumentNullException("destinationProperty"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Force = force, SuppressWildcardExpansion = literalPath }; this.CopyProperty(sourcePaths, sourceProperty, destinationPath, destinationProperty, context); context.ThrowFirstErrorOrDoNothing(); return context.GetAccumulatedObjects(); }
} // SetItemDynamicParameters #endregion SetItem #region ClearItem /// <summary> /// Clears the specified object. Depending on the provider that the path /// maps to, this could mean the properties and/or content and/or value is /// cleared. /// </summary> /// /// <param name="paths"> /// The path(s) to the object. It can be either a relative (most common) /// or absolute path. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// The items that were cleared. /// </returns> /// /// <remarks> /// If an error occurs that error will be thrown. /// </remarks> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal Collection<PSObject> ClearItem(string[] paths, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; ClearItem(paths, context); context.ThrowFirstErrorOrDoNothing(); return context.GetAccumulatedObjects(); } // ClearItem
private Collection<PSObject> GetChildNamesInDir(string dir, string leafElement, bool getAllContainers, CmdletProviderContext context, bool dirIsProviderPath, PSDriveInfo drive, ContainerCmdletProvider provider, out string modifiedDirPath) { string updatedPath = null; string updatedFilter = null; Collection<PSObject> collection4; string filter = context.Filter; bool flag = provider.ConvertPath(leafElement, context.Filter, ref updatedPath, ref updatedFilter, context); if (flag) { tracer.WriteLine("Provider converted path and filter.", new object[0]); tracer.WriteLine("Original path: " + leafElement, new object[0]); tracer.WriteLine("Converted path: " + updatedPath, new object[0]); tracer.WriteLine("Original filter: " + context.Filter, new object[0]); tracer.WriteLine("Converted filter: " + updatedFilter, new object[0]); leafElement = updatedPath; context.Filter = updatedFilter; } ReturnContainers returnAllContainers = ReturnContainers.ReturnAllContainers; if (!getAllContainers) { returnAllContainers = ReturnContainers.ReturnMatchingContainers; } CmdletProviderContext context2 = new CmdletProviderContext(context); context2.SetFilters(new Collection<string>(), new Collection<string>(), context.Filter); try { string path = null; modifiedDirPath = null; if (dirIsProviderPath) { modifiedDirPath = path = context.SuppressWildcardExpansion ? dir : RemoveGlobEscaping(dir); } else { modifiedDirPath = GetMshQualifiedPath(dir, drive); ProviderInfo info = null; CmdletProvider providerInstance = null; Collection<string> collection = this.GetGlobbedProviderPathsFromMonadPath(modifiedDirPath, false, context2, out info, out providerInstance); modifiedDirPath = context.SuppressWildcardExpansion ? modifiedDirPath : RemoveGlobEscaping(modifiedDirPath); if (collection.Count > 0) { path = collection[0]; } else { if (flag) { context.Filter = filter; } return new Collection<PSObject>(); } } if (provider.HasChildItems(path, context2)) { provider.GetChildNames(path, returnAllContainers, context2); } if (context2.HasErrors()) { Collection<ErrorRecord> accumulatedErrorObjects = context2.GetAccumulatedErrorObjects(); if ((accumulatedErrorObjects != null) && (accumulatedErrorObjects.Count > 0)) { foreach (ErrorRecord record in accumulatedErrorObjects) { context.WriteError(record); } } } Collection<PSObject> accumulatedObjects = context2.GetAccumulatedObjects(); if (flag) { context.Filter = filter; } collection4 = accumulatedObjects; } finally { context2.RemoveStopReferral(); } return collection4; }
internal Collection<PSObject> GetChildItems(string[] paths, bool recurse, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Force = force, SuppressWildcardExpansion = literalPath }; foreach (string str in paths) { if (str == null) { throw PSTraceSource.NewArgumentNullException("paths"); } this.GetChildItems(str, recurse, context); } context.ThrowFirstErrorOrDoNothing(); return context.GetAccumulatedObjects(); }
internal Collection<string> GetChildNames(string[] paths, ReturnContainers returnContainers, bool recurse, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Force = force, SuppressWildcardExpansion = literalPath }; foreach (string str in paths) { if (str == null) { throw PSTraceSource.NewArgumentNullException("paths"); } this.GetChildNames(str, returnContainers, recurse, context); } context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> accumulatedObjects = context.GetAccumulatedObjects(); Collection<string> collection2 = new Collection<string>(); foreach (PSObject obj2 in accumulatedObjects) { collection2.Add(obj2.BaseObject as string); } return collection2; }
internal PSDriveInfo NewDrive(PSDriveInfo drive, string scopeID) { if (drive == null) { throw PSTraceSource.NewArgumentNullException("drive"); } PSDriveInfo baseObject = null; CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); this.NewDrive(drive, scopeID, context); context.ThrowFirstErrorOrDoNothing(); Collection<PSObject> accumulatedObjects = context.GetAccumulatedObjects(); if (((accumulatedObjects != null) && (accumulatedObjects.Count > 0)) && !accumulatedObjects[0].immediateBaseObjectIsEmpty) { baseObject = (PSDriveInfo) accumulatedObjects[0].BaseObject; } return baseObject; }
private void DoManualGetChildItems(CmdletProvider providerInstance, string path, bool recurse, CmdletProviderContext context, bool skipIsItemContainerCheck = false) { Collection<WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(context.Include, WildcardOptions.IgnoreCase); Collection<WildcardPattern> collection2 = SessionStateUtilities.CreateWildcardsFromStrings(context.Exclude, WildcardOptions.IgnoreCase); if (skipIsItemContainerCheck || this.IsItemContainer(providerInstance, path, context)) { CmdletProviderContext context2 = new CmdletProviderContext(context); Collection<PSObject> accumulatedObjects = null; Dictionary<string, bool> dictionary = null; try { this.GetChildNames(providerInstance, path, recurse ? ReturnContainers.ReturnAllContainers : ReturnContainers.ReturnMatchingContainers, context2); context2.WriteErrorsToContext(context); accumulatedObjects = context2.GetAccumulatedObjects(); if (recurse && providerInstance.IsFilterSet()) { context2.RemoveStopReferral(); context2 = new CmdletProviderContext(context); Collection<PSObject> collection4 = new Collection<PSObject>(); dictionary = new Dictionary<string, bool>(); this.GetChildNames(providerInstance, path, ReturnContainers.ReturnMatchingContainers, context2); foreach (PSObject obj2 in context2.GetAccumulatedObjects()) { string baseObject = obj2.BaseObject as string; if (baseObject != null) { dictionary[baseObject] = true; } } } } finally { context2.RemoveStopReferral(); } for (int i = 0; i < accumulatedObjects.Count; i++) { if (context.Stopping) { return; } string child = accumulatedObjects[i].BaseObject as string; if (child != null) { string str3 = this.MakePath(providerInstance, path, child, context); if (str3 != null) { if (SessionStateUtilities.MatchesAnyWildcardPattern(child, patterns, true) && !SessionStateUtilities.MatchesAnyWildcardPattern(child, collection2, false)) { bool flag2 = true; if (dictionary != null) { bool flag3 = false; flag2 = dictionary.TryGetValue(child, out flag3); } if (flag2) { this.GetItemPrivate(providerInstance, str3, context); } } if (this.IsItemContainer(providerInstance, str3, context) && recurse) { if (context.Stopping) { return; } this.DoManualGetChildItems(providerInstance, str3, recurse, context, true); } } } } } else { string text = path; text = this.GetChildName(providerInstance, path, context, true); if (SessionStateUtilities.MatchesAnyWildcardPattern(text, patterns, true) && !SessionStateUtilities.MatchesAnyWildcardPattern(text, collection2, false)) { this.GetItemPrivate(providerInstance, path, context); } } }
/// <summary> /// Looks up the specified variable and returns the context under which /// the variable was found as well as the variable itself. /// </summary> /// /// <param name="variablePath"> /// The VariablePath helper for the variable. /// </param> /// /// <param name="scope"> /// The scope the variable was found in. Null if the variable wasn't found. /// </param> /// /// <param name="context"> /// Returns the context under which the variable was found. The context will /// have the drive data already set. This will be null if the variable was /// not found. /// </param> /// /// <param name="origin"> /// The origin of the caller of this API /// </param> /// /// <returns> /// The variable if it was found or null if it was not. /// </returns> /// /// <remarks> /// The <paramref name="variablePath" /> is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. If any other drive specifier /// is found the lookup goes in the following order. /// - current scope /// - each consecutive parent scope until the variable is found. /// - global scope /// </remarks> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="variablePath"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="variablePath"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="variablePath"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="variablePath"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// #pragma warning disable 0162 internal object GetVariableValueFromProvider( VariablePath variablePath, out CmdletProviderContext context, out SessionStateScope scope, CommandOrigin origin) { scope = null; if (variablePath == null) { throw PSTraceSource.NewArgumentNullException("variablePath"); } Dbg.Diagnostics.Assert( !variablePath.IsVariable, "This method can only be used to retrieve provider content"); context = null; DriveScopeItemSearcher searcher = new DriveScopeItemSearcher( this, variablePath); object result = null; do // false loop { if (!searcher.MoveNext()) { break; } PSDriveInfo drive = ((IEnumerator<PSDriveInfo>)searcher).Current; if (drive == null) { break; } // Create a new CmdletProviderContext and set the drive data context = new CmdletProviderContext(this.ExecutionContext, origin); context.Drive = drive; #if true // PSVariable get/set is the get/set of content in the provider Collection<IContentReader> readers = null; try { readers = GetContentReader(new string[] { variablePath.QualifiedName }, context); } // If the item is not found we just return null like the normal // variable semantics. catch (ItemNotFoundException) { break; } catch (DriveNotFoundException) { break; } catch (ProviderNotFoundException) { break; } catch (NotImplementedException notImplemented) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notImplemented, false); } catch (NotSupportedException notSupported) { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, providerInfo, variablePath.QualifiedName, notSupported, false); } if (readers == null || readers.Count == 0) { // The drive was found but the path was wrong or something so return null. // We don't want to continue searching if the provider didn't support content // or the path wasn't found. break; } if (readers.Count > 1) { // Since more than one path was resolved, this is an error. //Before throwing exception. Close the readers to avoid sharing violation. foreach (IContentReader r in readers) { r.Close(); } PSArgumentException argException = PSTraceSource.NewArgumentException( "path", SessionStateStrings.VariablePathResolvedToMultiple, variablePath.QualifiedName); // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, providerInfo, variablePath.QualifiedName, argException); } IContentReader reader = readers[0]; try { // Read all the content IList resultList = reader.Read(-1); if (resultList != null) { if (resultList.Count == 0) { result = null; } else if (resultList.Count == 1) { result = resultList[0]; } else { result = resultList; } } } catch (Exception e) // Third-party callout, catch-all OK { // First get the provider for the path. ProviderInfo providerInfo = null; string unused = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); CommandProcessorBase.CheckForSevereException(e); ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, providerInfo, variablePath.QualifiedName, e); throw providerException; } finally { reader.Close(); } #else try { GetItem(variablePath.LookupPath.ToString(), context); } catch (ItemNotFoundException) { break; } Collection<PSObject> items = context.GetAccumulatedObjects (); if (items != null && items.Count > 0) { result = items[0]; if (!items[0].basObjectIsEmpty) { result = items[0].BaseObject; } try { DictionaryEntry entry = (DictionaryEntry)result; result = entry.Value; } // Since DictionaryEntry is a value type we have to // try the cast and catch the exception to determine // if it is a DictionaryEntry type. catch (InvalidCastException) { } } #endif break; } while (false); return result; } // GetVariableFromProvider