Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

GetOrphanedAccess.cs 2.8 KiB

8 lat temu
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Alphaleonis.Win32.Filesystem;
  2. using Security2;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Management.Automation;
  7. namespace NTFSSecurity
  8. {
  9. [Cmdlet(VerbsCommon.Get, "NTFSOrphanedAccess")]
  10. [OutputType(typeof(FileSystemAccessRule2))]
  11. public class GetOrphanedAccess : GetAccess
  12. {
  13. int orphanedSidCount = 0;
  14. protected override void ProcessRecord()
  15. {
  16. IEnumerable<FileSystemAccessRule2> acl = null;
  17. FileSystemInfo item = null;
  18. foreach (var path in paths)
  19. {
  20. try
  21. {
  22. item = this.GetFileSystemInfo2(path);
  23. }
  24. catch (Exception ex)
  25. {
  26. this.WriteError(new ErrorRecord(ex, "ReadFileError", ErrorCategory.OpenError, path));
  27. continue;
  28. }
  29. try
  30. {
  31. acl = FileSystemAccessRule2.GetFileSystemAccessRules(item, !ExcludeExplicit, !ExcludeInherited, getInheritedFrom);
  32. }
  33. catch (UnauthorizedAccessException)
  34. {
  35. try
  36. {
  37. var ownerInfo = FileSystemOwner.GetOwner(item);
  38. var previousOwner = ownerInfo.Owner;
  39. FileSystemOwner.SetOwner(item, System.Security.Principal.WindowsIdentity.GetCurrent().User);
  40. acl = FileSystemAccessRule2.GetFileSystemAccessRules(item, !ExcludeExplicit, !ExcludeInherited, getInheritedFrom);
  41. FileSystemOwner.SetOwner(item, previousOwner);
  42. }
  43. catch (Exception ex2)
  44. {
  45. this.WriteError(new ErrorRecord(ex2, "AddAceError", ErrorCategory.WriteError, path));
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. this.WriteWarning(string.Format("Could not read item {0}. The error was: {1}", path, ex.Message));
  51. }
  52. finally
  53. {
  54. if (acl != null)
  55. {
  56. var orphanedAces = acl.Where(ace => string.IsNullOrEmpty(ace.Account.AccountName));
  57. orphanedSidCount += orphanedAces.Count();
  58. WriteVerbose(string.Format("Item {0} knows about {1} orphaned SIDs in its ACL", path, orphanedAces.Count()));
  59. orphanedAces.ForEach(ace => WriteObject(ace));
  60. }
  61. }
  62. }
  63. }
  64. protected override void EndProcessing()
  65. {
  66. WriteVerbose(string.Format("Total orphaned Access Control Enties: {0}", orphanedSidCount));
  67. base.EndProcessing();
  68. }
  69. }
  70. }