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.

NewHardLink.cs 2.9 KiB

7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using Alphaleonis.Win32.Filesystem;
  2. using System;
  3. using System.Management.Automation;
  4. namespace NTFSSecurity
  5. {
  6. [Cmdlet(VerbsCommon.New, "NTFSHardLink")]
  7. [OutputType(typeof(FileInfo), typeof(DirectoryInfo))]
  8. public class NewHardLink : BaseCmdlet
  9. {
  10. string target;
  11. private bool passThru;
  12. System.Reflection.MethodInfo modeMethodInfo = null;
  13. [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
  14. [ValidateNotNullOrEmpty]
  15. [Alias("FullName")]
  16. public string Path
  17. {
  18. get { return paths[0]; }
  19. set
  20. {
  21. paths.Clear();
  22. paths.Add(value);
  23. }
  24. }
  25. [Parameter(Position = 2, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
  26. [ValidateNotNullOrEmpty]
  27. public string Target
  28. {
  29. get { return target; }
  30. set { target = value; }
  31. }
  32. [Parameter]
  33. public SwitchParameter PassThru
  34. {
  35. get { return passThru; }
  36. set { passThru = value; }
  37. }
  38. protected override void BeginProcessing()
  39. {
  40. base.BeginProcessing();
  41. modeMethodInfo = typeof(FileSystemCodeMembers).GetMethod("Mode");
  42. }
  43. protected override void ProcessRecord()
  44. {
  45. var path = paths[0];
  46. path = GetRelativePath(path);
  47. target = GetRelativePath(target);
  48. var root = System.IO.Path.GetPathRoot(path);
  49. try
  50. {
  51. FileSystemInfo temp = null;
  52. if (TryGetFileSystemInfo2(path, out temp))
  53. throw new ArgumentException(string.Format("The file '{0}' does already exist, cannot create the link", path));
  54. if (!TryGetFileSystemInfo2(target, out temp))
  55. throw new ArgumentException("The target path exist, cannot create the link");
  56. else
  57. if (temp is DirectoryInfo)
  58. throw new ArgumentException("The target is not a file, cannot create the link");
  59. File.CreateHardlink(path, target);
  60. if (passThru)
  61. {
  62. var links = File.EnumerateHardlinks(path);
  63. foreach (var link in links)
  64. {
  65. var target = new PSObject(GetFileSystemInfo2(System.IO.Path.Combine(root, link.Substring(1))));
  66. target.Properties.Add(new PSCodeProperty("Mode", modeMethodInfo));
  67. WriteObject(target);
  68. }
  69. }
  70. }
  71. catch (System.IO.FileNotFoundException ex)
  72. {
  73. WriteError(new ErrorRecord(ex, "CreateHardLinkError", ErrorCategory.WriteError, path));
  74. }
  75. }
  76. protected override void EndProcessing()
  77. {
  78. base.EndProcessing();
  79. }
  80. }
  81. }