/// <summary> /// Internal wrapper for the GetItem protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to retrieve. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Nothing is returned, but all objects should be written to the WriteObject method. /// </returns> /// internal void GetItem(string path, CmdletProviderContext context) { Context = context; // Call virtual method GetItem(path); } // GetItem
/// <summary> /// Internal wrapper for the MakePath protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="parent"> /// The parent segment of a path to be joined with the child. /// </param> /// /// <param name="child"> /// The child segment of a path to be joined with the parent. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// A string that represents the parent and child segments of the path /// joined by a path separator. /// </returns> /// /// <remarks> /// This method should use lexical joining of two path segments with a path /// separator character. It should not validate the path as a legal fully /// qualified path in the provider namespace as each parameter could be only /// partial segments of a path and joined they may not generate a fully /// qualified path. /// Example: the file system provider may get "windows\system32" as the parent /// parameter and "foo.dll" as the child parameter. The method should join these /// with the "\" separator and return "windows\system32\foo.dll". Note that /// the returned path is not a fully qualified file system path. /// /// Also beware that the path segments may contain characters that are illegal /// in the provider namespace. These characters are most likely being used /// for globbing and should not be removed by the implementation of this method. /// </remarks> /// internal string MakePath( string parent, string child, CmdletProviderContext context) { Context = context; // Call virtual method return MakePath(parent, child); } // MakePath
/// <summary> /// Internal wrapper for the GetChildItems protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path (or name in a flat namespace) to the item from which to retrieve the children. /// </param> /// /// <param name="recurse"> /// True if all children in a subtree should be retrieved, false if only a single /// level of children should be retrieved. This parameter should only be true for /// the NavigationCmdletProvider derived class. /// </param> /// /// <param name="depth"> /// Limits the depth of recursion; uint.MaxValue performs full recursion. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Nothing is returned, but all children should be written to the Write*Object or /// Write*Objects method. /// </returns> /// internal void GetChildItems( string path, bool recurse, uint depth, CmdletProviderContext context) { Context = context; // Call virtual method GetChildItems(path, recurse, depth); } // GetChildItems
} // GetSecurityDescriptor /// <summary> /// Internal wrapper for the SetSecurityDescriptor protected method. This method will /// only be called if the provider implements the ISecurityDescriptorCmdletProvider interface. /// </summary> /// /// <param name="path"> /// The path to the item to set the new security descriptor on. /// </param> /// /// <param name="securityDescriptor"> /// The new security descriptor for the item. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Nothing. The security descriptor object that was set should be written /// to the context. /// </returns> /// internal void SetSecurityDescriptor( string path, ObjectSecurity securityDescriptor, CmdletProviderContext context) { Context = context; ISecurityDescriptorCmdletProvider permissionProvider = this as ISecurityDescriptorCmdletProvider; // // if this is not supported, the fn will throw // CheckIfSecurityDescriptorInterfaceIsSupported(permissionProvider); // Call interface method permissionProvider.SetSecurityDescriptor(path, securityDescriptor); } // SetSecurityDescriptor
/// <summary> /// Internal wrapper for the GetSecurityDescriptor protected method. This method will /// only be called if the provider implements the ISecurityDescriptorCmdletProvider interface. /// </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> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Nothing. An instance of an object that represents the security descriptor /// for the item specified by the path should be written to the context. /// </returns> /// internal void GetSecurityDescriptor( string path, AccessControlSections sections, CmdletProviderContext context) { Context = context; ISecurityDescriptorCmdletProvider permissionProvider = this as ISecurityDescriptorCmdletProvider; // // if this is not supported, the fn will throw // CheckIfSecurityDescriptorInterfaceIsSupported(permissionProvider); // Call interface method permissionProvider.GetSecurityDescriptor(path, sections); } // GetSecurityDescriptor
/// <summary> /// Determines if an item at the specified path exists. /// </summary> protected override void ProcessRecord() { if (_paths == null || _paths.Length == 0) { WriteError(new ErrorRecord( new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), "NullPathNotPermitted", ErrorCategory.InvalidArgument, Path)); return; } CmdletProviderContext currentContext = CmdletProviderContext; foreach (string path in _paths) { bool result = false; if (path == null) { WriteError(new ErrorRecord( new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), "NullPathNotPermitted", ErrorCategory.InvalidArgument, Path)); continue; } if (string.IsNullOrWhiteSpace(path)) { WriteObject(result); continue; } try { if (IsValid) { result = SessionState.Path.IsValid(path, currentContext); } else { if (this.PathType == TestPathType.Container) { result = InvokeProvider.Item.IsContainer(path, currentContext); } else if (this.PathType == TestPathType.Leaf) { result = InvokeProvider.Item.Exists(path, currentContext) && !InvokeProvider.Item.IsContainer(path, currentContext); } else { result = InvokeProvider.Item.Exists(path, currentContext); } } } // Any of the known exceptions means the path does not exist. catch (PSNotSupportedException) { } catch (DriveNotFoundException) { } catch (ProviderNotFoundException) { } catch (ItemNotFoundException) { } WriteObject(result); } }
} // Exists /// <summary> /// Gives the provider to attach additional parameters to /// the test-path cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> /// internal object ItemExistsDynamicParameters( string path, CmdletProviderContext context) { Context = context; return ItemExistsDynamicParameters(path); } // ItemExistsDynamicParameters
} // RemovePropertyValueAtDynamicParameters /// <summary> /// Adds the specified properties of the item at the specified path at the specified /// position if the property is a multivalued property. /// </summary> /// /// <param name="path"> /// The path to the item to add the property to. /// </param> /// /// <param name="position"> /// The position to place the new value of the property. /// </param> /// /// <param name="propertyValue"> /// A PSObject which contains a collection of the name, type, value /// of the properties to be added. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Nothing. An instance of PSObject representing the properties that were set /// should be passed to the WriteObject() method. /// </returns> /// internal void AddPropertyValueAt( string path, object position, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IMultivaluePropertyCmdletProvider propertyProvider = this as IMultivaluePropertyCmdletProvider; if (propertyProvider == null) { throw providerBaseTracer.NewNotSupportedException( "SessionStateStrings", "IMultivaluePropertyCmdletProvider_NotSupported"); } // Call interface method propertyProvider.AddPropertyValueAt(path, position, propertyValue); } // AddPropertyValueAt
} // SetPropertyDynamicParameters /// <summary> /// Internal wrapper for the ClearProperty protected method. This method will /// only be called if the provider implements the IPropertyCmdletProvider interface. /// </summary> /// /// <param name="path"> /// The path to the item from which the property should be cleared. /// </param> /// /// <param name="propertyName"> /// The name of the property that should be cleared. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <remarks> /// Implement this method when you are providing access to a data store /// that allows dynamic clearing of properties. /// </remarks> /// internal void ClearProperty( string path, Collection<string> propertyName, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.ClearProperty(path, propertyName); } // ClearProperty
} // Start /// <summary> /// Gets an object that defines the additional parameters for the Start implementation /// for a provider. /// </summary> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object StartDynamicParameters(CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; return StartDynamicParameters(); } // StartDynamicParameter
} // GetContentReaderDynamicParameters /// <summary> /// Internal wrapper for the GetContentWriter protected method. This method will /// only be called if the provider implements the IContentCmdletProvider interface. /// </summary> /// /// <param name="path"> /// The path to the item to set content on. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An instance of the IContentWriter for the specified path. /// </returns> /// internal IContentWriter GetContentWriter( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IContentCmdletProvider contentProvider = this as IContentCmdletProvider; if (contentProvider == null) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IContentCmdletProvider_NotSupported); } // Call interface method return contentProvider.GetContentWriter(path); } // GetContentWriter
} // RemoveProperty /// <summary> /// Gives the provider a chance to attach additional parameters to /// the remove-itemproperty cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="propertyName"> /// The name of the property that should be removed. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object RemovePropertyDynamicParameters( string path, string propertyName, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; if (propertyProvider == null) { return null; } return propertyProvider.RemovePropertyDynamicParameters(path, propertyName); } // RemovePropertyDynamicParameters
internal void GetProperty(string path, Collection <string> providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IPropertyCmdletProvider provider = this as IPropertyCmdletProvider; if (provider == null) { throw PSTraceSource.NewNotSupportedException("SessionStateStrings", "IPropertyCmdletProvider_NotSupported", new object[0]); } provider.GetProperty(path, providerSpecificPickList); }
} // NewDrive /// <summary> /// Gives the provider to attach additional parameters to /// the New-PSDrive cmdlet. /// </summary> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object NewDriveDynamicParameters(CmdletProviderContext context) { Context = context; return(NewDriveDynamicParameters()); } // NewDriveDynamicParameters
} // NewDriveDynamicParameters /// <summary> /// Internal wrapper for the RemoveDrive protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="drive"> /// The PSDriveInfo object the represents the mounted drive. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// The drive that was returned from the protected RemoveDrive method. /// </returns> /// internal PSDriveInfo RemoveDrive(PSDriveInfo drive, CmdletProviderContext context) { Context = context; return(RemoveDrive(drive)); } // RemoveDrive
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; } } }
} // GetItem /// <summary> /// Gives the provider to attach additional parameters to /// the get-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> /// internal object GetItemDynamicParameters(string path, CmdletProviderContext context) { Context = context; return GetItemDynamicParameters(path); } // GetItemDynamicParameters
} // InvokeDefaultAction /// <summary> /// Gives the provider to attach additional parameters to /// the invoke-item cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> /// internal object InvokeDefaultActionDynamicParameters( string path, CmdletProviderContext context) { Context = context; return InvokeDefaultActionDynamicParameters(path); } // InvokeDefaultActionDynamicParameters
} // IsValidPath /// <summary> /// Internal wrapper for the ExpandPath protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. Only called for providers that declare /// the ExpandWildcards capability. /// </summary> /// /// <param name="path"> /// The path to expand. Expansion must be consistent with the wildcarding /// rules of PowerShell's WildcardPattern class. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// A list of provider paths that this path expands to. They must all exist. /// </returns> /// internal string[] ExpandPath(string path, CmdletProviderContext context) { Context = context; // Call virtual method return ExpandPath(path); } // IsValidPath
/// <summary> /// Parses the specified path and returns the portion determined by the /// boolean parameters. /// </summary> protected override void ProcessRecord() { StringCollection pathsToParse = new StringCollection(); if (Resolve) { CmdletProviderContext currentContext = CmdletProviderContext; foreach (string path in Path) { // resolve the paths and then parse each one. Collection <PathInfo> resolvedPaths; try { resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(path, currentContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } foreach (PathInfo resolvedPath in resolvedPaths) { try { if (InvokeProvider.Item.Exists(resolvedPath.Path, currentContext)) { pathsToParse.Add(resolvedPath.Path); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } } } } else { pathsToParse.AddRange(Path); } // Now parse each path for (int index = 0; index < pathsToParse.Count; ++index) { string result = null; switch (ParameterSetName) { case isAbsoluteSet: string ignored; bool isPathAbsolute = SessionState.Path.IsPSAbsolute(pathsToParse[index], out ignored); WriteObject(isPathAbsolute); continue; case qualifierSet: int separatorIndex = pathsToParse[index].IndexOf(':'); if (separatorIndex < 0) { FormatException e = new FormatException( StringUtil.Format(NavigationResources.ParsePathFormatError, pathsToParse[index])); WriteError( new ErrorRecord( e, "ParsePathFormatError", // RENAME ErrorCategory.InvalidArgument, pathsToParse[index])); continue; } else { // Check to see if it is provider or drive qualified if (SessionState.Path.IsProviderQualified(pathsToParse[index])) { // The plus 2 is for the length of the provider separator // which is "::" result = pathsToParse[index].Substring( 0, separatorIndex + 2); } else { result = pathsToParse[index].Substring( 0, separatorIndex + 1); } } break; case parentSet: case literalPathSet: try { result = SessionState.Path.ParseParent( pathsToParse[index], string.Empty, CmdletProviderContext, true); } catch (PSNotSupportedException) { // Since getting the parent path is not supported, // the provider must be a container, item, or drive // provider. Since the paths for these types of // providers can't be split, asking for the parent // is asking for an empty string. result = string.Empty; } break; case leafSet: case leafBaseSet: case extensionSet: try { // default handles leafSet result = SessionState.Path.ParseChildName( pathsToParse[index], CmdletProviderContext, true); if (LeafBase) { result = System.IO.Path.GetFileNameWithoutExtension(result); } else if (Extension) { result = System.IO.Path.GetExtension(result); } } catch (PSNotSupportedException) { // Since getting the leaf part of a path is not supported, // the provider must be a container, item, or drive // provider. Since the paths for these types of // providers can't be split, asking for the leaf // is asking for the specified path back. result = pathsToParse[index]; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } break; case noQualifierSet: result = RemoveQualifier(pathsToParse[index]); break; default: Dbg.Diagnostics.Assert( false, "Only a known parameter set should be called"); break; } if (result != null) { WriteObject(result); } } }
/// <summary> /// Gets the content of an item at the specified path. /// </summary> protected override void ProcessRecord() { // TotalCount and Tail should not be specified at the same time. // Throw out terminating error if this is the case. if (_totalCountSpecified && _tailSpecified) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail"); ErrorRecord error = new(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); WriteError(error); return; } if (TotalCount == 0) { // Don't read anything return; } // Get the content readers CmdletProviderContext currentContext = CmdletProviderContext; contentStreams = this.GetContentReaders(Path, currentContext); try { // Iterate through the content holders reading the content foreach (ContentHolder holder in contentStreams) { long countRead = 0; Dbg.Diagnostics.Assert( holder.Reader != null, "All holders should have a reader assigned"); if (_tailSpecified && holder.Reader is not FileSystemContentReaderWriter) { string errMsg = SessionStateStrings.GetContent_TailNotSupported; ErrorRecord error = new(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail); WriteError(error); continue; } // If Tail is negative, we are supposed to read all content out. This is same // as reading forwards. So we read forwards in this case. // If Tail is positive, we seek the right position. Or, if the seek failed // because of an unsupported encoding, we scan forward to get the tail content. if (Tail >= 0) { bool seekSuccess = false; try { seekSuccess = SeekPositionForTail(holder.Reader); } catch (Exception e) { ProviderInvocationException providerException = new( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); WriteError(new ErrorRecord( providerException.ErrorRecord, providerException)); continue; } // If the seek was successful, we start to read forwards from that // point. Otherwise, we need to scan forwards to get the tail content. if (!seekSuccess && !ScanForwardsForTail(holder, currentContext)) { continue; } } if (TotalCount != 0) { IList results = null; do { long countToRead = ReadCount; // Make sure we only ask for the amount the user wanted // I am using TotalCount - countToRead so that I don't // have to worry about overflow if ((TotalCount > 0) && (countToRead == 0 || (TotalCount - countToRead < countRead))) { countToRead = TotalCount - countRead; } try { results = holder.Reader.Read(countToRead); } catch (Exception e) // Catch-all OK. 3rd party callout { ProviderInvocationException providerException = new( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); WriteError(new ErrorRecord( providerException.ErrorRecord, providerException)); break; } if (results != null && results.Count > 0) { countRead += results.Count; if (ReadCount == 1) { // Write out the content as a single object WriteContentObject(results[0], countRead, holder.PathInfo, currentContext); } else { // Write out the content as an array of objects WriteContentObject(results, countRead, holder.PathInfo, currentContext); } } } while (results != null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount)); } } } finally { // close all the content readers CloseContent(contentStreams, false); // Empty the content holder array contentStreams = new List <ContentHolder>(); } }
internal void GetSecurityDescriptor(string path, AccessControlSections sections, CmdletProviderContext context) { this.Context = context; ISecurityDescriptorCmdletProvider permissionProvider = this as ISecurityDescriptorCmdletProvider; CheckIfSecurityDescriptorInterfaceIsSupported(permissionProvider); permissionProvider.GetSecurityDescriptor(path, sections); }
} // CopyPropertyDynamicParameters /// <summary> /// Internal wrapper for the MoveProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. /// </summary> /// /// <param name="sourcePath"> /// The path to the item from which the property should be moved. /// </param> /// /// <param name="sourceProperty"> /// The name of the property that should be moved. /// </param> /// /// <param name="destinationPath"> /// The path to the item to which the property should be moved. /// </param> /// /// <param name="destinationProperty"> /// The name of the property that should be moved to. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <remarks> /// Implement this method when you are providing access to a data store /// that allows dynamic moving of properties. /// </remarks> /// internal void MoveProperty( string sourcePath, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IDynamicPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.MoveProperty(sourcePath, sourceProperty, destinationPath, destinationProperty); } // MoveProperty
internal object NewPropertyDynamicParameters(string path, string propertyName, string propertyTypeName, object value, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IDynamicPropertyCmdletProvider provider = this as IDynamicPropertyCmdletProvider; if (provider == null) { return(null); } return(provider.NewPropertyDynamicParameters(path, propertyName, propertyTypeName, value)); }
} // ClearContent /// <summary> /// Gives the provider a chance to attach additional parameters to /// the clear-content cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object ClearContentDynamicParameters( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IContentCmdletProvider contentProvider = this as IContentCmdletProvider; if (contentProvider == null) { return null; } return contentProvider.ClearContentDynamicParameters(path); } // ClearContentDynamicParameters
internal object RemovePropertyDynamicParameters(string path, string propertyName, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IDynamicPropertyCmdletProvider provider = this as IDynamicPropertyCmdletProvider; if (provider == null) { return(null); } return(provider.RemovePropertyDynamicParameters(path, propertyName)); }
} // GetPropertyDynamicParameters /// <summary> /// Internal wrapper for the SetProperty protected method. This method will /// only be called if the provider implements the IPropertyCmdletProvider interface. /// </summary> /// /// <param name="path"> /// The path to the item to set the properties on. /// </param> /// /// <param name="propertyValue"> /// A PSObject which contains a collection of the name, type, value /// of the properties to be set. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// internal void SetProperty( string path, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.SetProperty(path, propertyValue); } // SetProperty
internal void RenameProperty(string path, string propertyName, string newPropertyName, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IDynamicPropertyCmdletProvider provider = this as IDynamicPropertyCmdletProvider; if (provider == null) { throw PSTraceSource.NewNotSupportedException("SessionStateStrings", "IDynamicPropertyCmdletProvider_NotSupported", new object[0]); } provider.RenameProperty(path, propertyName, newPropertyName); }
} // ClearPropertyValueAtDynamicParameters /// <summary> /// Internal wrapper for the RemovePropertyValueAt protected method. This method will /// only be called if the provider implements the /// IMultivaluePropertyCmdletProvider interface. /// </summary> /// /// <param name="path"> /// The path to the item from which the property value should be removed. /// </param> /// /// <param name="propertyName"> /// The name of the property that the value should be remove from. /// </param> /// /// <param name="at"> /// The position of the value of the property to be removed. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <remarks> /// Implement this method when you are providing access to a data store /// that allows dynamic removing of property values. /// </remarks> /// internal void RemovePropertyValueAt( string path, string propertyName, object at, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IMultivaluePropertyCmdletProvider propertyProvider = this as IMultivaluePropertyCmdletProvider; if (propertyProvider == null) { throw providerBaseTracer.NewNotSupportedException( "SessionStateStrings", "IMultivaluePropertyCmdletProvider_NotSupported"); } // Call interface method propertyProvider.RemovePropertyValueAt(path, propertyName, at); } // RemovePropertyValueAt
internal object SetPropertyDynamicParameters(string path, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IPropertyCmdletProvider provider = this as IPropertyCmdletProvider; if (provider == null) { return(null); } return(provider.SetPropertyDynamicParameters(path, propertyValue)); }
internal void SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor, CmdletProviderContext context) { this.Context = context; ISecurityDescriptorCmdletProvider permissionProvider = this as ISecurityDescriptorCmdletProvider; CheckIfSecurityDescriptorInterfaceIsSupported(permissionProvider); permissionProvider.SetSecurityDescriptor(path, securityDescriptor); }
internal System.Management.Automation.ProviderInfo Start(System.Management.Automation.ProviderInfo providerInfo, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; return(this.Start(providerInfo)); }
/// <summary> /// The main execution method for the get-childitem command. /// </summary> protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; if (_paths == null || _paths.Length == 0) { _paths = new string[] { string.Empty }; } foreach (string path in _paths) { switch (ParameterSetName) { case childrenSet: case literalChildrenSet: try { if (Name) { // Get the names of the child items using the static namespace method. // The child names should be written directly to the pipeline using the // context.WriteObject method. InvokeProvider.ChildItem.GetNames(path, ReturnContainers.ReturnMatchingContainers, Recurse, Depth, currentContext); } else { // Get the children using the static namespace method. // The children should be written directly to the pipeline using // the context.WriteObject method. InvokeProvider.ChildItem.Get(path, Recurse, Depth, currentContext); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } break; default: Dbg.Diagnostics.Assert( false, "Only one of the specified parameter sets should be called."); break; } } }
internal object StartDynamicParameters(CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; return(this.StartDynamicParameters()); }
/// <summary> /// Scan forwards to get the tail content /// </summary> /// <param name="holder"></param> /// <param name="currentContext"></param> /// <returns> /// true if no error occured /// false if there was an error /// </returns> private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext currentContext) { var fsReader = holder.Reader as FileSystemContentReaderWriter; Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); var tailResultQueue = new Queue <object>(); IList results = null; ErrorRecord error = null; do { try { results = fsReader.ReadWithoutWaitingChanges(ReadCount); } catch (Exception e) { ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); // Create and save the error record. The error record // will be written outside the while loop. // This is to make sure the accumulated results get written // out before the error record when the 'scanForwardForTail' is true. error = new ErrorRecord( providerException.ErrorRecord, providerException); break; } if (results != null && results.Count > 0) { foreach (object entry in results) { if (tailResultQueue.Count == Tail) { tailResultQueue.Dequeue(); } tailResultQueue.Enqueue(entry); } } } while (results != null && results.Count > 0); if (tailResultQueue.Count > 0) { // Respect the ReadCount parameter. // Output single object when ReadCount == 1; Output array otherwise int count = 0; if (ReadCount <= 0 || (ReadCount >= tailResultQueue.Count && ReadCount != 1)) { count = tailResultQueue.Count; ArrayList outputList = new ArrayList(); while (tailResultQueue.Count > 0) { outputList.Add(tailResultQueue.Dequeue()); } // Write out the content as an array of objects WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); } else if (ReadCount == 1) { // Write out the content as single object while (tailResultQueue.Count > 0) { WriteContentObject(tailResultQueue.Dequeue(), count++, holder.PathInfo, currentContext); } } else // ReadCount < Queue.Count { while (tailResultQueue.Count >= ReadCount) { ArrayList outputList = new ArrayList(); for (int idx = 0; idx < ReadCount; idx++, count++) { outputList.Add(tailResultQueue.Dequeue()); } // Write out the content as an array of objects WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); } int remainder = tailResultQueue.Count; if (remainder > 0) { ArrayList outputList = new ArrayList(); for (; remainder > 0; remainder--, count++) { outputList.Add(tailResultQueue.Dequeue()); } // Write out the content as an array of objects WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); } } } if (error != null) { WriteError(error); return(false); } return(true); }
internal void Stop(CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; this.Stop(); }
} // GetDynamicParameters #endregion Parameters #region parameter data #endregion parameter data #region Command code /// <summary> /// Sets the content of the item at the specified path /// </summary> protected override void ProcessRecord() { // Default to the CmdletProviderContext that will direct output to // the pipeline. CmdletProviderContext currentCommandContext = CmdletProviderContext; currentCommandContext.PassThru = PassThru; PSObject mshObject = null; switch (ParameterSetName) { case propertyValuePathSet: case propertyValueLiteralPathSet: mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty(Name, Value)); break; case propertyPSObjectPathSet: mshObject = InputObject; break; default: Diagnostics.Assert( false, "One of the parameter sets should have been resolved or an error should have been thrown by the command processor"); break; } // switch foreach (string path in Path) { try { InvokeProvider.Property.Set(path, mshObject, currentCommandContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } } } // ProcessRecord
internal object ClearPropertyDynamicParameters(string path, Collection <string> providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IPropertyCmdletProvider provider = this as IPropertyCmdletProvider; if (provider == null) { return(null); } return(provider.ClearPropertyDynamicParameters(path, providerSpecificPickList)); }
} // NewProperty /// <summary> /// Gives the provider a chance to attach additional parameters to /// the new-itemproperty cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="propertyName"> /// The name of the property that should be created. /// </param> /// /// <param name="propertyTypeName"> /// 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="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object NewPropertyDynamicParameters( string path, string propertyName, string propertyTypeName, object value, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; if (propertyProvider == null) { return null; } return propertyProvider.NewPropertyDynamicParameters(path, propertyName, propertyTypeName, value); } // NewPropertyDynamicParameters
internal void CopyProperty(string sourcePath, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IDynamicPropertyCmdletProvider provider = this as IDynamicPropertyCmdletProvider; if (provider == null) { throw PSTraceSource.NewNotSupportedException("SessionStateStrings", "IDynamicPropertyCmdletProvider_NotSupported", new object[0]); } provider.CopyProperty(sourcePath, sourceProperty, destinationPath, destinationProperty); }
} // RemovePropertyDynamicParameters /// <summary> /// Internal wrapper for the RenameProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. /// </summary> /// /// <param name="path"> /// The path to the item on which the property should be renamed. /// </param> /// /// <param name="propertyName"> /// The name of the property that should be renamed. /// </param> /// /// <param name="newPropertyName"> /// The new name for the property. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <remarks> /// Implement this method when you are providing access to a data store /// that allows dynamic renaming of properties. /// </remarks> /// internal void RenameProperty( string path, string propertyName, string newPropertyName, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IDynamicPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.RenameProperty(path, propertyName, newPropertyName); } // RenameProperty
internal object CopyPropertyDynamicParameters(string path, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { this.Context = cmdletProviderContext; IDynamicPropertyCmdletProvider provider = this as IDynamicPropertyCmdletProvider; if (provider == null) { return(null); } return(provider.CopyPropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty)); }
} // MoveProperty /// <summary> /// Gives the provider a chance to attach additional parameters to /// the move-itemproperty cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="sourceProperty"> /// The name of the property that should be copied. /// </param> /// /// <param name="destinationPath"> /// The path to the item to which the property should be copied. /// </param> /// /// <param name="destinationProperty"> /// The name of the property that should be copied to. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object MovePropertyDynamicParameters( string path, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; if (propertyProvider == null) { return null; } return propertyProvider.MovePropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty); } // MovePropertyDynamicParameters
/// <summary> /// Removes the current scope from the scope tree and /// changes the current scope to the parent scope. /// </summary> /// <param name="scope"> /// The scope to cleanup and remove. /// </param> /// <exception cref="SessionStateUnauthorizedAccessException"> /// The global scope cannot be removed. /// </exception> internal void RemoveScope(SessionStateScope scope) { Diagnostics.Assert( _currentScope != null, "The currentScope should always be set."); if (scope == GlobalScope) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( StringLiterals.Global, SessionStateCategory.Scope, "GlobalScopeCannotRemove", SessionStateStrings.GlobalScopeCannotRemove); throw e; } // Give the provider a chance to cleanup the drive data associated // with drives in this scope foreach (PSDriveInfo drive in scope.Drives) { if (drive == null) { continue; } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); // Call CanRemoveDrive to give the provider a chance to cleanup // but ignore the return value and exceptions try { CanRemoveDrive(drive, context); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception) // Catch-all OK, 3rd party callout. { // Ignore all exceptions from the provider as we are // going to force the removal anyway } } scope.RemoveAllDrives(); // If the scope being removed is the current scope, // then it must be removed from the tree. if (scope == _currentScope && _currentScope.Parent != null) { _currentScope = _currentScope.Parent; } scope.Parent = null; }
} // GetContentWriterDynamicParameters /// <summary> /// Internal wrapper for the ClearContent protected method. This method will /// only be called if the provider implements the IContentCmdletProvider interface. /// </summary> /// /// <param name="path"> /// The path to the item to clear the content from. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// internal void ClearContent( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IContentCmdletProvider contentProvider = this as IContentCmdletProvider; if (contentProvider == null) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IContentCmdletProvider_NotSupported); } // Call interface method contentProvider.ClearContent(path); } // ClearContent
/// <summary> /// The main execution method for the get-childitem command. /// </summary> protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; if (_paths == null || (_paths != null && _paths.Length == 0)) { _paths = new string[] { String.Empty }; } foreach (string path in _paths) { switch (ParameterSetName) { case childrenSet: case literalChildrenSet: try { if (Name) { // Get the names of the child items using the static namespace method. // The child names should be written directly to the pipeline using the // context.WriteObject method. InvokeProvider.ChildItem.GetNames(path, ReturnContainers.ReturnMatchingContainers, Recurse, Depth, currentContext); } else { // Get the children using the static namespace method. // The children should be written directly to the pipeline using // the context.WriteObject method. InvokeProvider.ChildItem.Get(path, Recurse, Depth, currentContext); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } break; #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release case relationshipSet: foreach (string relationship in relationships) { Collection <string> results = null; try { results = InvokeProvider.Relationship.GetTargets( relationship, path, property); } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } foreach (string target in results) { // Create an PSObject with the result. // Attach the relationship name as a note, // and set "System.Management.Automation.RelationshipTarget" // as the TreatAs. PSObject result = PSObject.AsPSObject(target); result.Properties.Add( new PSNoteProperty( "Relationship", relationship)); Collection <string> treatAs = new Collection <string> (); treatAs.Add(targetTreatAsType); result.TypeNames = treatAs; // Now write out the result WriteObject(result); } } break; #endif default: Dbg.Diagnostics.Assert( false, "Only one of the specified parameter sets should be called."); break; } } } // ProcessRecord
} // Context /// <summary> /// Called when the provider is first initialized. It sets the context /// of the call and then calls the derived providers Start method. /// </summary> /// /// <param name="providerInfo"> /// The information about the provider. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// internal ProviderInfo Start(ProviderInfo providerInfo, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; return Start(providerInfo); } // Start
/// <summary> /// Gets the IContentWriters for the current path(s) /// </summary> /// <returns> /// An array of IContentWriters for the current path(s) /// </returns> internal List <ContentHolder> GetContentWriters( string[] writerPaths, CmdletProviderContext currentCommandContext) { // Resolve all the paths into PathInfo objects Collection <PathInfo> pathInfos = ResolvePaths(writerPaths, true, false, currentCommandContext); // Create the results array List <ContentHolder> results = new List <ContentHolder>(); foreach (PathInfo pathInfo in pathInfos) { // For each path, get the content writer Collection <IContentWriter> writers = null; try { writers = InvokeProvider.Content.GetWriter( pathInfo.Path, currentCommandContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } if (writers != null && writers.Count > 0) { if (writers.Count == 1 && writers[0] != null) { ContentHolder holder = new ContentHolder(pathInfo, null, writers[0]); results.Add(holder); } } } return(results); }
} // StartDynamicParameter /// <summary> /// Called when the provider is being removed. It sets the context /// of the call and then calls the derived providers Stop method. /// </summary> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. ///</param> /// internal void Stop(CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; Stop(); } // Stop
/// <summary> /// Appends the content to the specified item. /// </summary> protected override void ProcessRecord() { CmdletProviderContext currentContext = GetCurrentContext(); // Initialize the content if (_content is null) { _content = Array.Empty <object>(); } if (_pipingPaths) { // Make sure to clean up the content writers that are already there if (contentStreams != null && contentStreams.Count > 0) { CloseContent(contentStreams, false); _contentWritersOpen = false; contentStreams = new List <ContentHolder>(); } } if (!_contentWritersOpen) { // Since the paths are being pipelined in, we have // to get new content writers for the new paths string[] paths = GetAcceptedPaths(Path, currentContext); if (paths.Length > 0) { BeforeOpenStreams(paths); contentStreams = GetContentWriters(paths, currentContext); SeekContentPosition(contentStreams); } _contentWritersOpen = true; } // Now write the content to the item try { foreach (ContentHolder holder in contentStreams) { if (holder.Writer != null) { IList result = null; try { result = holder.Writer.Write(_content); } catch (Exception e) // Catch-all OK. 3rd party callout { ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); continue; } if (result != null && result.Count > 0 && PassThru) { WriteContentObject(result, result.Count, holder.PathInfo, currentContext); } } } } finally { // Need to close all the writers if the paths are being pipelined if (_pipingPaths) { CloseContent(contentStreams, false); _contentWritersOpen = false; contentStreams = new List <ContentHolder>(); } } }
} // SetProperty /// <summary> /// Gives the provider a chance to attach additional parameters to /// the set-itemproperty cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="propertyValue"> /// A PSObject which contains a collection of the name, type, value /// of the properties to be set. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object SetPropertyDynamicParameters( string path, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; if (propertyProvider == null) { return null; } return propertyProvider.SetPropertyDynamicParameters(path, propertyValue); } // SetPropertyDynamicParameters
/// <summary> /// Wraps the content into a PSObject and adds context information as notes /// </summary> /// <param name="content"> /// The content being written out. /// </param> /// <param name="readCount"> /// The number of blocks that have been read so far. /// </param> /// <param name="pathInfo"> /// The context the content was retrieved from. /// </param> /// <param name="context"> /// The context the command is being run under. /// </param> internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context) { Dbg.Diagnostics.Assert( content != null, "The caller should verify the content."); Dbg.Diagnostics.Assert( pathInfo != null, "The caller should verify the pathInfo."); Dbg.Diagnostics.Assert( context != null, "The caller should verify the context."); PSObject result = PSObject.AsPSObject(content); Dbg.Diagnostics.Assert( result != null, "A PSObject should always be constructed."); // Use the cached notes if the cache exists and the path is still the same PSNoteProperty note; if (_currentContentItem != null && ((_currentContentItem.PathInfo == pathInfo) || ( String.Compare( pathInfo.Path, _currentContentItem.PathInfo.Path, StringComparison.OrdinalIgnoreCase) == 0) ) ) { result = _currentContentItem.AttachNotes(result); } else { // Generate a new cache item and cache the notes _currentContentItem = new ContentPathsCache(pathInfo); // Construct a provider qualified path as the Path note string psPath = pathInfo.Path; note = new PSNoteProperty("PSPath", psPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath); _currentContentItem.PSPath = psPath; try { // Now get the parent path and child name string parentPath = null; if (pathInfo.Drive != null) { parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context); } else { parentPath = SessionState.Path.ParseParent(pathInfo.Path, String.Empty, context); } note = new PSNoteProperty("PSParentPath", parentPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath); _currentContentItem.ParentPath = parentPath; // Get the child name string childName = SessionState.Path.ParseChildName(pathInfo.Path, context); note = new PSNoteProperty("PSChildName", childName); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); _currentContentItem.ChildName = childName; } catch (NotSupportedException) { // Ignore. The object just won't have ParentPath or ChildName set. } // PSDriveInfo if (pathInfo.Drive != null) { PSDriveInfo drive = pathInfo.Drive; note = new PSNoteProperty("PSDrive", drive); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive); _currentContentItem.Drive = drive; } // ProviderInfo ProviderInfo provider = pathInfo.Provider; note = new PSNoteProperty("PSProvider", provider); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider); _currentContentItem.Provider = provider; } // Add the ReadCount note note = new PSNoteProperty("ReadCount", readCount); result.Properties.Add(note, true); WriteObject(result); } // WriteContentObject
} // ClearProperty /// <summary> /// Gives the provider a chance to attach additional parameters to /// the clear-itemproperty cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="providerSpecificPickList"> /// A list of properties that should be cleared. If this parameter is null /// or empty, all properties should be cleared. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object ClearPropertyDynamicParameters( string path, Collection<string> providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; if (propertyProvider == null) { return null; } return propertyProvider.ClearPropertyDynamicParameters(path, providerSpecificPickList); } // ClearPropertyDynamicParameters
} // ClearItemDynamicParameters /// <summary> /// Internal wrapper for the InvokeDefaultAction protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to perform the default action on. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// internal void InvokeDefaultAction( string path, CmdletProviderContext context) { providerBaseTracer.WriteLine("ItemCmdletProvider.InvokeDefaultAction"); Context = context; // Call virtual method InvokeDefaultAction(path); } // InvokeDefaultAction
} // RemovePropertyValueAt /// <summary> /// Gives the provider a chance to attach additional parameters to /// the remove-propertyvalue -at cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="propertyName"> /// The name of the property that the value should be remove from. /// </param> /// /// <param name="at"> /// The position of the value of the property to be removed. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object RemovePropertyValueAtDynamicParameters( string path, string propertyName, object at, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IMultivaluePropertyCmdletProvider propertyProvider = this as IMultivaluePropertyCmdletProvider; if (propertyProvider == null) { return null; } return propertyProvider.RemovePropertyValueAtDynamicParameters(path, propertyName, at); } // RemovePropertyValueAtDynamicParameters
} // GetContentReaders /// <summary> /// Resolves the specified paths to PathInfo objects /// </summary> /// <param name="pathsToResolve"> /// The paths to be resolved. Each path may contain glob characters. /// </param> /// <param name="allowNonexistingPaths"> /// If true, resolves the path even if it doesn't exist. /// </param> /// <param name="allowEmptyResult"> /// If true, allows a wildcard that returns no results. /// </param> /// <param name="currentCommandContext"> /// The context under which the command is running. /// </param> /// <returns> /// An array of PathInfo objects that are the resolved paths for the /// <paramref name="pathsToResolve"/> parameter. /// </returns> internal Collection <PathInfo> ResolvePaths( string[] pathsToResolve, bool allowNonexistingPaths, bool allowEmptyResult, CmdletProviderContext currentCommandContext) { Collection <PathInfo> results = new Collection <PathInfo>(); foreach (string path in pathsToResolve) { bool pathNotFound = false; bool filtersHidPath = false; ErrorRecord pathNotFoundErrorRecord = null; try { // First resolve each of the paths Collection <PathInfo> pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath( path, currentCommandContext); if (pathInfos.Count == 0) { pathNotFound = true; // If the item simply did not exist, // we would have got an ItemNotFoundException. // If we get here, it's because the filters // excluded the file. if (!currentCommandContext.SuppressWildcardExpansion) { filtersHidPath = true; } } foreach (PathInfo pathInfo in pathInfos) { results.Add(pathInfo); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); } catch (ItemNotFoundException pathNotFoundException) { pathNotFound = true; pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException); } if (pathNotFound) { if (allowNonexistingPaths && (!filtersHidPath) && (currentCommandContext.SuppressWildcardExpansion || (!WildcardPattern.ContainsWildcardCharacters(path)))) { ProviderInfo provider = null; PSDriveInfo drive = null; string unresolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath( path, currentCommandContext, out provider, out drive); PathInfo pathInfo = new PathInfo( drive, provider, unresolvedPath, SessionState); results.Add(pathInfo); } else { if (pathNotFoundErrorRecord == null) { // Detect if the path resolution failed to resolve to a file. String error = StringUtil.Format(NavigationResources.ItemNotFound, Path); Exception e = new Exception(error); pathNotFoundErrorRecord = new ErrorRecord( e, "ItemNotFound", ErrorCategory.ObjectNotFound, Path); } WriteError(pathNotFoundErrorRecord); } } } return(results); } // ResolvePaths
} // AddPropertyValueAt /// <summary> /// Gives the provider a chance to attach additional parameters to /// the add-propertyvalue -at cmdlet. /// </summary> /// /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// /// <param name="at"> /// The position to place the new value of the property. /// </param> /// /// <param name="propertyValue"> /// A PSObject which contains a collection of the name, type, value /// of the properties to be added. /// </param> /// /// <param name="cmdletProviderContext"> /// The context under which this method is being called. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// internal object AddPropertyValueAtDynamicParameters( string path, object at, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; IMultivaluePropertyCmdletProvider propertyProvider = this as IMultivaluePropertyCmdletProvider; if (propertyProvider == null) { return null; } return propertyProvider.AddPropertyValueAtDynamicParameters(path, at, propertyValue); } // AddPropertyValueAtDynamicParameters
} // NormalizeRelativePath internal string ContractRelativePath( string path, string basePath, bool allowNonExistingPaths, CmdletProviderContext context) { Context = context; if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (path.Length == 0) { return(String.Empty); } if (basePath == null) { basePath = String.Empty; } providerBaseTracer.WriteLine("basePath = {0}", basePath); string result = path; bool originalPathHadTrailingSlash = false; string normalizedPath = path; string normalizedBasePath = basePath; // NTRAID#Windows 7-697922-2009/06/29-leeholm // WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND // // This path normalization got moved here from the MakePath override in V2 to prevent // over-normalization of paths. This was a net-improvement for providers that use the default // implementations, but now incorrectly replaces forward slashes with back slashes during the call to // GetParentPath and GetChildName. This breaks providers that are sensitive to slash direction, the only // one we are aware of being the Active Directory provider. This change prevents this over-normalization // from being done on AD paths. // // For more information, see Win7:695292. Do not change this code without closely working with the // Active Directory team. // // WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND if (!String.Equals(context.ProviderInstance.ProviderInfo.FullName, @"Microsoft.ActiveDirectory.Management\ActiveDirectory", StringComparison.OrdinalIgnoreCase)) { normalizedPath = NormalizePath(path); normalizedBasePath = NormalizePath(basePath); } do // false loop { // Convert to the correct path separators and trim trailing separators string originalPath = path; Stack <string> tokenizedPathStack = null; if (path.EndsWith(StringLiterals.DefaultPathSeparator)) { path = path.TrimEnd(StringLiterals.DefaultPathSeparator); originalPathHadTrailingSlash = true; } basePath = basePath.TrimEnd(StringLiterals.DefaultPathSeparator); // See if the base and the path are already the same. We resolve this to // ..\Leaf, since resolving "." to "." doesn't offer much information. if (String.Equals(normalizedPath, normalizedBasePath, StringComparison.OrdinalIgnoreCase) && (!originalPath.EndsWith(StringLiterals.DefaultPathSeparator))) { string childName = GetChildName(path); result = MakePath("..", childName); break; } // If the base path isn't really a base, then we resolve to a parent // path (such as ../../foo) if (!normalizedPath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase) && (basePath.Length > 0)) { result = String.Empty; string commonBase = GetCommonBase(normalizedPath, normalizedBasePath); Stack <string> parentNavigationStack = TokenizePathToStack(normalizedBasePath, commonBase); int parentPopCount = parentNavigationStack.Count; if (String.IsNullOrEmpty(commonBase)) { parentPopCount--; } for (int leafCounter = 0; leafCounter < parentPopCount; leafCounter++) { result = MakePath("..", result); } // This is true if we get passed a base path like: // c:\directory1\directory2 // and an actual path of // c:\directory1 // Which happens when the user is in c:\directory1\directory2 // and wants to resolve something like: // ..\..\dir* // In that case (as above,) we keep the ..\..\directory1 // instead of ".." as would usually be returned if (!String.IsNullOrEmpty(commonBase)) { if (String.Equals(normalizedPath, commonBase, StringComparison.OrdinalIgnoreCase) && (!normalizedPath.EndsWith(StringLiterals.DefaultPathSeparator))) { string childName = GetChildName(path); result = MakePath("..", result); result = MakePath(result, childName); } else { string[] childNavigationItems = TokenizePathToStack(normalizedPath, commonBase).ToArray(); for (int leafCounter = 0; leafCounter < childNavigationItems.Length; leafCounter++) { result = MakePath(result, childNavigationItems[leafCounter]); } } } } // Otherwise, we resolve to a child path (such as foo/bar) else { tokenizedPathStack = TokenizePathToStack(path, basePath); // Now we have to normalize the path // by processing each token on the stack Stack <string> normalizedPathStack; try { normalizedPathStack = NormalizeThePath(tokenizedPathStack, path, basePath, allowNonExistingPaths); } catch (ArgumentException argumentException) { WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.InvalidArgument, null)); result = null; break; } // Now that the path has been normalized, create the relative path result = CreateNormalizedRelativePathFromStack(normalizedPathStack); } } while (false); if (originalPathHadTrailingSlash) { result = result + StringLiterals.DefaultPathSeparator; } return(result); } // ContractRelativePath
/// <summary> /// Gets the IContentReaders for the current path(s) /// </summary> /// <returns> /// An array of IContentReaders for the current path(s) /// </returns> internal List <ContentHolder> GetContentReaders( string[] readerPaths, CmdletProviderContext currentCommandContext) { // Resolve all the paths into PathInfo objects Collection <PathInfo> pathInfos = ResolvePaths(readerPaths, false, true, currentCommandContext); // Create the results array List <ContentHolder> results = new List <ContentHolder>(); foreach (PathInfo pathInfo in pathInfos) { // For each path, get the content writer Collection <IContentReader> readers = null; try { string pathToProcess = WildcardPattern.Escape(pathInfo.Path); if (currentCommandContext.SuppressWildcardExpansion) { pathToProcess = pathInfo.Path; } readers = InvokeProvider.Content.GetReader(pathToProcess, currentCommandContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } if (readers != null && readers.Count > 0) { if (readers.Count == 1 && readers[0] != null) { ContentHolder holder = new ContentHolder(pathInfo, readers[0], null); results.Add(holder); } } } // foreach pathInfo in pathInfos return(results); } // GetContentReaders
} // InvokeDefaultActionDynamicParameters /// <summary> /// Internal wrapper for the Exists protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// /// <param name="path"> /// The path to the item to see if it exists. /// </param> /// /// <param name="context"> /// The context under which this method is being called. /// </param> /// /// <returns> /// True if the item exists, false otherwise. /// </returns> /// internal bool ItemExists(string path, CmdletProviderContext context) { Context = context; // Call virtual method bool itemExists = false; try { // Some providers don't expect non-valid path elements, and instead // throw an exception here. itemExists = ItemExists(path); } catch (Exception e) { // ignore non-severe exceptions CommandProcessorBase.CheckForSevereException(e); } return itemExists; } // Exists