Problems Executing Powershell from .cmd file - windows

I am attempting to run a build task from a .cmd file where Powershell extracts a zip file, which helps bypass a problem with Visual Studio's limit on the number of directory characters. However, I am having problems getting the Powershell command to execute correctly. I've tried a number of variations with the quotations, and I either get a termination error, or the Powershell command outputs as a string with the zip file not extracted. Below is an example of my current .cmd file:
//%1% is a passed in command line argument for the absolute path, e.g. C:\path\to\dir
set Source=%1%directory.zip
set Destination=%1%directory
powershell -Command $pscmd = '{Add-Type -assembly "system.io.compression.filesystem";[io.compression.zipfile]::ExtractToDirectory("%Source%", "%Destination%");}'; Write-Host $pscmd;
I'm very open to a number of variations that can get this to work, provided that this task runs on the command line, uses Powershell, and can be executed from a .cmd file, which is triggered by our app's build process. I'll be happy to provide additional information if needed. Thanks!

This was a strange one. Your code above has some sort of hidden character in it. I took the code and opened it in notepad, saved as ANSI, and when you type it to command line or open it again in a new instance of notepad you can see the error.
Neither add-type nor ExtractToDirectory give output, so I removed your pscmd var.
I would open your existing script, save as ansi as a new file name, delete the original, rename the new one back to the original name.
Here is what I came up with to troubleshoot your script, and it works on my machine.
I named my script L:\util\unzip.cmd
setlocal
//%1% is a passed in command line argument for the absolute path, e.g. C:\path\to\dir
set _Source='%1\directory.zip'
set _Destination='%1\directory'
echo _Source=%_Source%
echo _Destination=%_Destination%
set _c1=Add-Type -assembly system.io.compression.filesystem;
set _c2=[io.compression.zipfile]::ExtractToDirectory(%_Source%, %_Destination%)
echo _c1=%_c1%
echo _c2=%_c2%
set _Command=^& {%_c1% %_c2%};
: to echo, use double quotes or cmd thinks text after & is another command
echo _Command="%_Command%"
pause
powershell -Command "%_Command%"
endlocal
I ran it like this, and it worked: unzip.cmd L:\util
I'll bet this this info, you are good to go.

Related

Best method to automate across platforms

On a daily basis I edit G code to be run on a CO2 laser and I must remove the same string from every file before running it. Currently I open each file in notepad and do ctrl + h and replace it that way. I am looking for a more efficient way to do it.
I am given a packet with a run number (ie 123456), and that run number corresponds to a directory on the network. In that directory are a number of .txt or .nc files that require the string to be removed.
Each run directory is contained in a file structure that looks like this
"\\server\x\companyname\123456"
In \companyname\ there could be hundreds of run directories, all 6 digits - these are the run numbers and are different for each case. I would like to be able to create a program that prompts me for the the run number, and then finds that directory in \x, or rather the complete path as \companyname changes based on the run number, and then replace the string in each file within the \123456 directory. So if the string is Y11 and I was given the run number 000001, I would be prompted for the run number, it would search for the directory and set the path to \\server\x\walmart\000001\ and search each file in this directory for the string Y11 and delete it.
I tried using powershell and was able to find the run folder using Prompt and get-childitem using -recurse and setting a prompted variable to use for -include, however the system doesn't allow scripts!
I can't run scripts because it's a work computer. It says the execution of scripts are disabled on this system. Basically get-executionpolicy is set to restricted and I don't have a cert for this.
This is the code i have so far
$Run = Read-Host prompt "What is the run number?"
$Files = Get-ChildItem -Path "\\\server\x\" -Filter "$Run" -recurse
foreach ($file in $files)
(Get-object $file.PSPath) |
Foreach-Object {$_ -replace "G33", ""} |
Set-Content $file.PSPath
The last portion starting with foreach is something I copied and pasted off a previous example. I have very little experience with powershell. So the run number is located in a directory two levels below x\, for and when the user is prompted for the run number I want it to search all of x, locate the path including the directory that contains the run number (walmart in the example above), and then get all the files in the run number folder. Those files would have a path like
\server\x\walmart\000001\118000001_01.NC
There can be many files in this run folder, and they all need to have the string G33 removed from them.
I am new to this, can someone please explain step by step using powershell, visual basic or any method you think would be the easiest? Even java! I am hoping to be able to use this across PCs with different operating systems. Mostly windows. Thanks!
One possible solution is having an administrator for that server run PowerShell's Set-ExecutionPolicy RemoteSigned commandlet, so that local PowerShell scripts can be executed. Note that on Windows 64-bit, this might need to be done from both a 64-bit PowerShell prompt and from a 32-bit PowerShell prompt, to ensure local PowerShell scripts could be executed from either PowerShell.
Another approach is to use sed (short for Stream Editor), a classic Unix utility that is available on Linux, macOS and Windows. For the latter, search Google for UnixUtils on SourceForge, which includes sed and several other classic Unix utilities built for Windows. Sed can do global search-and-replace within text files. It is non-interactive and meant to be executed from a script (or Batch File).
A VBScript can also read each text file and do search-and-replace. You can open the text file and using a loop read each line. If a line contains the search string, replace that text (optionally with nothing) and then write it; otherwise write it unmodified. You write to a temp file in the same path as the file you're reading, and when done you delete the original and rename the new temp file to the original file name. You have to do error checking all along the way.
As for locating the sub-folders by Run Number, you can probably do that with a batch file (or bash script on Linux and macOS). Something like this:
#echo off
:get-directory-list
dir \\server\x /S /B /AD /OGNE > "C:\Users\Me\Desktop\ListOfDirectories.txt"
:prompt-runnumber
SET RUNNUMBER=
SET /P RUNNUMBER= Enter the 6-digit run number:
if not defined RUNNUMBER echo invalid input & goto prompt-runnumber
if /i "%RUNNUMBER%" EQU "q" goto :EOF
:get-dir-for-run-number
type "C:\Users\Me\Desktop\ListOfDirectories.txt" | find "%RUNNUMBER%" > nul
if ERRORLEVEL 1 echo Run Number not found & goto prompt-runnumber
type "C:\Users\Me\Desktop\ListOfDirectories.txt" | find "%RUNNUMBER%" > %TEMP%\%~n0.tmp"
set /P RUNFOLDER= < "%TEMP%\%~n0.tmp"
echo Run Folder full path is %RUNFOLDER%
:process-files-in-folder
for %%i in (%RUNFOLDER%\*.*) do (
echo Processing folder %RUNFOLDER%, file %%i
rem ... run sed, VBscript, etc. to edit file
)
You might have to edit the above batch file to use a mapped drive letter. For bash, you'd have to first mount the network share and refer to the mount point "directory".
bash offers corresponding commands to list directories, sort them, search for text strings (using grep rather than find), prompting for input, reading input from text files, etc. Both Windows Batch and bash support sub-routines (batch files can call themselves and pass a label as a parameter) if needed.

How to run VBScript from command line without Cscript/Wscript

I am a beginner in VBScript. I googled it & got to know that we can run VBScript from command line by executing below command:
For Example my vbscript name is Converter.vbs & it's present in folder D:\VBS.
I can run it through following methods:
CScript "D:\VBS\Converter.vbs"
OR
WScript "D:\VBS\Converter.vbs"
Now I would like to execute above VBScript without Cscript or Wscript command by simply typing the name of VBscript name i.e. Converter.
I DON'T WANT TO SPECIFY THE FULL PATH OF VBSCRIPT EVERYTIME.
Can anyone please guide me on how to do that ?
I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)
First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:
C:\Windows\System32>assoc .vbs
.vbs=VBSFile
Using that, you then type "ftype VBSFile", which should result in a response of:
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
-OR-
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*
If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)
If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:
C:\Windows\System32>assoc .vbs=VBSFile
-and/or-
C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)
Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:
C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY
Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.
Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P
Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).
Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.
Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)
One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!
On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:
#ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!
ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..
REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE
ECHO Okay, if you're really determined to do this, type this command:
ECHO. %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!
You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!
Here's some links to some good resources on how to use all this power:
http://ss64.com/
http://www.computerhope.com/batch.htm
http://commandwindows.com/batch.htm
http://www.robvanderwoude.com/batchfiles.php
Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.
When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by
assoc | grep -i vbs
.vbs=VBSFile
ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*
to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.
As
cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]
Options:
//B Batch mode: Suppresses script errors and prompts from displaying
//D Enable Active Debugging
//E:engine Use engine for executing script
//H:CScript Changes the default script host to CScript.exe
//H:WScript Changes the default script host to WScript.exe (default)
//I Interactive mode (default, opposite of //B)
//Job:xxxx Execute a WSF job
//Logo Display logo (default)
//Nologo Prevent logo display: No banner will be shown at execution time
//S Save current command line options for this user
//T:nn Time out in seconds: Maximum time a script is permitted to run
//X Execute script in debugger
//U Use Unicode for redirected I/O from the console
shows, you can use //E and //S to permanently switch your default host to cscript.exe.
If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable
set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1
contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.
Update wrt comment:
If you 'don't want to specify the full path of my vbscript everytime' you may:
put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.
put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS
In both cases I would type out the extension to avoid (nasty) surprises.
I am wondering why you cannot put this in a batch file. Example:
cd D:\VBS\
WSCript Converter.vbs
Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.
Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.
Check the answer -> Here
And here is an example:
Converter.bat
::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &#echo off
rem^ &call :'sub
rem^ &exit /b
:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b
'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester
You may follow the following steps:
Open your CMD(Command Prompt)
Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
Type 'CD VBS' and hit Enter. Example: D:>CD VBS
Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

powershell command not running in .bat file?

I am trying to make a simple script to set my gcc variables. as a .bat file.
the variable is set like this
$env:Path += ";C:\Users\Brett\Compilers\MinGW\bin"
this runs just fine when I type/paste it into power shell.
but when I paste into a script myscript.bat, and run it through powershell I get this error:
C:\Users\Brett\Compilers>"$env:Path += ";C:\Users\Brett\Compilers\MinGW\bin""
The filename, directory name, or volume label syntax is incorrect.
PS C:\Users\Scruffy\Compilers>
PowerShell is a seperate execution enviroment from with Windows Command Line (cmd.exe)
If you want to run powershell commands from a batch file you need to save the powershell script (.ps1) and pass it into powershell.exe as a command line argument.
Example:
powershell.exe -noexit c:\scripts\test.ps1
More Information is available here on Microsoft TechNet
In general, leave batch stuff to .BAT files and put PowerShell stuff into .ps1 files.
I can duplicate your results here - but those are to be expected. Cmd.exe sees a string then a path and then gets quite confused as the syntax is not one that the command prompt can handle. So it gives that error message.
If you want to add stuff to your path, then why not put the statement inside a .ps1 script file?
As mentioned by others, you need to save the code in a .ps1 file and not .bat.
This line (from Setting Windows PowerShell path variable) will do the trick:
$env:Path = $env:Path + ";C:\Users\Brett\Compilers\MinGW\bin"
Or even shorter:
$env:Path += ";C:\Users\Brett\Compilers\MinGW\bin"

help with windows batch scripting basics - execution and calling a separate executable within the script

Newbie to windows scripting. I need help running the .bat file on the command line so I can test it.
I used Text Document as my editor to create the file (opens up also as Notepad).
I performed file "save as" (ALL FILES). If I open up cmd, I can see the file has a .txt extension (myfile.bat.txt). So if I just type in cmd myfile.bat.txt the editor opens. I am not sure how to execute this correctly.
As for the logic in my batch script, I am basically logging into a remote directory (already created the net mount) and now I want to:
run an executeable file
rename some files.
With some research, I written this so far. I have saved it as a .bat file
# echo off
echo This is a batch file to run an executable and rename some files
pause
--run executable file here, just don't know how to do it
x:
cd x:
rename fileA fileB
Any help, good tips/practice would be great. Thanks.
Type in this command in cmd window:
rename myfile.bat.txt myfile.bat
Now you can run the script by simply invoking:
myfile.bat
or
myfile
(provided there's no myfile.exe or myfile.com in the same directory).
If you need to edit the script further, you can either right click it in Explorer and choose Edit or call the editor from the command window:
notepad myfile.bat
To call a program from the script, simply add its name, if it's in the current directory:
someprogram.exe
or the name with the path, if it's somewhere else:
directory\program.exe
or
d:\directory\program.exe
If the name or the path contain spaces, be sure to enclose the entire name & path string in double quotes:
"d:\directory\program name.exe"
you can just type the full name of the program
eg
"c:\program dir\program.exe"
or you can add the program directory to your path environment variable
set PATH=%PATH%;"c:\program dir"
and just type the program name
program
you can also edit your PATH variable in windows http://support.microsoft.com/kb/310519
NOTE: When you save the file in notepad, you want to save it as filename.BAT and select All Files from the second dropdown. If you don't it still gets saved as a .TXT.
A couple of command to consider:
CSCRIPT cscript /? in CMD
START http://ss64.com/nt/start.html
If you're doing say a VBSCRIPT use CSCRIPT to start it. If you're trying to execute another BATCH script or an EXE, use START

Administrator's shortcut to batch file with double quoted parameters

Take an excruciatingly simple batch file:
echo hi
pause
Save that as test.bat. Now, make a shortcut to test.bat. The shortcut runs the batch file, which prints "hi" and then waits for a keypress as expected. Now, add some argument to the target of the shortcut. Now you have a shortcut to:
%path%\test.bat some args
The shortcut runs the batch file as before.
Now, run the shortcut as administrator. (This is on Windows 7 by the way.) You can use either right-click -> Run as Administrator, or go to the shortcut's properties and check the box in the advanced section. Tell UAC that it's okay and once again the shortcut runs the batch file as expected.
Now, change the arguments in the target of the shortcut to add double quotes:
%path%\test.bat "some args"
Now try the shortcut as administrator. It doesn't work this time! A command window pops up and and disappears too fast to see any error. I tried adding > test.log 2>&1 to the shortcut, but no log is created in this case.
Try running the same shortcut (with the double quotes) but not as Administrator. It runs the batch file fine. So, it seems the behavior is not because of the double quoted parameters, and it's not because it's run as Administrator. It's some weird combination of the two.
I also tried running the same command from an administrator's command window. This ran the batch file as expected without error. Running the shortcut from the command window spawned a new command window which flashed and went away. So apparently the issue is caused by a combination of administrator, the shortcut, and the double quotes.
I'm totally stumped, does anyone have any idea what's going on? I'd also like a workaround.
I just ran Process Monitor on this and here is what I saw:
Run as User:
cmd /c ""C:\Users\Sunbelt\Desktop\test.bat" "some args""
Run as Admin:
"C:\Windows\System32\cmd.exe" /C "C:\Users\Sunbelt\Desktop\test.bat" "some args"
For some reason, the Run as Admin case is not quoting the entire command. It seems it is trying to run the command:
C:\Users\Sunbelt\Desktop\test.bat" "some args
I would guess that since the first space is quoted it actually trying to run the following command:
"C:\Users\Sunbelt\Desktop\test.bat some" args
And in Process Monitor logs there is a file system entry of "NO SUCH FILE" for "C:\Users\Sunbelt\Desktop\test.bat some". I don't know why it is different when run as Admin, but that's what appears to be happening.
To work around this, create another bat file on a path without spaces, and with a filename without spaces, that simply does this:
call "Long path to original bat file\Original bat file.bat"
This secondary bat file can be run as admin.
You can now create a shortcut to this secondary bat file and check run as admin in the shortcut's advanced options. The shortcut can be placed on a path with spaces and it can have a filename containing spaces.
In my case I just want to pass one filename as parameter, but the path has spaces.
I found a solution that worked for this case (if that's okay to truncate the file name).
Create another bat file (input_gate.bat) to remove the spaces in the path using the syntax of CALL.exe.
Assuming that the shortcut is named test.lnk and is on the same route as the input_gate.bat:
call %~sdp0test.lnk %~sf1
This pass as a parameter to test.bat the full file name in short format, with administrator privileges.
%~sdp0 -> Is the current path (for the input_gate.bat) in short format.
%~sf1 -> Is the first parameter passed to input_gate.bat (in my case the full filename with spaces)
This worked for me in Windows 7:
ShortcutTarget: C:\Windows\System32\cmd.exe /C myscript.bat Param1 "Param Two with spaces"
StartIn: "C:\Path containing\my script"
Not tried it yet as Admin. I don't think it would work if myscript.bat contained spaces
I finally figured it out, in a way that allows the use of long filenames (short filenames weren't adequate for my use case). My solution works on Win 7, 8, and 10. I think it was inspired by Luke's mention of the missing double-quote.
Here it is:
1.) For the shortcut you create to the batch file, which you set to run as admin, use the following command line:
cmd /s /c ""path_to_batch_file"
Note that there are 2 double-quote characters at the beginning of the command, and only 1 at the end, even though there should normally be 2 at the end also. But that is the trick in getting it to work!
2.) In your batch file, add back the missing double-quote character:
set user_file=%1"
That's it! Here's an example to let you see it in action:
1.) On your desktop, create "test.bat" with the following content:
#echo off
set user_file=%1"
echo The file is: %user_file%
pause
3.) Create a shortcut to the batch file. Set it to run as admin, and give it the following command line:
cmd /s /c ""%userprofile%\desktop\test.bat"
4.) Drag a file onto the shortcut. Success! (I hope...)
Answer here worked for me: https://superuser.com/questions/931003/passing-variables-with-space-to-the-command-line-as-admin
Which is...
Adding cmd /C before the target.
I also had to make sure my script's name and path didn't have spaces, and not quote the script's path in target.

Resources