Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

NewSymbolicLink.cs 2.5 KiB

7 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Alphaleonis.Win32.Filesystem;
  2. using System;
  3. using System.Management.Automation;
  4. namespace NTFSSecurity
  5. {
  6. [Cmdlet(VerbsCommon.New, "NTFSSymbolicLink")]
  7. [OutputType(typeof(FileInfo), typeof(DirectoryInfo))]
  8. public class NewSymbolicLink : 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. FileSystemInfo targetItem = null;
  49. var root = System.IO.Path.GetPathRoot(path);
  50. try
  51. {
  52. targetItem = GetFileSystemInfo2(target);
  53. FileSystemInfo temp;
  54. if (TryGetFileSystemInfo2(path, out temp))
  55. {
  56. throw new ArgumentException("The path does already exist, cannot create link");
  57. }
  58. File.CreateSymbolicLink(path, target, targetItem is FileInfo ? SymbolicLinkTarget.File : SymbolicLinkTarget.Directory);
  59. if (passThru)
  60. {
  61. WriteObject(new FileInfo(path));
  62. }
  63. }
  64. catch (System.IO.FileNotFoundException ex)
  65. {
  66. WriteError(new ErrorRecord(ex, "CreateSymbolicLinkError", ErrorCategory.ObjectNotFound, path));
  67. }
  68. }
  69. protected override void EndProcessing()
  70. {
  71. base.EndProcessing();
  72. }
  73. }
  74. }