ここにリストした各コマンドを使用してcommandname /?
、詳細情報を得ることができます。
%date%
環境変数の 2 番目のトークンとdate /t
コマンドは、今日の日付をリストと同じ形式でdir
表示します。
このdir
コマンドには/a
、特定の属性を持つ (または持たない) ファイルのみを表示できるスイッチがあります。.
ディレクトリ (やなど) を除外するには、を..
使用しますdir /a:-d
。
を使用して、コマンドの出力をキャプチャできますfor /f
。
最後に、find
またはfindstr
コマンドを使用して文字列の存在をテストできます。 findstr
より柔軟に正規表現を使用して検索できます。ただし、リテラル文字列を検索するだけの場合は、find
問題なく動作します。
すべてをまとめる:
@echo off
rem "setlocal" prevents any variables you set within your batch script
rem from remaining as environment orphans after the script completes.
setlocal
rem set variable %today% as the second token of %date%
for /f "tokens=2" %%I in ("%date%") do set today=%%I
rem dir list, skip directories, skip this batch script, include only files with a date matching %today%
for /f "tokens=4*" %%H in ('dir /a-d ^| findstr /v /i "%~nx0$" ^| find "%today%"') do (
rem record success for later
set found=1
rem search file %%I for "string" (case-insensitive).
find /i "string" "%%I">NUL
rem Was last command successful?
if %ERRORLEVEL%==0 (
echo Test string found
) else (
echo Test string NOT found
)
)
rem if success was not recorded
if not defined found echo No file today
その後、コーディングを目的を達成するための手段ではなく、芸術的表現の手段として認識し始めると、より高度なトリックを実行して、より少ないコード行で同じタスクを実行できます。
@echo off
setlocal
for /f "tokens=2" %%I in ("%date%") do set today=%%I
for /f "tokens=4*" %%H in ('dir /a-d ^| findstr /v /i "%~nx0$" ^| find "%today%" ^|^| echo No file today 1^>^&2') do (
(find /i "string" "%%I" >NUL && (
echo Test string found.
)) || echo Test string not found.
)