Home > database >  Automate creation of symbolic links on Windows bash
Automate creation of symbolic links on Windows bash

Time:11-10

I'm trying to make a script that will do some directory management. The final script will run on Windows and will preferably be written in python. At one point in the script I need to automate the creation of multiple symbolic links between multiple folders. The script itself runs without administrator permissions from a bash terminal (Git Bash). Windows is not in developer mode.

The perfect solution would be to have a list of tuples (link, source) and create the corresponding symbolic links all at once, while having to press "Yes" for administrator rights only once.

I already did some research:

Let's say I want to create a symbolic link in my current working directory to a relative directory. I tried 2 ways:

  1. When I combine all of the above points and execute the following command from the Git Bash terminal:

    powershell 'start cmd -v runAs -Args /k, cd, $pwd, "&", mklink, /D, \"link_to_utils\", \"common\utils\"'

    A new terminal opens up (after agreeing for admin rights). But it resulted in a new symlink being created in the root of C:\ .

  2. When I execute this:

    powershell 'start cmd -v runAs -Args /k, cd, $pwd

    A new terminal opens up (after agreeing for admin rights). I can now run this command:

    mklink /D "link_to_utils" "common\utils"

    The link is created in the current working directory, as I wanted.

So my questions are:

a) How can I make option 1 work in bash?

b) Why is it actually creating the symlink in C:\?

c) Is there a way to pipe a command into the opened elevated cmd terminal (to make option 2 work)?

Note: I have been trying to find a solution using python and the win32api (pywin32). But that resulted in a bunch of command prompts opening up for each symlink that needs to be created. Also there is barely any documentation regarding pywin32.

CodePudding user response:

Use the following:

powershell 'Start-Process -Verb RunAs cmd /k, " cd `"$PWD`" & mklink /D `"link_to_utils`" `"common\utils`" "'
  • Since it is PowerShell that interprets that verbatim content of the command line being passed, its syntax rules must be followed, meaning that a "..." (double-quoted) string is required for expansion (string interpolation) of the automatic $PWD variable to occur, and that embedded " characters inside that string must be escaped as `" ("" would work too).

  • The pass-through command line for cmd.exe is passed as a single string argument, for conceptual clarity.

  • Related