// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 #pragma warning disable 56506 using System.Collections.ObjectModel; using System.IO; using System.Management.Automation.Runspaces; using System.Management.Automation.Internal; using System.Management.Automation.Host; using System.Resources; using System.Diagnostics.CodeAnalysis; // for fxcop using System.Security.AccessControl; namespace System.Management.Automation.Provider { /// /// This interface needs to be implemented by providers that want users to see /// provider-specific help. /// #nullable enable public interface ICmdletProviderSupportsHelp { /// /// Called by the help system to get provider-specific help from the provider. /// /// /// Name of command that the help is requested for. /// /// /// Full path to the current location of the user or the full path to /// the location of the property that the user needs help about. /// /// /// The MAML help XML that should be presented to the user. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Maml", Justification = "Maml is an acronym.")] string GetHelpMaml(string helpItemName, string path); } #nullable restore #region CmdletProvider /// /// The base class for Cmdlet provider. /// /// /// Although it is possible to derive from this base class to implement a Cmdlet Provider, in most /// cases one should derive from , /// , or /// /// public abstract partial class CmdletProvider : IResourceSupplier { #region private data /// /// The context under which the provider is running. This will change between each /// invocation of a method in this class or derived classes. /// private CmdletProviderContext _contextBase = null; /// /// The information that the Monad engine stores on behalf of the provider. /// private ProviderInfo _providerInformation = null; #endregion private data #region internal members #region Trace object /// /// An instance of the PSTraceSource class used for trace output /// using "CmdletProviderClasses" as the category. /// [TraceSource( "CmdletProviderClasses", "The namespace provider base classes tracer")] internal static readonly PSTraceSource providerBaseTracer = PSTraceSource.GetTracer( "CmdletProviderClasses", "The namespace provider base classes tracer"); #endregion Trace object /// /// Sets the provider information that is stored in the Monad engine into the /// provider base class. /// /// /// The provider information that is stored by the Monad engine. /// /// /// If is null. /// internal void SetProviderInformation(ProviderInfo providerInfoToSet) { if (providerInfoToSet == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInfoToSet)); } _providerInformation = providerInfoToSet; } /// /// Checks whether the filter of the provider is set. /// Can be overridden by derived class when additional filters are defined. /// /// /// Whether the filter of the provider is set. /// internal virtual bool IsFilterSet() { bool filterSet = !string.IsNullOrEmpty(Filter); return filterSet; } #region CmdletProvider method wrappers /// /// Gets or sets the context for the running command. /// /// /// On set, if the context contains credentials and the provider /// doesn't support credentials, or if the context contains a filter /// parameter and the provider does not support filters. /// internal CmdletProviderContext Context { get { return _contextBase; } set { if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } // Check that the provider supports the use of credentials if (value.Credential != null && value.Credential != PSCredential.Empty && !CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Credentials, _providerInformation)) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.Credentials_NotSupported); } // Supplying Credentials for the FileSystemProvider is supported only for New-PSDrive Command. if (_providerInformation != null && !string.IsNullOrEmpty(_providerInformation.Name) && _providerInformation.Name.Equals("FileSystem") && value.Credential != null && value.Credential != PSCredential.Empty && !value.ExecutionContext.CurrentCommandProcessor.Command.GetType().Name.Equals("NewPSDriveCommand")) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.FileSystemProviderCredentials_NotSupported); } // Check that the provider supports the use of filters if ((!string.IsNullOrEmpty(value.Filter)) && (!CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Filter, _providerInformation))) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.Filter_NotSupported); } // Check that the provider supports the use of transactions if the command // requested it if ((value.UseTransaction) && (!CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Transactions, _providerInformation))) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.Transactions_NotSupported); } _contextBase = value; _contextBase.ProviderInstance = this; } } /// /// Called when the provider is first initialized. It sets the context /// of the call and then calls the derived providers Start method. /// /// /// The information about the provider. /// /// /// The context under which this method is being called. /// internal ProviderInfo Start(ProviderInfo providerInfo, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; return Start(providerInfo); } /// /// Gets an object that defines the additional parameters for the Start implementation /// for a provider. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object StartDynamicParameters(CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; return StartDynamicParameters(); } /// /// Called when the provider is being removed. It sets the context /// of the call and then calls the derived providers Stop method. /// /// /// The context under which this method is being called. /// internal void Stop(CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; Stop(); } /// protected internal virtual void StopProcessing() { } #endregion CmdletProvider method wrappers #region IPropertyCmdletProvider method wrappers /// /// Internal wrapper for the GetProperty protected method. This method will /// only be called if the provider implements the IPropertyCmdletProvider interface. /// /// /// The path to the item to retrieve properties from. /// /// /// A list of properties that should be retrieved. If this parameter is null /// or empty, all properties should be retrieved. /// /// /// The context under which this method is being called. /// internal void GetProperty( string path, Collection providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.GetProperty(path, providerSpecificPickList); } /// /// Gives the provider a chance to attach additional parameters to /// the get-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// A list of properties that should be retrieved. If this parameter is null /// or empty, all properties should be retrieved. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object GetPropertyDynamicParameters( string path, Collection providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.GetPropertyDynamicParameters(path, providerSpecificPickList); } /// /// Internal wrapper for the SetProperty protected method. This method will /// only be called if the provider implements the IPropertyCmdletProvider interface. /// /// /// The path to the item to set the properties on. /// /// /// A PSObject which contains a collection of the name, type, value /// of the properties to be set. /// /// /// The context under which this method is being called. /// internal void SetProperty( string path, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.SetProperty(path, propertyValue); } /// /// Gives the provider a chance to attach additional parameters to /// the set-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// A PSObject which contains a collection of the name, type, value /// of the properties to be set. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object SetPropertyDynamicParameters( string path, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.SetPropertyDynamicParameters(path, propertyValue); } /// /// Internal wrapper for the ClearProperty protected method. This method will /// only be called if the provider implements the IPropertyCmdletProvider interface. /// /// /// The path to the item from which the property should be cleared. /// /// /// The name of the property that should be cleared. /// /// /// The context under which this method is being called. /// /// /// Implement this method when you are providing access to a data store /// that allows dynamic clearing of properties. /// internal void ClearProperty( string path, Collection propertyName, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.ClearProperty(path, propertyName); } /// /// Gives the provider a chance to attach additional parameters to /// the clear-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// A list of properties that should be cleared. If this parameter is null /// or empty, all properties should be cleared. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object ClearPropertyDynamicParameters( string path, Collection providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.ClearPropertyDynamicParameters(path, providerSpecificPickList); } #endregion IPropertyCmdletProvider #region IDynamicPropertyCmdletProvider /// /// Internal wrapper for the NewProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. /// /// /// The path to the item on which the new property should be created. /// /// /// The name of the property that should be created. /// /// /// The type of the property that should be created. /// /// /// The new value of the property that should be created. /// /// /// The context under which this method is being called. /// /// /// Implement this method when you are providing access to a data store /// that allows dynamic creation of properties. /// internal void NewProperty( string path, string propertyName, string propertyTypeName, object value, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IDynamicPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.NewProperty(path, propertyName, propertyTypeName, value); } /// /// Gives the provider a chance to attach additional parameters to /// the new-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The name of the property that should be created. /// /// /// The type of the property that should be created. /// /// /// The new value of the property that should be created. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object NewPropertyDynamicParameters( string path, string propertyName, string propertyTypeName, object value, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.NewPropertyDynamicParameters(path, propertyName, propertyTypeName, value); } /// /// Internal wrapper for the RemoveProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. /// /// /// The path to the item on which the property should be removed. /// /// /// The name of the property to be removed /// /// /// The context under which this method is being called. /// /// /// Implement this method when you are providing access to a data store /// that allows dynamic removal of properties. /// internal void RemoveProperty( string path, string propertyName, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IDynamicPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.RemoveProperty(path, propertyName); } /// /// Gives the provider a chance to attach additional parameters to /// the remove-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The name of the property that should be removed. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object RemovePropertyDynamicParameters( string path, string propertyName, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.RemovePropertyDynamicParameters(path, propertyName); } /// /// Internal wrapper for the RenameProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. /// /// /// The path to the item on which the property should be renamed. /// /// /// The name of the property that should be renamed. /// /// /// The new name for the property. /// /// /// The context under which this method is being called. /// /// /// Implement this method when you are providing access to a data store /// that allows dynamic renaming of properties. /// internal void RenameProperty( string path, string propertyName, string newPropertyName, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IDynamicPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.RenameProperty(path, propertyName, newPropertyName); } /// /// Gives the provider a chance to attach additional parameters to /// the rename-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The name of the property that should be renamed. /// /// /// The name of the property to rename it to. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object RenamePropertyDynamicParameters( string path, string sourceProperty, string destinationProperty, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.RenamePropertyDynamicParameters(path, sourceProperty, destinationProperty); } /// /// Internal wrapper for the CopyProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. /// /// /// The path to the item from which the property should be copied. /// /// /// The name of the property that should be copied. /// /// /// The path to the item to which the property should be copied. /// /// /// The name of the property that should be copied to. /// /// /// The context under which this method is being called. /// /// /// Implement this method when you are providing access to a data store /// that allows dynamic copying of properties. /// internal void CopyProperty( string sourcePath, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IDynamicPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.CopyProperty(sourcePath, sourceProperty, destinationPath, destinationProperty); } /// /// Gives the provider a chance to attach additional parameters to /// the copy-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The name of the property that should be copied. /// /// /// The path to the item to which the property should be copied. /// /// /// The name of the property that should be copied to. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object CopyPropertyDynamicParameters( string path, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.CopyPropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty); } /// /// Internal wrapper for the MoveProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. /// /// /// The path to the item from which the property should be moved. /// /// /// The name of the property that should be moved. /// /// /// The path to the item to which the property should be moved. /// /// /// The name of the property that should be moved to. /// /// /// The context under which this method is being called. /// /// /// Implement this method when you are providing access to a data store /// that allows dynamic moving of properties. /// internal void MoveProperty( string sourcePath, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IDynamicPropertyCmdletProvider_NotSupported); } // Call interface method propertyProvider.MoveProperty(sourcePath, sourceProperty, destinationPath, destinationProperty); } /// /// Gives the provider a chance to attach additional parameters to /// the move-itemproperty cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The name of the property that should be copied. /// /// /// The path to the item to which the property should be copied. /// /// /// The name of the property that should be copied to. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object MovePropertyDynamicParameters( string path, string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } return propertyProvider.MovePropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty); } #endregion IDynamicPropertyCmdletProvider method wrappers #region IContentCmdletProvider method wrappers /// /// Internal wrapper for the GetContentReader protected method. This method will /// only be called if the provider implements the IContentCmdletProvider interface. /// /// /// The path to the item to retrieve content from. /// /// /// The context under which this method is being called. /// /// /// An instance of the IContentReader for the specified path. /// internal IContentReader GetContentReader( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IContentCmdletProvider contentProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IContentCmdletProvider_NotSupported); } // Call interface method return contentProvider.GetContentReader(path); } /// /// Gives the provider a chance to attach additional parameters to /// the get-content cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object GetContentReaderDynamicParameters( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IContentCmdletProvider contentProvider) { return null; } return contentProvider.GetContentReaderDynamicParameters(path); } /// /// Internal wrapper for the GetContentWriter protected method. This method will /// only be called if the provider implements the IContentCmdletProvider interface. /// /// /// The path to the item to set content on. /// /// /// The context under which this method is being called. /// /// /// An instance of the IContentWriter for the specified path. /// internal IContentWriter GetContentWriter( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IContentCmdletProvider contentProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IContentCmdletProvider_NotSupported); } // Call interface method return contentProvider.GetContentWriter(path); } /// /// Gives the provider a chance to attach additional parameters to /// the add-content and set-content cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object GetContentWriterDynamicParameters( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IContentCmdletProvider contentProvider) { return null; } return contentProvider.GetContentWriterDynamicParameters(path); } /// /// Internal wrapper for the ClearContent protected method. This method will /// only be called if the provider implements the IContentCmdletProvider interface. /// /// /// The path to the item to clear the content from. /// /// /// The context under which this method is being called. /// internal void ClearContent( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IContentCmdletProvider contentProvider) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.IContentCmdletProvider_NotSupported); } // Call interface method contentProvider.ClearContent(path); } /// /// Gives the provider a chance to attach additional parameters to /// the clear-content cmdlet. /// /// /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// /// /// The context under which this method is being called. /// /// /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// internal object ClearContentDynamicParameters( string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; if (this is not IContentCmdletProvider contentProvider) { return null; } return contentProvider.ClearContentDynamicParameters(path); } #endregion IContentCmdletProvider method wrappers #endregion internal members #region protected members /// /// Gives the provider the opportunity to initialize itself. /// /// /// The information about the provider that is being started. /// /// /// The default implementation returns the ProviderInfo instance that /// was passed. /// /// To have session state maintain persisted data on behalf of the provider, /// the provider should derive from /// and add any properties or /// methods for the data it wishes to persist. When Start gets called the /// provider should construct an instance of its derived ProviderInfo using the /// providerInfo that is passed in and return that new instance. /// protected virtual ProviderInfo Start(ProviderInfo providerInfo) { using (PSTransactionManager.GetEngineProtectionScope()) { return providerInfo; } } /// /// Gets an object that defines the additional parameters for the Start implementation /// for a provider. /// /// /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// . /// /// The default implementation returns null. (no additional parameters) /// protected virtual object StartDynamicParameters() { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } /// /// Called by session state when the provider is being removed. /// /// /// A provider should override this method to free up any resources that the provider /// was using. /// /// The default implementation does nothing. /// protected virtual void Stop() { using (PSTransactionManager.GetEngineProtectionScope()) { } } /// /// Indicates whether stop has been requested on this provider. /// public bool Stopping { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Stopping; } } } /// /// Gets the instance of session state for the current runspace. /// public SessionState SessionState { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return new SessionState(Context.ExecutionContext.EngineSessionState); } } } /// /// Gets the instance of the provider interface APIs for the current runspace. /// public ProviderIntrinsics InvokeProvider { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return new ProviderIntrinsics(Context.ExecutionContext.EngineSessionState); } } } /// /// Gets the instance of the command invocation APIs for the current runspace. /// public CommandInvocationIntrinsics InvokeCommand { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return new CommandInvocationIntrinsics(Context.ExecutionContext); } } } /// /// Gets the credentials under which the operation should run. /// public PSCredential Credential { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Credential; } } } /// /// The information about the provider that is stored in the runspace /// on behalf of the provider. /// /// /// If a derived type of ProviderInfo was returned from the Start method, it /// will be set here in all subsequent calls to the provider. /// protected internal ProviderInfo ProviderInfo { get { using (PSTransactionManager.GetEngineProtectionScope()) { return _providerInformation; } } } /// /// The drive information associated with the context of the current operation. /// protected PSDriveInfo PSDriveInfo { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Drive; } } } /// /// The dynamic parameters object populated with the values as specified /// by the user. /// protected object DynamicParameters { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.DynamicParameters; } } } /// /// Gets the force property. /// /// /// Gives the provider guidance on how vigorous it should be about performing /// the operation. If true, the provider should do everything possible to perform /// the operation. If false, the provider should attempt the operation but allow /// even simple errors to terminate the operation. /// For example, if the user tries to copy a file to a path that already exists and /// the destination is read-only, if force is true, the provider should copy over /// the existing read-only file. If force is false, the provider should write an error. /// public SwitchParameter Force { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Force; } } } /// /// Gets the provider specific filter that was supplied by the caller. /// public string Filter { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Filter; } } } /// /// Gets the include wildcard patterns which is used to determine which items /// will be included when taking an action. /// public Collection Include { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Include; } } } /// /// Gets the exclude wildcard patterns which is used to determine which items /// will be excluded when taking an action. /// public Collection Exclude { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Exclude; } } } /// /// Gets the host interaction APIs. /// public PSHost Host { get { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.ExecutionContext.EngineHostInterface; } } } /// /// Gets the default item separator character for this provider. /// public virtual char ItemSeparator => Path.DirectorySeparatorChar; /// /// Gets the alternate item separator character for this provider. /// public virtual char AltItemSeparator => #if UNIX '\\'; #else Path.AltDirectorySeparatorChar; #endif #region IResourceSupplier /// /// Gets the resource string corresponding to baseName and /// resourceId from the current assembly. You should override /// this if you require a different behavior. /// /// /// the base resource name /// /// /// the resource id /// /// /// the resource string corresponding to baseName and resourceId /// /// /// When overriding this method, the resource string for the specified /// resource should be retrieved from a localized resource assembly. /// public virtual string GetResourceString(string baseName, string resourceId) { using (PSTransactionManager.GetEngineProtectionScope()) { if (string.IsNullOrEmpty(baseName)) { throw PSTraceSource.NewArgumentException(nameof(baseName)); } if (string.IsNullOrEmpty(resourceId)) { throw PSTraceSource.NewArgumentException(nameof(resourceId)); } ResourceManager manager = ResourceManagerCache.GetResourceManager( this.GetType().Assembly, baseName); string retValue = null; try { retValue = manager.GetString(resourceId, System.Globalization.CultureInfo.CurrentUICulture); } catch (MissingManifestResourceException) { throw PSTraceSource.NewArgumentException(nameof(baseName), GetErrorText.ResourceBaseNameFailure, baseName); } if (retValue == null) { throw PSTraceSource.NewArgumentException(nameof(resourceId), GetErrorText.ResourceIdFailure, resourceId); } return retValue; } } #endregion IResourceSupplier #region ThrowTerminatingError /// [System.Diagnostics.CodeAnalysis.DoesNotReturn] public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } if (errorRecord.ErrorDetails != null && errorRecord.ErrorDetails.TextLookupError != null) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogProviderHealthEvent( this.Context.ExecutionContext, ProviderInfo.Name, textLookupError, Severity.Warning); } // We can't play the same game as Cmdlet.ThrowTerminatingError // and save the exception in the "pipeline". We need to pass // the actual exception as a thrown exception. So, we wrap // it in ProviderInvocationException. ProviderInvocationException providerInvocationException = new ProviderInvocationException(ProviderInfo, errorRecord); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context.ExecutionContext, ProviderInfo.Name, providerInvocationException, Severity.Warning); throw providerInvocationException; } } #endregion ThrowTerminatingError #region User feedback mechanisms /// public bool ShouldProcess( string target) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.ShouldProcess(target); } } /// public bool ShouldProcess( string target, string action) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.ShouldProcess(target, action); } } /// public bool ShouldProcess( string verboseDescription, string verboseWarning, string caption) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.ShouldProcess( verboseDescription, verboseWarning, caption); } } /// public bool ShouldProcess( string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.ShouldProcess( verboseDescription, verboseWarning, caption, out shouldProcessReason); } } /// public bool ShouldContinue( string query, string caption) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.ShouldContinue(query, caption); } } /// public bool ShouldContinue( string query, string caption, ref bool yesToAll, ref bool noToAll) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); return Context.ShouldContinue( query, caption, ref yesToAll, ref noToAll); } } #region Transaction Support /// /// Returns true if a transaction is available and active. /// public bool TransactionAvailable() { using (PSTransactionManager.GetEngineProtectionScope()) { if (Context == null) return false; else return Context.TransactionAvailable(); } } /// /// Gets an object that surfaces the current PowerShell transaction. /// When this object is disposed, PowerShell resets the active transaction. /// public PSTransactionContext CurrentPSTransaction { get { if (Context == null) return null; else return Context.CurrentPSTransaction; } } #endregion Transaction Support /// public void WriteVerbose(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); Context.WriteVerbose(text); } } /// public void WriteWarning(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); Context.WriteWarning(text); } } /// public void WriteProgress(ProgressRecord progressRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); if (progressRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(progressRecord)); } Context.WriteProgress(progressRecord); } } /// public void WriteDebug(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); Context.WriteDebug(text); } } /// public void WriteInformation(InformationRecord record) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); Context.WriteInformation(record); } } /// public void WriteInformation(object messageData, string[] tags) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); Context.WriteInformation(messageData, tags); } } /// /// Converts the incoming object to a PSObject and then adds extra /// data as notes. Then it writes the shell object to the context. /// /// /// The item being written out. /// /// /// The path of the item being written out. /// /// /// True if the item is a container, false otherwise. /// private void WriteObject( object item, string path, bool isContainer) { PSObject result = WrapOutputInPSObject(item, path); // Now add the IsContainer result.AddOrSetProperty("PSIsContainer", isContainer ? Boxed.True : Boxed.False); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSIsContainer", isContainer); Diagnostics.Assert( Context != null, "The context should always be set"); Context.WriteObject(result); } /// /// Converts the incoming object to a PSObject and then adds extra /// data as notes. Then it writes the shell object to the context. /// /// /// The item being written out. /// /// /// The path of the item being written out. /// private void WriteObject( object item, string path) { PSObject result = WrapOutputInPSObject(item, path); Diagnostics.Assert( Context != null, "The context should always be set"); Context.WriteObject(result); } /// /// Wraps the item in a PSObject and attaches some notes to the /// object that deal with path information. /// /// /// The item to be wrapped. /// /// /// The path to the item. /// /// /// A PSObject that wraps the item and has path information attached /// as notes. /// /// /// if is null. /// private PSObject WrapOutputInPSObject( object item, string path) { if (item == null) { throw PSTraceSource.NewArgumentNullException(nameof(item)); } PSObject result = new PSObject(item); Diagnostics.Assert( ProviderInfo != null, "The ProviderInfo should always be set"); // Move the TypeNames to the wrapping object if the wrapped object // was an PSObject PSObject mshObj = item as PSObject; if (mshObj != null) { result.InternalTypeNames = new ConsolidatedString(mshObj.InternalTypeNames); } // Construct a provider qualified path as the Path note string providerQualifiedPath = LocationGlobber.GetProviderQualifiedPath(path, ProviderInfo); result.AddOrSetProperty("PSPath", providerQualifiedPath); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSPath", providerQualifiedPath); // Now get the parent path and child name NavigationCmdletProvider navProvider = this as NavigationCmdletProvider; if (navProvider != null && path != null) { // Get the parent path string parentPath = null; if (PSDriveInfo != null) { parentPath = navProvider.GetParentPath(path, PSDriveInfo.Root, Context); } else { parentPath = navProvider.GetParentPath(path, string.Empty, Context); } string providerQualifiedParentPath = string.Empty; if (!string.IsNullOrEmpty(parentPath)) { providerQualifiedParentPath = LocationGlobber.GetProviderQualifiedPath(parentPath, ProviderInfo); } result.AddOrSetProperty("PSParentPath", providerQualifiedParentPath); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSParentPath", providerQualifiedParentPath); // Get the child name string childName = navProvider.GetChildName(path, Context); result.AddOrSetProperty("PSChildName", childName); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); #if UNIX // Add a commonstat structure to file system objects if (ProviderInfo.ImplementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider)) { try { // Use LStat because if you get a link, you want the information about the // link, not the file. var commonStat = Platform.Unix.GetLStat(path); result.AddOrSetProperty("UnixStat", commonStat); } catch { // If there is *any* problem in retrieving the stat information // set the property to null. There is no specific exception which // would result in different behavior. result.AddOrSetProperty("UnixStat", value: null); } } #endif } // PSDriveInfo if (PSDriveInfo != null) { result.AddOrSetProperty(this.PSDriveInfo.GetNotePropertyForProviderCmdlets("PSDrive")); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSDrive", this.PSDriveInfo); } // ProviderInfo result.AddOrSetProperty(this.ProviderInfo.GetNotePropertyForProviderCmdlets("PSProvider")); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSProvider", this.ProviderInfo); return result; } /// /// Writes an item to the output as a PSObject with extra data attached /// as notes. /// /// /// The item to be written. /// /// /// The path of the item being written. /// /// /// True if the item is a container, false otherwise. /// /// public void WriteItemObject( object item, string path, bool isContainer) { using (PSTransactionManager.GetEngineProtectionScope()) { WriteObject(item, path, isContainer); } } /// /// Writes a property object to the output as a PSObject with extra data attached /// as notes. /// /// /// The properties to be written. /// /// /// The path of the item being written. /// /// public void WritePropertyObject( object propertyValue, string path) { using (PSTransactionManager.GetEngineProtectionScope()) { WriteObject(propertyValue, path); } } /// /// Writes a Security Descriptor object to the output as a PSObject with extra data attached /// as notes. /// /// /// The Security Descriptor to be written. /// /// /// The path of the item from which the Security Descriptor was retrieved. /// /// public void WriteSecurityDescriptorObject( ObjectSecurity securityDescriptor, string path) { using (PSTransactionManager.GetEngineProtectionScope()) { WriteObject(securityDescriptor, path); } } /// public void WriteError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } if (errorRecord.ErrorDetails != null && errorRecord.ErrorDetails.TextLookupError != null) { MshLog.LogProviderHealthEvent( this.Context.ExecutionContext, ProviderInfo.Name, errorRecord.ErrorDetails.TextLookupError, Severity.Warning); } Context.WriteError(errorRecord); } } #endregion User feedback mechanisms #endregion protected members } #endregion CmdletProvider } #pragma warning restore 56506