PoshCode Archive  Artifact Content

Artifact a0134f5405ebd9f68dec5b5a28f4e734c0bd3a2d19ff2adb9ccd25def45ca8a8:

  • File mklink.ps1 — part of check-in [0670b5cf39] at 2018-06-10 13:09:03 on branch trunk — MKLINK – Make Symbolic File and Directory links. Useful for making symbolic links from powershell. (user: James Gentile size: 2164)

# encoding: ascii
# api: csharp
# title: mklink
# description: MKLINK – Make Symbolic File and Directory links.  Useful for making symbolic links from powershell.
# version: 0.1
# type: class
# author: James Gentile
# license: CC0
# x-poshcode-id: 2353
# x-archived: 2016-11-01T14:05:50
# x-published: 2011-11-09T03:14:00
#
#
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;


namespace mklink
{
    class mklink
    {
        [DllImport("kernel32.dll")]
        static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);

        static void Main(string[] args)
        {
            int dirlink = 0;
            int c = 0;
            string[] paths = new string[0];
            
            Console.WriteLine("MKLINK - Create a symbolic or directory link. MKLINK -help for usage. Created in 2010 by James Gentile.");

            foreach (string a in args)
            {
                if ((System.String.Compare(a, "-help", true) == 0) || (System.String.Compare(a, "-H", true) == 0))
                {
                    Console.WriteLine("MKLINK [/D] <Symbolic Link> <file or directory source>");
                    return;
                }
                if (System.String.Compare(a, @"/d", true) == 0)
                {
                    dirlink = 1;
                    continue;
                }
                Array.Resize(ref paths, paths.Length + 1);
                paths[c] = a;
                c++;
            }

            if (paths.Length != 2)
            {
                Console.WriteLine("Requires a <symbolic link> and <file or directory> source.");
                return;
            }
            try
            {
                if (CreateSymbolicLink(paths[0], paths[1], dirlink))
                    Console.WriteLine("Symblic link created for " + paths[0] + " <<===>> " + paths[1]);
            }
            catch (Exception e) 
            {
                Console.WriteLine("Error creating symbolic link: " + e.Message);
            }            
        }
    }
}