I am looking to smarten up my batch file to NOT include the current database in the menu when the users decides to switch -looks a bit silly to chose something you are already using.
The script scans for text files in the workingdir path and uses them as identifiers for different configurations of the software. It replaces the standard shortcut for the software so the client can choose where they want to connect to - or carry on with the 'current' configuration.
It all does exactly as I want it's just making it a bit smarter with regards to how it appears to the customers.
Within the software to access a different database you just overwrite the workingdir contents with contents of another workingdir but with configs to point somewhere else. When you switch the current set up is backed up to a special directory of its own name, then the other is copied out of its own dir and overwrites the current working dir.
What I am after is (hopefully) some adjustments that will show the user what configuration they are using and if they decided to Switch 'NOT' see the current one as a choice.
What happens now & its fine, but it is clunky, it will tell them what database they are using
you are using Essex_Medical Database
continue (1) or Switch (2)
if they switch they can choose the other option BUT still gives the choice of the current one which I think will look sloppy to the customer.
switch to Essex_Medical Database 1
switch to Newcastle Medical 2
continue (1) (2)
I had a go but my brain fogged up. I think I need a scan to identify the choices via the available text files, set up the input menu from variables and the current one in use be omitted from the input switch options, I hope that makes sense?? Here is the code...
#echo off
color 8b
mode con: cols=80 lines=30
title Multi Database Switcher
rem setting working dir variable
set progdata=C:\ProgramData\Company\WorkingDir
cd %progdata%
for /r %%a in (*.txt) do (
rem spdir 'special directory to hold client specific config file &
rem folders'
set spdir=C:\ProgramData\Company\%%~na
set current=%%~na
)
:menu
CLS
echo.
echo --------------------------------------------------
echo [1] -- Continue Using %current%'s DataBase
echo --------------------------------------------------
echo.
SET /P "Input=Continue(1)/Switch to Another Database(2):"
if '%Input%'=='1' goto continue
if '%Input%'=='2' goto menu2
goto :menu
:menu2
CLS
echo.
echo --------------------------------------------------
echo [2] -- Switch to the 'Essex_Medical' Database
echo [3] -- Switch to the 'Newcastle_Surgery' Database
echo --------------------------------------------------
ECHO.
echo Choose a number...
echo.
SET /P "Input=(2)/(3):"
if '%Input%'=='2' goto Essex_Medical
if '%Input%'=='3' goto Newcastle_Surgery
goto :menu2
:continue
start "" "C:\Temp\Shortcut.lnk" & exit
:Essex_Medical
robocopy %progdata% %spdir% /MIR >nul 2>&1 & robocopy C:\ProgramData\Company\Essex_Medical %progdata% /MIR >nul 2>&1
start "" "C:\Temp\Shortcut.lnk" & exit
:Newcastle_Surgery
robocopy %progdata% %spdir% /MIR >nul 2>&1 & robocopy C:\ProgramData\Company\Newcastle_Surgery %progdata% /MIR >nul 2>&1
start "" "C:\Temp\Shortcut.lnk" & exit
edit for clarity
software program uses a set of folders & a config file in one location c:\programdata\company\workingdir. In workingdir there are 3 or 4 subfolders & one cfg file. They contain info for the software as to what database to use.
I have a client who wants to access other databases, its easily done by over writing the contents of workingdir with a different folder set and config file (all same name etc) with different database details etc.
To facilitate switching my script uses a text file in the workingdir to identify the different databases usually other surgeries essex_surgery , newcastle_surgery so that when the user fires up the script it tells them from the workingdir you ARE using what ever the database is just from what the text file is called. They can continue or switch. When they switch the current working dir is backed up to a separate folder ready to be recalled if its needs to be switched back. Its just robocopy mirroing current to a named folder and over writing with chosen folder set.
My beef is, when you switch, the current database is choice to switch to and its looks silly, why choose something you are already using.
something like:
set "current=Newcastle_Surgery"
(
echo.
echo --------------------------------------------------
echo [2] -- Switch to the 'Essex_Medical' Database
echo [3] -- Switch to the 'Newcastle_Surgery' Database
echo --------------------------------------------------
echo.
)|find /v "%current%"
Perhaps if we populate with an array like this :
#echo off
color 8b
mode con: cols=80 lines=30
title Multi Database Switcher
rem setting working dir variable
set "progdata=C:\ProgramData\Company\WorkingDir"
cd "%progdata%"
setlocal enableDelayedExpansion
for /r %%a in (*.txt) do (
rem spdir 'special directory to hold client specific config file &
rem folders'
rem Populate the array with existent files
set /a idx+=1
set "spdir[!idx!]=C:\ProgramData\Company\%%~na"
set "current[!idx!]=%%~na"
)
:menu
CLS
rem Display array elements
echo --------------------------------------------------
for /L %%i in (1,1,%idx%) do (
set "msg=[%%i] - !current[%%i]!"
echo.
echo !msg!
echo.
echo --------------------------------------------------
)
echo(
echo Please choose a number to continue ...
set /p "Input="
For /L %%i in (1,1,%idx%) Do (
If "%INPUT%" EQU "%%i" (
echo robocopy "%progdata%" "!spdir[%%i]!" /MIR
rem >nul 2>&1 &
echo robocopy "!spdir[%%i]!" "%progdata%" /MIR
rem )>nul 2>&1
echo start "" "C:\Temp\Shortcut.lnk" & pause
rem & exit
)
)
goto :menu
Related
I have written a batch file that I use for file management. The batch file parses an .XML database to get a list of base filenames, then allows the user to move/copy those specific files into a new directory. The program prompts the user for a source directory and the name of the .XML file. I would like the program to default the variables to the last used entry, even if the previous CMD session has closed. My solution has been to ask the user for each variable at the beginning of the program, then write those variables to a separate batch file called param.bat at the end like this:
#echo off
set SOURCEDIR=NOT SET
set XMLFILE=NOT SET
if exist param.bat call param.bat
set /p SOURCEDIR=The current source directory is %SOURCEDIR%. Please input new directory or press [Enter] for no change.
set /p XMLFILE=The current XML database is %XMLFILE%. Please input new database or press [Enter] for no change.
REM {Rest of program goes here}
echo #echo off>param.bat
echo set SOURCEDIR=%SOURCEDIR%>>param.bat
echo set XMLFILE=%XMLFILE%>>param.bat
:END
I was hoping for a more elegant solution that does not require a separate batch file and allows me to store the variable data within the primary batch file itself. Any thoughts?
#echo off
setlocal
dir /r "%~f0" | findstr /c:" %~nx0:settings" 2>nul >nul && (
for /f "usebackq delims=" %%A in ("%~f0:settings") do set %%A
)
if defined SOURCEDIR echo The current source directory is %SOURCEDIR%.
set /p "SOURCEDIR= Please input new directory or press [Enter] for no change. "
if defined XMLFILE echo The current XML database is %XMLFILE%.
set /p "XMLFILE=Please input new database or press [Enter] for no change. "
(
echo SOURCEDIR=%SOURCEDIR%
echo XMLFILE=%XMLFILE%
) > "%~f0:settings"
This uses the Alternate Data Stream (ADS) of the batchfile to
save the settings.
NTFS file system is required. The ADS stream is lost if the
batchfile is copied to a file system other than NTFS.
The dir piped to findstr is to determine if the
stream does exist before trying to read from it.
This helps to avoid an error message from the for
loop if the ADS does not exist.
The for loop sets the variable names and values read from the ADS.
Finally, the variables are saved to the ADS.
Note:
%~f0 is full path to the batchfile.
See for /? about all modifiers available.
%~f0:settings is the batchfile with ADS named settings.
dir /r displays files and those with ADS.
Important:
Any idea involving writing to the batchfile could result
in file corruption so would certainly advise a backup of
the batchfile.
There is one way to save variables itself on the bat file, but, you need replace :END to :EOF
:EOF have a good explained in this link .:|:. see Where does GOTO :EOF return to?
Also, this work in fat32/ntfs file system!
You can write the variables in your bat file, and read when needs:
Obs.: Sorry my limited English
#echo off & setlocal enabledelayedexpansion
set "bat_file="%temp%\new_bat_with_new_var.tmp"" & type nul >!bat_file! & set "nop=ot Se"
for /f %%a in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo 0x40"') do set "delim=%%a"
type "%~f0"| findstr "!delim!"| find /v /i "echo" >nul || for %%s in (SOURCEDIR XMLFILE) do set "%%s=N!nop!t"
if defined SOURCEDIR echo/!SOURCEDIR!%delim%!XMLFILE!%delim%>>"%~f0"
for /f "delims=%delim% tokens=1,2" %%a in ('type "%~f0"^| findstr /l "!delim!"^| find /v /i "echo"') do (
set /p "SOURCEDIR=The current source directory is %%~a. Please input new directory or press [Enter] for no change: "
set /p "XMLFILE=The current XML database is %%~b. Please input new database or press [Enter] for no change: "
if /i "!old_string!" neq "!SOURCEDIR!!delim!!XMLFILE!!delim!" (
type "%~f0"| findstr /vic:"%%~a!delim!%%~b!delim!">>!bat_file!"
copy /y !bat_file! "%~f0" >nul
echo/!SOURCEDIR!!delim!!XMLFILE!!delim!>>%~f0"
goto :_continue_:
))
:_continue_:
rem :| Rest of program goes here | replace/change last command [goto :END] to [goto :EOF]
goto :EOF
rem :| Left 2 line blank above, because your variable will be save/read in next line above here |:
Okay here is what I got so far.
This is meant to add websites to block in the hosts file, as well as allow the user to delete the entries when they want to. When trying to add a website to block sometimes it creates a new line then puts the entry on the line before it. This is not what I want. I want it to create a new line then add the entry on that line. For some reason it works sometimes and other times it don't work at all. I get an error message that says Find parameter is incorrect. I am using the Find command to see if the entries is already in the hosts file. If it is I want it to avoid adding it. If it is not then I want to add it. When I try to delete a entry the batch just crashes, so I am not really sure what I am doing wrong here. I am trying to find the entry and replace it with nothing. What I really want to do is delete the entire line so that I don't end up with a lot of blank lines.
Any help is greatly appreciated. Thanks!
#echo off
TITLE Modifying your HOSTS file
COLOR F0
:LOOP
cls
SET "CHOICE="
ECHO Choose 1 to block a website
ECHO Choose 2 remove a blocked website
ECHO Choose 3 to exit
SET /P CHOICE= selection %CHOICE%
GOTO %CHOICE%
:1
cls
SET /P WEBSITE=Enter the name of the website to add:
SET HOME= 127.0.0.1
SET NEWLINE=^& echo.
SET BLOCKEDSITE=%HOME% %WEBSITE%
FIND /C /I %BLOCKEDSITE% %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^%BLOCKEDSITE%>>%WINDIR%\System32\drivers\etc\hosts
ECHO Website blocked
ping 127.0.0.1 -n 5 > nul
GOTO LOOP
:2
cls
SET /P WEBSITE=Enter the name of the website to remove:
SETLOCAL ENABLEEXTENTIONS DISABLEDELAYEDEXPANSION
SET "HOME= 127.0.0.1 "
SET "BLOCKEDSITE=%HOME% %WEBSITE%"
SET "REPLACE="
SET "HOSTSFILE=%WINDIR%\system32\drivers\etc\hosts"
FOR /F "DELIMS=" %%i IN ('TYPE "%HOSTSFILE%" ^& BREAK ^> "%HOSTSFILE%" ')
DO
(
SET "LINE=%%i"
SETLOCAL ENABLEDELAYEDEXPANSION
>>"%HOSTSFILE%" echo(!LINE:%BLOCKEDSITE%=%REPLACE%!
ENDLOCAL
)
ECHO Website unblocked
GOTO LOOP
:3
EXIT
Please note that the term website is misleading when referring to the entries of the hosts file. The entries of hosts file are used for custom mappings of DNS host names to IP addresses, and any host name that is present in the file does not necessarily hosts a website. Using the term website may lead to the false impression that something like http://www.example.com can be added to hosts file which is not true.
Skipping a host if it is already present in the hosts file:
The problem with your usage of find is that %BLOCKEDSITE% has embedded spaces so you should enclose it quotes and use:
FIND /C /I "%BLOCKEDSITE%" %WINDIR%\system32\drivers\etc\hosts
But it has another problem: Because of its dependency on the exact spacing between the IP address and host name which is mandated by %BLOCKEDSITE% It only works for the entries that are added by your batch file. Additionally the user may have commented out (disabled) an entry by placing # in the begging of the line that contains the entry, and your batch code will skip adding the host even if the entry is disabled.
This can be resolved by using findstr with its regex syntax. for example:
findstr /IRC:"^ *127\.0\.0\.1 *example\.com *$" "%WINDIR%\system32\drivers\etc\hosts"
Removing an entry from the hosts file:
In the FOR loop you just have to skip writing the lines that contains the specified entry:
if "!Line!"=="!LINE:%BLOCKEDSITE%=!" echo(!Line!>>"%HOSTSFILE%"
But again it is not accurate and is suffering from the same problems that are mentioned earlier for skipping adding the entry. Again By using findstr you can easily remove the lines that contain the unwanted entry:
findstr /VIRC:"^ *127\.0\.0\.1 *example\.com *$" "%HOSTSFILE%" > "%HOSTSFILE%.tmp"
del "%HOSTSFILE%"
ren "%HOSTSFILE%.tmp" "hosts"
With above mentioned points the script can be rewritten like this:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
title Modifying your HOSTS file
color F0
set "HOSTSFILE=%WINDIR%\system32\drivers\etc\hosts"
set "HOME=127.0.0.1"
set "PROMPT_TEXT=Enter the host name to"
set "ACTION_TEXT[1]=add"
set "ACTION_TEXT[2]=remove"
set "FindEmptyLine=^ *$"
set "NewLineAppended="
cls
setlocal EnableDelayedExpansion
:LOOP
echo,
echo 1. Block a host
echo 2. Remove a blocked host
echo 3. Exit
choice /C "123" /N /M "Choose an item [1, 2, 3]: "
set "Item=%errorlevel%"
goto choice%Item%
:choice0 // User Pressed CTRL-C
:choice3
exit /b
:choice1
call :Common
set "HostEntry=!HOME! !HOST!"
findstr /IRC:"!FindEntry!" "!HOSTSFILE!"> nul && (
echo The host !HOST! is already blocked, No action taken.
) || (
if not defined NewLineAppended (
REM This will append a new line ONLY if the file does not end by LF character
type "!HOSTSFILE!" | findstr $ > "!HOSTSFILE!.tmp" && (
del "!HOSTSFILE!"
ren "!HOSTSFILE!.tmp" "hosts"
set "NewLineAppended=1"
)
)
echo !HostEntry!>>"!HOSTSFILE!"
echo The host !HOST! blocked
)
goto LOOP
:choice2
call :Common
findstr /VIR /C:"!FindEntry!" /C:"!FindEmptyLine!" "!HOSTSFILE!">"!HOSTSFILE!.tmp" && (
del "!HOSTSFILE!"
ren "!HOSTSFILE!.tmp" "hosts"
echo The host !HOST! unblocked
)
goto LOOP
:Common
set "HOST="
set /P "HOST=!PROMPT_TEXT! !ACTION_TEXT[%Item%]! (e.g. example.com): "
if not defined HOST (
(goto)2>nul
goto LOOP
)
set "FindEntry=^^ *!HOME! *!HOST! *$"
set "FindEntry=!FindEntry:.=\.!"
exit /b
So, I've been working on a batch script that essentially helps you with youtube-dl, essentially filing out all the data it needs to download into a directory. I want to be able to make a special shortcut that launches it, and instead of doing what it normally does, I want it to go through a text file (for example, let's call it update list.txt) and update playlists when that shortcut is run. I don't want to make another batch file that does this (for simplicity for user).
Here's what I have so far:
#echo off
:loop
title Welcome to CCF_100's youtube-dl helper!
set /A loop=loop+1
echo.Times Looped: %loop%
cd %~dp0
set /p input=Enter YouTube ID, URL, or Playlist ID:
set /p Output_Dir=Enter Directory you want to save in (Directory will be
created if it does not exist):
set /p flags=Enter flags (Optional):
if exist %Output_Dir%\ (goto Do_the_thing) else (goto make_directory)
:make_directory
mkdir "%Output_Dir%"
if /I %loop% LEQ 2 goto Do_the_thing
explorer "%Output_Dir%"
:Do_the_thing
title CCF_100's ytdl helper: currently downloading: %input% to %Output_Dir%
youtube-dl.exe -i -U %flags% -o "%Output_Dir%\%%(title)s - %%(id)s.%%(ext)s"
%input%
set /p loop=Successfully downloaded file(s). Download more?
if /i %loop%==y goto loop
if /i %loop%==Y goto loop
if /i %loop%==n goto end
if /i %loop%==N goto end
:end
exit
And yes I know the last two if statements are unnecessary.
You can get the arguments of a batchfile by reading the value of %n with n being a number between 0 and 9 or an asterisk. 0 is the batch-file itself (in the sense of the path to it) and the asterisk means any additional argument (excluding the batch-file-path).
So with that you can check for the contents of %1 and see if it is the flag you thought of or existent at all:
REM Demo only!
#echo off
if "%1"=="" (
echo no flags set
) ELSE (
echo flag set: %1
)
or change the if in a similar fashion to react to your flag only.
I wrote myself a script based off another one that I found and I'm having trouble figuring out why it's not working.
How it is supposed to work is once a torrent has finished downloading, it runs the script and grabs the Label on the torrent. For testing, I was downloading a song with the label of Music.
When it gets to the point at :copyfile, it won't move it into the correct directory. Instead of moving into F:\Completed Torrents\Music, it just moves into F:\Completed Torrents.
Can someone please point out what I'm missing because I've looked through it thrice already and it's driving me crazy. The script is below.
#echo off
title Liam's torrent-file script
rem Parameter usage: fromdir torrent-name label kind [filename]
rem corresponds to uTorrents flags: %D %N %L %K %F
echo *********************************************
echo Run on %date% at %time%
set fromdir=%1
set name=%2
set label=%3
set kind=%4
set filename=%5
set savepartition="F:\Completed Torrents"
set winrar="C:\Program Files (x86)\WinRAR\WinRAR.exe"
set torrentlog="F:\Torrent Scripts\logs\torrentlog.txt"
set handledlog="F:\Torrent Scripts\logs\handled_torrents.txt"
set errorlog="F:\Torrent Scripts\logs\ErrorLog.txt"
set label_prefix=""
echo Input: %fromdir% %name% %label% %kind% %filename%
rem Check if the label has a sub label by searching for \
if x%label:\=%==x%label% goto skipsublabel
rem Has a sub label so split into prefix and suffix so we can process properly later
echo sub label
for /f "tokens=1,2 delims=\ " %%a in ("%label%") do set label_prefix=%%a&set label_suffix=%%b
rem add the removed quote mark
set label_prefix=%label_prefix%"
set label_suffix="%label_suffix%
echo.prefix : %label_prefix%
echo.suffix : %label_suffix%
goto:startprocess
:skipsublabel
echo Skipped Sub Label
goto:startprocess
:startprocess
echo %date% at %time%: Handling %label% torrent %name% >> %handledlog%
rem Process the label
if %label%=="Movies" goto known
if %label%=="Music" goto known
if %label_prefix%=="TV" goto TV
rem Last resort
rem Double underscores so the folders are easier to spot (listed on top in explorer)
echo Last Resort
set todir=%savepartition%\Unsorted\__%name%
if %kind%=="single" goto copyfile
if %kind%=="multi" goto copyall
GOTO:EOF
:known
echo **Known Download Type - %label%
set todir=%savepartition%\%label%\%name%
echo todir = %todir%
GOTO:process
:TV
echo **Known Download Type - %label%
set todir=%savepartition%\%label_prefix%\%label_suffix%
echo todir = %todir%
GOTO:process
:process
rem If there are rar files in the folder, extract them.
rem If there are mkvs, copy them. Check for rars first in case there is a sample.mkv, then we want the rars
if %kind%=="single" goto copyfile
if exist %fromdir%\*.rar goto extractrar
if exist %fromdir%\*.mkv goto copymkvs
if %kind%=="multi" goto copyall
echo Guess we didnt find anything
GOTO:EOF
:copyall
echo **Type unidentified so copying all
echo Copy all contents of %fromdir% to %todir%
xcopy %fromdir%\*.* %todir% /S /I /Y
GOTO:EOF
:copyfile
rem Copies single file from fromdir to todir
echo Single file so just copying
echo Copy %filename% from %fromdir% to %todir%
xcopy %fromdir%\%filename% %todir%\ /S /Y
GOTO:EOF
:copymkvs
echo Copy all mkvs from %fromdir% and subdirs to %todir%
xcopy %fromdir%\*.mkv %todir% /S /I /Y
GOTO:EOF
:extractrar
echo Extracts all rars in %fromdir% to %todir%.
rem Requires WinRar installed to c:\Program files
if not exist %todir% mkdir %todir%
IF EXIST %fromdir%\subs xcopy %fromdir%\subs %todir% /S /I /Y
IF EXIST %fromdir%\subtitles xcopy %fromdir%\subtitles %todir% /S /I /Y
call %winrar% x %fromdir%\*.rar *.* %todir% -IBCK -ilog"%todir%\RarErrors.log"
IF EXIST %fromdir%\*.nfo xcopy %fromdir%\*.nfo %todir% /S /I /Y
GOTO:EOF
EDIT
Also, for some reason, on line 39 nothing prints to the log. For those who wish to see the code with line numbers: http://hastebin.com/juqokefoxa.dos
A couple of bits for ya:
1) Likely, your script isn't moving the files. Preferences / Directories has an option to move downloads when completed. verify that these settings aren't doing the file moving.
2) uTorrent locks the files on completion so that seeding can continue. To change this behavior, go to Preferences / Advanced and set bt.read_only_on_complete to false
3) you will still be foiled because "Run this program when a torrent finishes" doesn't really do what it says. It runs the program as downloading reaches 100%, but while uTorrent is still either moving the file or seeding. See my bug report here.
A quick summary of the post, just in case that post gets deleted: you have to set the command in "Run this program when a torrent changes state:", add a %S parameter and check that %S == 11
4) Just a tip from my attempt at doing something very similar: when you set the variables from the arguments, add a tilde (%~1 instead of %1). This will strip the quotes off and let us more easily build command lines with the variables later.
You say that the log is not being written to. Try this as a test and see if it writes to the log.
If it doesn't there there is some other fundamental problem.
#echo off
title Liam's torrent-file script
rem Parameter usage: fromdir torrent-name label kind [filename]
rem corresponds to uTorrents flags: %D %N %L %K %F
echo *********************************************
echo Run on %date% at %time%
set "fromdir=%~1"
set "name=%~2"
set "label=%~3"
set "kind=%~4"
set "filename=%~5"
set "savepartition=F:\Completed Torrents"
set "winrar=C:\Program Files (x86)\WinRAR\WinRAR.exe"
set "torrentlog=F:\Torrent Scripts\logs\torrentlog.txt"
set "handledlog=F:\Torrent Scripts\logs\handled_torrents.txt"
set "errorlog=F:\Torrent Scripts\logs\ErrorLog.txt"
set "label_prefix="
set "handledlog=%userprofile%\desktop\handled_torrents.txt"
>> "%handledlog%" echo Input: "%fromdir%" "%name%" "%label%" "%kind%" "%filename%"
>> "%handledlog%" echo %date% at %time%: Handling "%label%" torrent "%name%"
I have a portable development tool that I want to use on other PCs. I'd like to set a file association so that clicking a file opens the tool. Then, when I'm finished, I want to undo or reset the file association on that PC.
Is there a way to do this? Possibly from a batch file?
Well, you can use the ftype and assoc commands to create or delete file type associations:
ASSOC .foo=FooFile
FTYPE FooFile=X:\Foo\foo.exe %1 %*
You can delete them later with
FTYPE FooFile=
ASSOC .foo=
EDIT: I've got a try now with something that enables you to re-set the association back to its default. I put it in my Subversion repo. In its current stage it generates two new batch files: set.cmd and reset.cmd; one of which sets a new association, the other reverses it. Rolling the set.cmd into the actual batch shouldn't be too difficult but it would have made testing here a hell, so I'll leave that as an exercise.
Code follows, it should be commented enough, hopefully.
#echo off
setlocal enableextensions enabledelayedexpansion
rem Debug flag. Generates a little more output; un-set if undesired
set DEBUG=1
rem Parse arguments and help
if [%1]==[] goto Usage
if [%2]==[] goto Usage
rem Find out whether the association is taken
for /f "usebackq tokens=2* delims==" %%x in (`assoc .%1 2^>nul`) do set assoc_old=%%x
if defined DEBUG (
if defined assoc_old (echo Association already defined: [%assoc_old%]) else (echo Association not yet taken)
)
rem Find a new, unused association
rem Note that we assume that we find one, eventually. This isn't guaranteed, but we'll ignore that for the moment
rem Otherwise this loop might run forever
:loop
set assoc_new=My.%1.%RANDOM%
if defined DEBUG echo Trying new association (%assoc_new%)
assoc .%1 >nul 2>nul
if errorlevel 1 (
set assoc_new=
if defined DEBUG echo Didn't work out
) else (
if defined DEBUG echo Found one! \o/
)
if not defined assoc_new goto loop
if defined DEBUG echo Writing reset batch file
echo #echo off>reset.cmd
echo assoc .%1=%assoc_old%>>reset.cmd
echo ftype %assoc_new%=>>reset.cmd
if defined DEBUG echo Writing setting batch file
echo #echo off>set.cmd
echo assoc .%1=%assoc_new%>>set.cmd
echo ftype %assoc_new%=%2 %%1>>set.cmd
goto :eof
:Usage
echo.Usage
echo. %~nx0 type command
echo.
echo. type is the file type to override, such as docx or txt.
echo. No dot before it is necessary.
echo. command is the command to perform on that file.
echo. %%1 is automatically appended at the end.
echo. If the command includes spaces, surround it with quotes.
echo.
echo.Example
echo. %~nx0 txt notepad
exit /b 1