LoginSignup
2
0

More than 1 year has passed since last update.

バッチファイルで引数(ファイル)を利用する

Posted at

バッチファイルの引数(ファイル)のパスを取得したり、処理をしたりする方法。毎回忘れてしまうので具体例でまとめ。

ファイル(%1)のパスを展開する

コマンドの例
C:\work>a.bat sample.txt
修飾子 展開結果
%~f1 C:\work\sample.txt フルパス
%~dp1 C:\work\ フォルダパス
%~nx1 sample.txt ファイル名(拡張子あり)
%~n1 sample ファイル名(拡張子なし)
%~x1 .txt 拡張子
%~1 sample.txt
%~d1 C:
%~p1 \work\

バッチファイル(%0)のあるフォルダを作業フォルダにする

a.bat
REM エコーをOFFにする場合は @echo off
cd /d %~dp0

すべての引数(%*)に対して処理をする

すべての引数に対して個別に処理をする方法

a.bat
for %%f in (%*) do (
  REM 処理内容
)

先にファイルの存在確認をしてから処理をする方法

a.bat
REM ファイルの存在確認
for %%f in (%*) do (
  if not exist %%~ff goto error
)

REM すべてのファイルに対して処理
for %%f in (%*) do (
  REM 処理内容
)
goto end

REM ファイルが1つでも存在しない場合はエラーを出して終了
:error
echo ファイルが存在しません。
goto end

:end

バッチファイルの処理を一時停止する

バッチファイルはたまにしか作成しないので、うまく動作しないことが多い。最後にpauseを書いて状況確認をする。

a.bat
REM 処理内容をここに記載
pause
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0