Created
May 5, 2019 06:28
-
-
Save seraphy/0fc14023b40935ed925021e64ebaf7b2 to your computer and use it in GitHub Desktop.
バッチファイルがExplorerかTerminalのどちらで起動されたか判定する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo off | |
rem ==================================================================== | |
rem バッチファイルがExplorerかTerminalのどちらで起動されたか判定する方法 | |
rem ==================================================================== | |
rem | |
rem %cmdcmdline%環境変数にはシェル起動時のコマンドラインが格納されている | |
rem explorerから起動した場合は、 | |
rem C:\WINDOWS\system32\cmd.exe /c ""C:\Users\archa\Desktop\determine_launch_from_explorer.bat" " | |
rem のような内容となり、 | |
rem ターミナルからバッチファイルを指定した場合は | |
rem "C:\Windows\SysWOW64\cmd.exe" | |
rem のような内容が入っている。 | |
rem | |
rem そこで、エクスプローラから渡されるであろう文字列の一部をトリムするようにして | |
rem 実際にトリムできたか判定する。トリムされていればエクスプローラからであるし、 | |
rem トリムされていなければトリムする文字がなかったということなのでエスプローラではない、と判断できる | |
rem | |
rem 環境変数は%varname:str=rep%の形式で、環境変数varname中の文字strをrepに置き換えることができる。 | |
rem repを空にすればトリムとなる。 | |
rem | |
rem なお、ifで判定する上でダブルクォートがネストしているとまずいので判定前にダブルクォートは除去する細工をいれている。 | |
rem | |
rem [参考] | |
rem https://stackoverflow.com/questions/7005951/batch-file-find-if-substring-is-in-string-not-in-a-file | |
rem https://stackoverflow.com/questions/1964192/removing-double-quotes-from-variables-in-batch-file-creates-problems-with-cmd-en | |
set A=%cmdcmdline% | |
set A=%A:"=% | |
if not "%A%" == "%A:/c=%" ( | |
echo launch from explorer | |
echo ターミナルで起動し直します | |
pause | |
cmd.exe /k "%~f0" | |
exit /b | |
) | |
echo launch from terminal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment