internal ErrorDetails(ErrorDetails errorDetails) { this._message = ""; this._recommendedAction = ""; this._message = errorDetails._message; this._recommendedAction = errorDetails._recommendedAction; }
internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force) { DirectoryInfo targetObject = null; try { string str = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context); if (string.IsNullOrEmpty(str) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase)) { str = Path.Combine(cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem).ProviderPath, moduleNameOrPath); } if (string.IsNullOrEmpty(str)) { str = Path.Combine(ModuleIntrinsics.GetPersonalModulePath(), moduleNameOrPath); } targetObject = new DirectoryInfo(str); if (targetObject.Exists) { if (!force) { ErrorDetails details = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_ErrorDirectoryExists, new object[] { targetObject.FullName })); ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(details.Message), "ExportProxyCommand_OutputDirectoryExists", ErrorCategory.ResourceExists, targetObject); cmdlet.ThrowTerminatingError(errorRecord); } return targetObject; } targetObject.Create(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); ErrorDetails details2 = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory, new object[] { moduleNameOrPath, exception.Message })); ErrorRecord record2 = new ErrorRecord(new ArgumentException(details2.Message, exception), "ExportProxyCommand_CannotCreateOutputDirectory", ErrorCategory.ResourceExists, moduleNameOrPath); cmdlet.ThrowTerminatingError(record2); } return targetObject; }
} // EnsureDriveIsRooted static private ErrorRecord CreateErrorRecord(string path, CertificateProviderItem itemType) { Exception e = null; string message = null; // // first, find the resource-id so that we can display // correct message // switch (itemType) { case CertificateProviderItem.Certificate: message = CertificateProviderStrings.CertificateNotFound; break; case CertificateProviderItem.Store: message = CertificateProviderStrings.CertificateStoreNotFound; break; case CertificateProviderItem.StoreLocation: message = CertificateProviderStrings.CertificateStoreLocationNotFound; break; default: message = CertificateProviderStrings.InvalidPath; break; } message = String.Format( System.Globalization.CultureInfo.CurrentCulture, message, path); ErrorDetails ed = new ErrorDetails(message); // // create appropriate exception type // switch (itemType) { case CertificateProviderItem.Certificate: e = new CertificateNotFoundException(message); break; case CertificateProviderItem.Store: e = new CertificateStoreNotFoundException(message); break; case CertificateProviderItem.StoreLocation: e = new CertificateStoreLocationNotFoundException(message); break; default: e = new ArgumentException(message); break; } ErrorRecord er = new ErrorRecord(e, "CertProviderItemNotFound", ErrorCategory.ObjectNotFound, null); er.ErrorDetails = ed; return er; }
private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args) { ErrorDetails details = new ErrorDetails(this.GetType().Assembly, "UpdateListStrings", resourceId, args); ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(details.Message), errorId, ErrorCategory.InvalidOperation, targetObject); return errorRecord; }
private static ErrorRecord CreateErrorRecord(string path, CertificateProviderItem itemType) { Exception certificateNotFoundException = null; string certificateNotFound = null; CertificateProviderItem certificateProviderItem = itemType; switch (certificateProviderItem) { case CertificateProviderItem.Certificate: { certificateNotFound = CertificateProviderStrings.CertificateNotFound; break; } case CertificateProviderItem.Store: { certificateNotFound = CertificateProviderStrings.CertificateStoreNotFound; break; } case CertificateProviderItem.StoreLocation: { certificateNotFound = CertificateProviderStrings.CertificateStoreLocationNotFound; break; } default: { certificateNotFound = CertificateProviderStrings.InvalidPath; break; } } object[] objArray = new object[1]; objArray[0] = path; certificateNotFound = string.Format(CultureInfo.CurrentCulture, certificateNotFound, objArray); ErrorDetails errorDetail = new ErrorDetails(certificateNotFound); CertificateProviderItem certificateProviderItem1 = itemType; switch (certificateProviderItem1) { case CertificateProviderItem.Certificate: { certificateNotFoundException = new CertificateNotFoundException(certificateNotFound); break; } case CertificateProviderItem.Store: { certificateNotFoundException = new CertificateStoreNotFoundException(certificateNotFound); break; } case CertificateProviderItem.StoreLocation: { certificateNotFoundException = new CertificateStoreLocationNotFoundException(certificateNotFound); break; } default: { certificateNotFoundException = new ArgumentException(certificateNotFound); break; } } ErrorRecord errorRecord = new ErrorRecord(certificateNotFoundException, "CertProviderItemNotFound", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = errorDetail; return errorRecord; }
private ErrorRecord NewError() { ErrorDetails details = new ErrorDetails(base.GetType().Assembly, "WebCmdletStrings", "JsonStringInBadFormat", new object[0]); return new ErrorRecord(new InvalidOperationException(details.Message), "JsonStringInBadFormat", ErrorCategory.InvalidOperation, this.InputObject); }
// deep-copy constructor internal ErrorDetails(ErrorDetails errorDetails) { _message = errorDetails._message; _recommendedAction = errorDetails._recommendedAction; }
private void PopulateProperties(Exception exception, object targetObject, string fullyQualifiedErrorId, ErrorCategory errorCategory, string errorCategory_Activity, string errorCategory_Reason, string errorCategory_TargetName, string errorCategory_TargetType, string errorCategory_Message, string errorDetails_Message, string errorDetails_RecommendedAction, string errorDetails_ScriptStackTrace) { if (exception == null) { throw PSTraceSource.NewArgumentNullException("exception"); } if (fullyQualifiedErrorId == null) { throw PSTraceSource.NewArgumentNullException("fullyQualifiedErrorId"); } //Mark this error record as serialized _isSerialized = true; _error = exception; _target = targetObject; _serializedFullyQualifiedErrorId = fullyQualifiedErrorId; _category = errorCategory; _activityOverride = errorCategory_Activity; _reasonOverride = errorCategory_Reason; _targetNameOverride = errorCategory_TargetName; _targetTypeOverride = errorCategory_TargetType; _serializedErrorCategoryMessageOverride = errorCategory_Message; if (errorDetails_Message != null) { _errorDetails = new ErrorDetails(errorDetails_Message); if (errorDetails_RecommendedAction != null) { _errorDetails.RecommendedAction = errorDetails_RecommendedAction; } } _scriptStackTrace = errorDetails_ScriptStackTrace; }
/// <summary> /// Copy constructor, for use when a new wrapper exception wraps an /// exception which already has an ErrorRecord /// ErrorCategoryInfo and ErrorDetails are deep-copied, other fields are not. /// </summary> /// <param name="errorRecord">wrapped ErrorRecord</param> /// <param name="replaceParentContainsErrorRecordException"> /// If the wrapped exception contains a ParentContainsErrorRecordException, the new /// ErrorRecord should have this exception as its Exception instead. /// </param> public ErrorRecord(ErrorRecord errorRecord, Exception replaceParentContainsErrorRecordException) { if (errorRecord == null) { throw new PSArgumentNullException("errorRecord"); } if (null != replaceParentContainsErrorRecordException && (errorRecord.Exception is ParentContainsErrorRecordException)) { _error = replaceParentContainsErrorRecordException; } else { _error = errorRecord.Exception; } _target = errorRecord.TargetObject; _errorId = errorRecord._errorId; _category = errorRecord._category; _activityOverride = errorRecord._activityOverride; _reasonOverride = errorRecord._reasonOverride; _targetNameOverride = errorRecord._targetNameOverride; _targetTypeOverride = errorRecord._targetTypeOverride; if (null != errorRecord.ErrorDetails) _errorDetails = new ErrorDetails(errorRecord.ErrorDetails); SetInvocationInfo(errorRecord._invocationInfo); _scriptStackTrace = errorRecord._scriptStackTrace; _serializedFullyQualifiedErrorId = errorRecord._serializedFullyQualifiedErrorId; }
private void RemoveFileSystemItem(FileSystemInfo fileSystemInfo, bool force) { if ((base.Force == 0) && ((fileSystemInfo.Attributes & (System.IO.FileAttributes.System | System.IO.FileAttributes.Hidden | System.IO.FileAttributes.ReadOnly)) != 0)) { Exception exception = new IOException(StringUtil.Format(FileSystemProviderStrings.PermissionError, new object[0])); ErrorDetails details = new ErrorDetails(this, "FileSystemProviderStrings", "CannotRemoveItem", new object[] { fileSystemInfo.FullName, exception.Message }); ErrorRecord errorRecord = new ErrorRecord(exception, "RemoveFileSystemItemUnAuthorizedAccess", ErrorCategory.PermissionDenied, fileSystemInfo) { ErrorDetails = details }; base.WriteError(errorRecord); } else { System.IO.FileAttributes attributes = fileSystemInfo.Attributes; bool flag = false; try { if (force) { fileSystemInfo.Attributes &= ~(System.IO.FileAttributes.System | System.IO.FileAttributes.Hidden | System.IO.FileAttributes.ReadOnly); flag = true; } fileSystemInfo.Delete(); if (force) { flag = false; } } catch (Exception exception2) { CommandProcessorBase.CheckForSevereException(exception2); ErrorDetails details2 = new ErrorDetails(this, "FileSystemProviderStrings", "CannotRemoveItem", new object[] { fileSystemInfo.FullName, exception2.Message }); if ((exception2 is SecurityException) || (exception2 is UnauthorizedAccessException)) { ErrorRecord record2 = new ErrorRecord(exception2, "RemoveFileSystemItemUnAuthorizedAccess", ErrorCategory.PermissionDenied, fileSystemInfo) { ErrorDetails = details2 }; base.WriteError(record2); } else if (exception2 is ArgumentException) { ErrorRecord record3 = new ErrorRecord(exception2, "RemoveFileSystemItemArgumentError", ErrorCategory.InvalidArgument, fileSystemInfo) { ErrorDetails = details2 }; base.WriteError(record3); } else { if ((!(exception2 is IOException) && !(exception2 is FileNotFoundException)) && !(exception2 is DirectoryNotFoundException)) { throw; } ErrorRecord record4 = new ErrorRecord(exception2, "RemoveFileSystemItemIOError", ErrorCategory.WriteError, fileSystemInfo) { ErrorDetails = details2 }; base.WriteError(record4); } } finally { if (flag) { try { if (fileSystemInfo.Exists) { fileSystemInfo.Attributes = attributes; } } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); if ((!(exception3 is DirectoryNotFoundException) && !(exception3 is SecurityException)) && ((!(exception3 is ArgumentException) && !(exception3 is FileNotFoundException)) && !(exception3 is IOException))) { throw; } ErrorDetails details3 = new ErrorDetails(this, "FileSystemProviderStrings", "CannotRestoreAttributes", new object[] { fileSystemInfo.FullName, exception3.Message }); ErrorRecord record5 = new ErrorRecord(exception3, "RemoveFileSystemItemCannotRestoreAttributes", ErrorCategory.PermissionDenied, fileSystemInfo) { ErrorDetails = details3 }; base.WriteError(record5); } } } } }
} // RemoveFileInfoItem /// <summary> /// Removes the file system object from the file system. /// </summary> /// /// <param name="fileSystemInfo"> /// The FileSystemInfo object representing the file or directory to be removed. /// </param> /// /// <param name="force"> /// If true, the readonly and hidden attributes will be masked off in the case of /// an error, and the removal will be attempted again. If false, exceptions are /// written to the error pipeline. /// </param> /// private void RemoveFileSystemItem(FileSystemInfo fileSystemInfo, bool force) { Dbg.Diagnostics.Assert( fileSystemInfo != null, "Caller should always check fileSystemInfo"); //First check if we can delete this file when force is not specified. if (!Force && (fileSystemInfo.Attributes & (FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReadOnly)) != 0) { String error = StringUtil.Format(FileSystemProviderStrings.PermissionError); Exception e = new IOException(error); ErrorDetails errorDetails = new ErrorDetails(this, "FileSystemProviderStrings", "CannotRemoveItem", fileSystemInfo.FullName, e.Message); ErrorRecord errorRecord = new ErrorRecord(e, "RemoveFileSystemItemUnAuthorizedAccess", ErrorCategory.PermissionDenied, fileSystemInfo); errorRecord.ErrorDetails = errorDetails; WriteError(errorRecord); return; } // Store the old attributes in case we fail to delete FileAttributes oldAttributes = fileSystemInfo.Attributes; bool attributeRecoveryRequired = false; try { // Try to delete the item. Strip any problematic attributes // if they've specified force. if (force) { fileSystemInfo.Attributes = fileSystemInfo.Attributes & ~(FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System); attributeRecoveryRequired = true; } fileSystemInfo.Delete(); if (force) { attributeRecoveryRequired = false; } } catch (Exception fsException) { CommandProcessorBase.CheckForSevereException(fsException); ErrorDetails errorDetails = new ErrorDetails(this, "FileSystemProviderStrings", "CannotRemoveItem", fileSystemInfo.FullName, fsException.Message); if ((fsException is System.Security.SecurityException) || (fsException is UnauthorizedAccessException)) { ErrorRecord errorRecord = new ErrorRecord(fsException, "RemoveFileSystemItemUnAuthorizedAccess", ErrorCategory.PermissionDenied, fileSystemInfo); errorRecord.ErrorDetails = errorDetails; WriteError(errorRecord); } else if (fsException is ArgumentException) { ErrorRecord errorRecord = new ErrorRecord(fsException, "RemoveFileSystemItemArgumentError", ErrorCategory.InvalidArgument, fileSystemInfo); errorRecord.ErrorDetails = errorDetails; WriteError(errorRecord); } else if ((fsException is IOException) || (fsException is FileNotFoundException) || (fsException is DirectoryNotFoundException)) { ErrorRecord errorRecord = new ErrorRecord(fsException, "RemoveFileSystemItemIOError", ErrorCategory.WriteError, fileSystemInfo); errorRecord.ErrorDetails = errorDetails; WriteError(errorRecord); } else { throw; } } finally { if (attributeRecoveryRequired) { try { if (fileSystemInfo.Exists) { fileSystemInfo.Attributes = oldAttributes; } } catch (Exception attributeException) { CommandProcessorBase.CheckForSevereException(attributeException); if ((attributeException is System.IO.DirectoryNotFoundException) || (attributeException is System.Security.SecurityException) || (attributeException is System.ArgumentException) || (attributeException is System.IO.FileNotFoundException) || (attributeException is System.IO.IOException)) { ErrorDetails attributeDetails = new ErrorDetails( this, "FileSystemProviderStrings", "CannotRestoreAttributes", fileSystemInfo.FullName, attributeException.Message); ErrorRecord errorRecord = new ErrorRecord(attributeException, "RemoveFileSystemItemCannotRestoreAttributes", ErrorCategory.PermissionDenied, fileSystemInfo); errorRecord.ErrorDetails = attributeDetails; WriteError(errorRecord); } else throw; } } } } // RemoveFileSystemItem
/// <summary> /// Removes a directory from the file system. /// </summary> /// /// <param name="directory"> /// The DirectoryInfo object representing the directory to be removed. /// </param> /// /// <param name="recurse"> /// If true, ShouldProcess will be called for each item in the subtree. /// If false, ShouldProcess will only be called for the directory item. /// </param> /// /// <param name="force"> /// If true, attempts to modify the file attributes in case of a failure so that /// the file can be removed. /// </param> /// /// <param name="rootOfRemoval"> /// True if the DirectoryInfo being passed in is the root of the tree being removed. /// ShouldProcess will be called if this is true or if recurse is true. /// </param> /// private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool force, bool rootOfRemoval) { Dbg.Diagnostics.Assert(directory != null, "Caller should always check directory"); bool continueRemoval = true; // We only want to confirm the removal if this is the root of the // tree being removed or the recurse flag is specified. if (rootOfRemoval || recurse) { // Confirm the user wants to remove the directory string action = FileSystemProviderStrings.RemoveItemActionDirectory; continueRemoval = ShouldProcess(directory.FullName, action); } //if this is a reparse point and force is not specified then warn user but dont remove the directory. if (Platform.IsWindows && ((directory.Attributes & FileAttributes.ReparsePoint) != 0) && !Force) { String error = StringUtil.Format(FileSystemProviderStrings.DirectoryReparsePoint, directory.FullName); Exception e = new IOException(error); WriteError(new ErrorRecord(e, "DirectoryNotEmpty", ErrorCategory.WriteError, directory)); return; } if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) { bool success = InternalSymbolicLinkLinkCodeMethods.DeleteJunction(directory.FullName); if (!success) { string error = StringUtil.Format(FileSystemProviderStrings.CannotRemoveItem, directory.FullName); Exception e = new IOException(error); WriteError(new ErrorRecord(e, "DeleteJunctionFailed", ErrorCategory.WriteError, directory)); return; } bool isDirectory; Exception accessException; if (!Utils.NativeItemExists(directory.FullName, out isDirectory, out accessException)) { return; } if (accessException != null) { ErrorRecord errorRecord = new ErrorRecord(accessException, "RemoveFileSystemItemUnAuthorizedAccess", ErrorCategory.PermissionDenied, directory); ErrorDetails errorDetails = new ErrorDetails(this, "FileSystemProviderStrings", "CannotRemoveItem", directory.FullName, accessException.Message); errorRecord.ErrorDetails = errorDetails; WriteError(errorRecord); return; } } if (continueRemoval) { // Loop through each of the contained directories and recurse into them for // removal. foreach (DirectoryInfo childDir in directory.EnumerateDirectories()) { // Making sure to obey the StopProcessing. if (Stopping) { return; } if (childDir != null) { RemoveDirectoryInfoItem(childDir, recurse, force, false); } } // Loop through each of the contained files and remove them. IEnumerable<FileInfo> files = null; if (!String.IsNullOrEmpty(Filter)) { files = directory.EnumerateFiles(Filter); } else { files = directory.EnumerateFiles(); } foreach (FileInfo file in files) { // Making sure to obey the StopProcessing. if (Stopping) { return; } if (file != null) { if (recurse) { // When recurse is specified we need to confirm each // item before removal. RemoveFileInfoItem(file, force); } else { // When recurse is not specified just delete all the // subitems without confirming with the user. RemoveFileSystemItem(file, force); } } } // Check to see if the item has children bool hasChildren = DirectoryInfoHasChildItems(directory); if (hasChildren && !force) { String error = StringUtil.Format(FileSystemProviderStrings.DirectoryNotEmpty, directory.FullName); Exception e = new IOException(error); WriteError(new ErrorRecord(e, "DirectoryNotEmpty", ErrorCategory.WriteError, directory)); } else // !hasChildren || force { // Finally, remove the directory RemoveFileSystemItem(directory, force); } } // ShouldProcess } // RemoveDirectoryInfoItem
internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force) { Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null"); Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)"); DirectoryInfo directoryInfo = null; try { string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context); if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase)) { PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem); rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath); } if (string.IsNullOrEmpty(rootedPath)) { string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath(); rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath); } directoryInfo = new DirectoryInfo(rootedPath); if (directoryInfo.Exists) { if (!force) { string errorMessage = string.Format( CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant PathUtilsStrings.ExportPSSession_ErrorDirectoryExists, directoryInfo.FullName); ErrorDetails details = new ErrorDetails(errorMessage); ErrorRecord errorRecord = new ErrorRecord( new ArgumentException(details.Message), "ExportProxyCommand_OutputDirectoryExists", ErrorCategory.ResourceExists, directoryInfo); cmdlet.ThrowTerminatingError(errorRecord); } } else { directoryInfo.Create(); } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); string errorMessage = string.Format( CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory, moduleNameOrPath, e.Message); ErrorDetails details = new ErrorDetails(errorMessage); ErrorRecord errorRecord = new ErrorRecord( new ArgumentException(details.Message, e), "ExportProxyCommand_CannotCreateOutputDirectory", ErrorCategory.ResourceExists, moduleNameOrPath); cmdlet.ThrowTerminatingError(errorRecord); } return directoryInfo; }
private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args) { ErrorDetails details = new ErrorDetails(base.GetType().Assembly, "AddMember", resourceId, args); return new ErrorRecord(new InvalidOperationException(details.Message), errorId, ErrorCategory.InvalidOperation, targetObject); }