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:
How to create a symlink between directories from inside an elevated cmd: Git Bash shell fails to create symbolic links
mklink /D link source_directory
How to run a command in cmd as an administrator from inside bash: Launch Elevated CMD.exe from Powershell
powershell 'start cmd -v runAs -Args /k, [comma-separated-args]'
How to set the working directory after launching the powershell command as an administrator (Otherwise it launches a terminal from inside C:\Windows\System32\): PowerShell: Run command from script's directory
powershell 'start cmd -v runAs -Args /k, cd, $pwd, "&", [comma-separated-args]'
Let's say I want to create a symbolic link in my current working directory to a relative directory. I tried 2 ways:
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:\ .
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.