You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GetSecurityDescriptor.cs 2.4 KiB

7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Alphaleonis.Win32.Filesystem;
  2. using Security2;
  3. using System;
  4. using System.Management.Automation;
  5. namespace NTFSSecurity
  6. {
  7. [Cmdlet(VerbsCommon.Get, "NTFSSecurityDescriptor")]
  8. [OutputType(typeof(FileSystemSecurity2))]
  9. public class GetSecurityDescriptor : BaseCmdletWithPrivControl
  10. {
  11. [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
  12. [ValidateNotNullOrEmpty]
  13. [Alias("FullName")]
  14. public string[] Path
  15. {
  16. get { return paths.ToArray(); }
  17. set
  18. {
  19. paths.Clear();
  20. paths.AddRange(value);
  21. }
  22. }
  23. protected override void BeginProcessing()
  24. {
  25. base.BeginProcessing();
  26. if (paths.Count == 0)
  27. {
  28. paths.Add(GetVariableValue("PWD").ToString());
  29. }
  30. }
  31. protected override void ProcessRecord()
  32. {
  33. FileSystemInfo item = null;
  34. foreach (var path in paths)
  35. {
  36. try
  37. {
  38. item = GetFileSystemInfo2(path);
  39. }
  40. catch (Exception ex)
  41. {
  42. WriteError(new ErrorRecord(ex, "ReadFileError", ErrorCategory.OpenError, path));
  43. continue;
  44. }
  45. try
  46. {
  47. WriteObject(new FileSystemSecurity2(item));
  48. }
  49. catch (UnauthorizedAccessException)
  50. {
  51. try
  52. {
  53. var ownerInfo = FileSystemOwner.GetOwner(item);
  54. var previousOwner = ownerInfo.Owner;
  55. FileSystemOwner.SetOwner(item, System.Security.Principal.WindowsIdentity.GetCurrent().User);
  56. WriteObject(new FileSystemSecurity2(item));
  57. FileSystemOwner.SetOwner(item, previousOwner);
  58. }
  59. catch (Exception ex2)
  60. {
  61. WriteError(new ErrorRecord(ex2, "ReadSecurityError", ErrorCategory.WriteError, path));
  62. continue;
  63. }
  64. }
  65. catch (Exception ex)
  66. {
  67. WriteError(new ErrorRecord(ex, "ReadSecurityError", ErrorCategory.OpenError, path));
  68. }
  69. }
  70. }
  71. }
  72. }