pass a file to command prompt by OpenWith dropdown menu - batch-file

Well, There is an application called QRCP which can share files through LAN by Qr Code.
It uses a command in cmd to share the file:
I want to add this to SendTo dropdown menu, but the problem is I can't pass it the file that I want to share.
I need something like this:
Which I could pass the file location with %1
and the final command should be like
qrcp send "D:\Program Files\file.exe"
But it seems it's not how it works!

Here is an example that I tried on my side.
This batch file can create a shortcut on SendTo Folder and may be can do the trick for you too , just change the path of QRCP on your side :
#echo off
Title QRCP Batch File
REM Create a shortcut on SendTo Folder
REM "Call :CreateShortcut_SendTo" - This command calls the CreateShortcut_SendTo subroutine,
REM which creates a shortcut in the SendTo folder that can be used to easily execute the script.
Call :CreateShortcut_SendTo
REM This command sets the QRCP_Path variable to the location of the QRCP.exe file in the same directory as the batch file.
Set QRCP_Path="%~dp0QRCP.exe"
Set FilePath=%1
If "%FilePath%" == "" (
Color 0C & echo No File was passed throw this Program, Exiting ... & Timeout /T 5 /NoBreak>nul & Exit
)
%QRCP_Path% %1
echo File %1 passed to QRCP
Exit /B
::---------------------------------------------------------------------------------------------------
:CreateShortcut_SendTo
Powershell -Command "If (Test-Path '%Appdata%\Microsoft\Windows\SendTo\%~n0.lnk') { Remove-Item '%Appdata%\Microsoft\Windows\SendTo\%~n0.lnk' }"
Powershell ^
"$s=(New-Object -COM WScript.Shell).CreateShortcut('%Appdata%\Microsoft\Windows\SendTo\%~n0.lnk'); ^
$s.TargetPath='%~dpnx0'; ^
$s.WorkingDirectory='%~dp0'; ^
$s.IconLocation='%QRCP_Path%,0'; ^
$s.Save()"
Exit /B
::---------------------------------------------------------------------------------------------------

Related

If else statement in bat

The code below checks if there is a folder called Made_files if so it will cd to that folder and make a new file using variables
Else it will make a folder called Made_files THEN cd to that folder and run the code but at the moment all it does is flash up then close instantlly can someone help
if EXIST Made_files (
cd Made_files
set /p name=Name of file:-
set /p Filetype=Type of file(txt, bat js):-
echo #echo off > %name%.%Filetype%
echo color 0a >> %name%.%Filetype%
) else mkdir Made_files
cd Made_files
set /p name=Name of file:-
set /p Filetype=Type of file(txt, bat js):-
echo #echo off > %name%.%Filetype%
echo color 0a >> %name%.%Filetype%
echo ___
pause
#ECHO OFF
SETLOCAL
:: Ask for filename and type
set /p name=Name of file:-
set /p Filetype=Type of file(txt, bat js):-
:: Required file to be located in "Made_files"
SET "subdir=Made_files"
MD ".\%subdir%" 2>NUL
CD "%subdir%"
(
echo #echo off
echo color 0a
)> %name%.%Filetype%
echo ___
pause
GOTO :EOF
What your code does:
If the subdirectory already exists, switch to that directory, ask for the filename&type, then create a new file using the requested data. Otherwise, create the directory.
THEN
Change to the subdirectory again (so if made_files already existed, try to change to .\made_files\made_files), ask for the filename and type and create the file.
===
BUT Please read Stephan's DELAYEDEXPANSION link. Since you are not using delayedexpansion, when the if statement is parsed (and the if statement continues until the end of the else clause) the values of the variables name and filetype are replaced by their values when the statement was parsed (~verified), NOT as they were input, so the destination filename will be nothing.nothing , which is "." - a directory-name (sort-of).
It's likely that this is the source of the drama.
When you use the point-click-and-giggle method of executing a batch, the batch window will close if a syntax-error is found or the script runs to completion. You can put a pause after statements and home in on the error, but better to open a 'command prompt' and run your batch from there so that the window remains open and any (error) messages will be displayed.
===
So : the code I suggest:
Asks for the file name and type.
Attempts to make the directory. If it already exists, this will generate an errormessage which is suppressed by the 2>nul.
switches to that subdirectory.
Creates the file.
Note that if the echoes are surrounded by parentheses, then their output is combined and directed to the file, saving a plethora of redirect-to-file clauses.

How to convert bat to exe and make the exe receive parameters?

I have a bat file that I want to convert into an exe so I can add a icon and a name. But I also need it to accept parameters like my bat file.
Here's the bat file receive parameters like this:%*
The bat file works fine on it own.
#echo off
title Parsing...
set v=%temp%\cmd.vbs
set d=%temp%\decode.wsc
(echo ^<?xml version="1.0"?^>^<component^>^<?component error="true" debug="true"?^>
echo ^<registration description="Url Decode Helper" progid="JSEngine.Url" version="1.0" classid="{80246bcc-45d4-4e92-95dc-4fd9a93d8529}" /^>
echo ^<public^>
echo ^<method name="decode"^>^<PARAMETER name="s"/^>^</method^>
echo ^</public^>
echo ^<script language="JScript"^>
echo ^<!^[CDATA^[
echo var description=new UrlEncodeDecodeHelper;
echo function UrlEncodeDecodeHelper^(^)^{this.decode=decode;^}
echo function decode^(s^)^{return decodeURIComponent^(s.replace^(/\+/g," "^)^);^}
echo ^]^]^>
echo ^</script^>
echo ^</component^>)>%d%
(echo Set JSEngine=GetObject^("Script:C:\Users\vanes\AppData\Local\Temp\decode.wsc"^)
echo Set obj=WScript.CreateObject^("WScript.Shell"^)
echo stre=JSEngine.decode^(Wscript.Arguments^(0^)^)
echo str=Mid^(stre,5^)
echo If Len^(stre^)^>5 Then
echo 'Remove the ^(^'^) from run and move it to para for it to run without confirmation
echo para^(^)
echo 'run^(^)
echo Else
echo obj.Run^("cmd.exe"^)
echo End If
echo.
echo Function para^(^)
echo MsgBox str,vbOKOnly+vbInformation+4096,"Code passed by program:"
echo user=MsgBox^("Do you allow it to pass to the Command prompt and run?",vbQuestion+4096+vbYesNo+vbDefaultButton2,str^)
echo If user=vbYes Then
echo run^(^)
echo Else
echo End If
echo End Function
echo Function run^(^)
echo obj.Run^("cmd.exe /k " ^& str^)
echo End Function)>%v%
rem creates the wsc and vbs files needed.
wscript %v% %*
del %v% %d%
I've tried all sorts of converters but they don't allow me to pass parameters.
Is there any other converter or way to do it manually that will allow me to pass parameters into the exe file created?
I don't need it to have a icon and name right away I can add them through Resource hacker.
I'm trying to make a URL parser that will parser a URL like cmd:shutdown /s so the command shutdown /s will be sent into the command prompt and run. But only if the user allows it to be passed to the cmd!
Here the idea_ https://youtu.be/46pBeyHKQuQ
In this case, the best option may be to "convert" your batch file to an exe by rewriting it in C#. Below is a simple C# program you can use with your URL protocol handler. It converts the URI encoded parameter to plain text, splits off the command by looking for the protocol handler name (assumed to be "cmd:"), and then executes the command using Cmd /c. If you don't want a Cmd console screen popping up, then you could modify this code to run the command directly with a bit more parsing. And, of course, you can add a confirmation prompt as well.
using System;
using System.Diagnostics;
namespace Parser
{
class Program
{
static void Main(string[] args)
{
string x = System.Uri.UnescapeDataString(Environment.CommandLine);
string[] y = x.Split(new string[] {"cmd:"}, StringSplitOptions.None);
Process.Start("Cmd.exe", " /c " + y[1]);
}
}
}
Here is the URL protocol handler reg entries I used to test this:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SOFTWARE\Classes\cmd]
"URL Protocol"="\"\""
#="\"URL:cmd Protocol\""
[HKEY_CURRENT_USER\SOFTWARE\Classes\cmd\DefaultIcon]
#="\"parser.exe,1\""
[HKEY_CURRENT_USER\SOFTWARE\Classes\cmd\shell]
[HKEY_CURRENT_USER\SOFTWARE\Classes\cmd\shell\open]
[HKEY_CURRENT_USER\SOFTWARE\Classes\cmd\shell\open\command]
#="C:\\Parser\\Parser.exe %1"
BTW, you can run a .vbs via the Shell Open registry key by prefixing it with Wscript.exe or Cscript.exe. However, the browser will then ask if you want to run Windows Scripting Host. If you create your own exe, the browser will show the exe name (and you can add an icon) so an exe is probably the way you'll want to go.
I tried Bat To Exe Converter from MajorGeeks.com and it seems to work fine with parameters. One thing I noticed is that when passing arguments to a batch file, %* doesn't include the path of the batch file being run, but the converted exe does.

Kodi - open .strm files by running a .bat / VBScript

I have legal .strm files of different TV Shows in a folder named TV Shows. Each strm file of each episode is stored in different subfolders.
I would like to run a certain VBScript before these strm files are played.
Then I have a different folder named MOVIES. Again, I would like to run a VBScript before these strm files are played. But this VBScript is a different one.
How would I do that?
Platform is Windows.
Thanks!
If you're looking to open or do something to each file based on extension, An easy way to do this is to use an for loop with /R to search all sub-directories for an *.strm file.
#ECHO OFF
SET "LOC=C:\Folder"
CD %LOC%
FOR /R %%A IN (*.strm) DO (
Rem | Do something with each file.
Start cmd.exe /C "notepad.exe "%%A""
)
Echo No More Items Found!
pause
goto :EOF
%%A will return the file path.
Start cmd.exe /C "" will start a CMD command. (Replace with your code)
notepad.exe "" will open the file (Used as an example)
EDIT:
So you're looking to check if the file exists then if true run the script? Bellow should solve that.
#ECHO OFF
If exist (C:/Path/file.strm) (
Rem | File exists, run script
Echo Do something
)
GOTO :EOF

Moving and renaming downloaded files to another directory in WinSCP scripting

I have created the following files that do specific tasks as indicated:
DataCollection.bat - Opens WinSCP and runs command in the dailyimport.txt
Dailyimport.txt - logs into remote FTP site and retrieves three *.csv files, renaming them in the destination folder.
Later a PHP script is executed to import the data in the three CSV files into my database.
What I need to do now, and where I am having a problem is:
Moving the downloaded files (Now on local host) into a new directory, and again renaming them, by keeping the file name and adding a timestamp.
Moving the files on the FTP server into a new directory.
Please see my code I have below:
DataCollection.bat:
#echo off
winscp.com /script=dailyimport.txt
if %ERRORLEVEL% neq 0 goto error
echo Upload succeeded, moving local files
move "C:\DataImport\modules_flat_file_footer.csv" "C:\DataImport\Imported\modules_flat_file_footer.csv.%TIMESTAMP#yyyymmss%"
exit /b 0
:error
echo Upload failed, keeping local files
exit /b 1
dailyimport.txt:
# Connect
open ftp://myftpdetails/
# Change remote directory
cd /downloads/MySQL
# Force binary mode transfer
option transfer binary
# Download file to the local directory
get modules_flat_file_footer_*.csv "C:\DataImport\modules_flat_file_footer.csv"
# Disconnect
close
# Exit WinSCP
exit
The %TIMESTAMP#yyyymmss% is a feature of WinSCP, you cannot use it in Windows batch file directly. Though you can run winscp.com from the batch file to format the timestamp. See the code below and WinSCP example Formatting Timestamp in Batch File.
You are downloading three files to a single local name (modules_flat_file_footer.csv). So you actually lose two of them.
You can use a batch file like this:
#echo off
set SESSION=ftp://username:password#ftp.example.com/
set REMOTE_PATH=/downloads/MySQL
set ARCHIVE_PATH=/remote/archive/path
set LOCAL_PATH=C:\DataImport
set IMPORTED_PATH=C:\DataImport\Imported
set MASK=modules_flat_file_footer_*.csv
winscp.com /ini=nul /log=download.log /command ^
"open %SESSION%" ^
"get %REMOTE_PATH%/%MASK% %LOCAL_PATH%\*" ^
"exit"
if errorlevel 1 (
echo Error downloading
exit /b 1
)
php import.php
if errorlevel 1 (
echo Error importing
exit /b 1
)
for /F "tokens=* USEBACKQ" %%F in (`winscp.com /command "echo %%TIMESTAMP#yyyymmss%%" "exit"`) do (
set STAMP=%%F
)
for %%F in (%LOCAL_PATH%\%MASK%) do (
move %%F %IMPORTED_PATH%\%%~nxF.%STAMP%
if errorlevel 1 (
echo Error moving %%~nxF
exit /b 1
)
winscp.com /ini=nul /log=archive_%%~nxF.log /command ^
"open %SESSION%" ^
"mv %REMOTE_PATH%/%%~nxF %ARCHIVE_PATH%/%%~nxF" ^
"exit"
if errorlevel 1 (
echo Error archiving %%~nxF
exit /b 1
)
)
Though with such a complex logic, you better use a PowerShell, not batch file.
Use WinSCP .NET assembly from the PowerShell script.
In PowerShell you can also enumerate the list of actually downloaded files, so you are sure to move only the files that were downloaded. This protects you against situation that new file is added to the remote folder between the download and move (transactional safety).
You can base the code these official examples for the WinSCP .NET assembly:
Downloading file to timestamped-filename
Moving local files to different location after successful upload

Batch script to wait for file to be generated on FTP server and download

I have a program in my FTP server to generate a file, which may take 3-5 minutes to complete and also I knew the name of the file which i being created by my program. Now, once I initiate the program in my server, I have keep checking until the file is created. Once it is created, I am using the below batch script to ftp the file to my local desktop.
#ftp -i -s:"%~f0"&GOTO:EOF
open 10.100.16.111
username
password
lcd c:\
cd root/output_folder
binary
mget "*partial_file_name*" REM mget using wildcard search
disconnect
bye
This script works fine for me. But the problem is, I need modify this script as such, script should keep running until the file is generated. Because i don't know when the file creation will get completed. So, it will great if some one help/guide me to make a looping script which will wait until the completion of file creation and download the same file through FTP.
With this edit you can launch the batch file with the file name on the command line, like this:
ftpscript.bat "filename.ext"
Note that your lcd uses c:\ which is a restricted location in later versions of windows.
#echo off
>file.tmp echo open 10.100.16.111
>>file.tmp echo username
>>file.tmp echo password
>>file.tmp echo lcd c:\
>>file.tmp echo cd root/output_folder
>>file.tmp echo binary
>>file.tmp echo mget "%~1"
>>file.tmp echo disconnect
>>file.tmp echo bye
:retry
ftp -i -s:"file.tmp"
if not exist "%~1" timeout /t 300 & goto :retry
echo file has downloaded
del file.tmp
pause
More elegant solution is to use an FTP client that supports parametrized scripts or commands on command-line, such as WinSCP, to avoid creating a temporary script file.
Parametrized script
The batch file would be more or less identical as with the Windows ftp:
#echo off
:retry
winscp.com /script=script.txt /parameter "%~1"
if not exist "%~1" timeout /t 300 & goto :retry
echo file has downloaded
pause
The ftp script converts to following WinSCP script:
open ftp://username:password#10.100.16.111/
lcd c:\
cd root/output_folder
get -transfer=binary "%1%"
exit
Commands on command-line
You can also inline the commands the to the batch file:
#echo off
:retry
winscp.com /command ^
"open ftp://username:password#10.100.16.111/" ^
"lcd c:\" ^
"cd root/output_folder" ^
"get -transfer=binary ""%~1""" ^
"exit"
if not exist "%~1" timeout /t 300 & goto :retry
echo file has downloaded
pause
References:
Automating file transfers to FTP server;
Upload to multiple servers / Parametrized script.
Had you ever need to upgrade to the FTPS or the SFTP, just modify the session URL in the open command command accordingly.
(I'm the author of WinSCP)

Resources