25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 

99 satır
3.1 KiB

  1. using Alphaleonis.Win32.Filesystem;
  2. using Security2;
  3. using System;
  4. using System.Management.Automation;
  5. using Security2.FileSystem.FileInfo;
  6. namespace NTFSSecurity
  7. {
  8. [Cmdlet(VerbsCommon.Get, "FileHash2")]
  9. [OutputType(typeof(FileSystemAccessRule2))]
  10. public class GetFileHash2 : BaseCmdlet
  11. {
  12. private HashAlgorithms algorithm = HashAlgorithms.SHA256;
  13. [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
  14. [ValidateNotNullOrEmpty]
  15. [Alias("FullName")]
  16. public string[] Path
  17. {
  18. get { return paths.ToArray(); }
  19. set
  20. {
  21. paths.Clear();
  22. paths.AddRange(value);
  23. }
  24. }
  25. [Parameter(Position = 2, ValueFromPipelineByPropertyName = true)]
  26. public HashAlgorithms Algorithm
  27. {
  28. get { return algorithm; }
  29. set { algorithm = value; }
  30. }
  31. protected override void BeginProcessing()
  32. {
  33. base.BeginProcessing();
  34. }
  35. protected override void ProcessRecord()
  36. {
  37. string hash = string.Empty;
  38. FileSystemInfo item = null;
  39. foreach (var path in paths)
  40. {
  41. try
  42. {
  43. item = GetFileSystemInfo2(path) as FileInfo;
  44. if (item == null)
  45. return;
  46. }
  47. catch (Exception ex)
  48. {
  49. WriteError(new ErrorRecord(ex, "ReadFileError", ErrorCategory.OpenError, path));
  50. continue;
  51. }
  52. try
  53. {
  54. hash = ((FileInfo)item).GetHash(algorithm);
  55. }
  56. catch (UnauthorizedAccessException)
  57. {
  58. try
  59. {
  60. var ownerInfo = FileSystemOwner.GetOwner(item);
  61. var previousOwner = ownerInfo.Owner;
  62. FileSystemOwner.SetOwner(item, System.Security.Principal.WindowsIdentity.GetCurrent().User);
  63. hash = ((FileInfo)item).GetHash(algorithm);
  64. FileSystemOwner.SetOwner(item, previousOwner);
  65. }
  66. catch (Exception ex2)
  67. {
  68. WriteError(new ErrorRecord(ex2, "GetHashError", ErrorCategory.WriteError, path));
  69. }
  70. }
  71. catch (Exception ex)
  72. {
  73. WriteError(new ErrorRecord(ex, "GetHashError", ErrorCategory.WriteError, path));
  74. }
  75. var result = new PSObject(item);
  76. result.Properties.Add(new PSNoteProperty("Hash", hash));
  77. result.Properties.Add(new PSNoteProperty("Algorithm", algorithm.ToString()));
  78. result.TypeNames.Insert(0, "Alphaleonis.Win32.Filesystem.FileInfo+Hash");
  79. WriteObject(result);
  80. }
  81. }
  82. protected override void EndProcessing()
  83. {
  84. base.EndProcessing();
  85. }
  86. }
  87. }