1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

◇Windowsのバッチファイルでカレントフォルダ名を取得する

Last updated at Posted at 2022-08-19

◇カレントフォルダ名を取得する

バッチファイルにファイルやフォルダをドラッグアンドドロップして処理する時に、ドロップされたパスの最後のフォルダとなるカレントフォルダを取得します。

バッチファイルではcallで呼び出したルーチンには通常とは別の%1などの特殊変数が使えます。
これを使うことでパスを分解できます。

例えば
C:\AAA\BBB\CCC\DDD.txtからCCCを取り出します。

:: ドロップされたパスからカレントフォルダ名を取得;
:GetCurrenrFolderName
set TargetFolderName=%~dp1
set TargetFolderName=%TargetFolderName:~0,-1%
set TargetPathATTR=%~a1
set TargetPathATTR=%TargetPathATTR:~0,1%
if /i "%TargetPathATTR%" equ "d" if /i "%~n1" neq "" (
  set TargetFolderName=%~dpn1
)
call :GetName "%TargetFolderName%"
goto :EndGetCurrenrFolderName
:GetName
set TargetFolderName=%~n1
exit /b
:EndGetCurrenrFolderName
echo Current FolderName = "%TargetFolderName%"
echo.

ドロップされたパスから種別とカレントフォルダ情報を表示するサンプル

DropFileIdentification.bat
@echo off


:: 遅延展開 バグの原因になる場合があるので注意;
setlocal enabledelayedexpansion


:: エスケープシーケンスを利用;
for /f "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set ESC=%%b)


echo ◇ドロップされたパスから種別とカレントフォルダ情報を表示します。
echo.


:: ドロップされたパスがドライブかファイルかフォルダか判別する;
set TargetPath=%1
set TargetPathATTR=%~a1
set TargetPathATTR=%TargetPathATTR:~0,1%
if /i "%~n1" equ "" (
  echo "%1" is drive.
)
if /i "%TargetPathATTR%" equ "d" if /i "%~n1" neq "" (
  echo "%1" is folder.
)
if /i "%TargetPathATTR%" neq "d" (
  echo "%1" is file.
)
echo.


:: ドロップされたパスからカレントフォルダ名を取り出す;
:GetCurrenrFolderName
set TargetFolderName=%~dp1
set TargetFolderName=%TargetFolderName:~0,-1%
set TargetPathATTR=%~a1
set TargetPathATTR=%TargetPathATTR:~0,1%
if /i "%TargetPathATTR%" equ "d" if /i "%~n1" neq "" (
  set TargetFolderName=%~dpn1
)
call :GetName "%TargetFolderName%"
goto :EndGetCurrenrFolderName
:GetName
set TargetFolderName=%~n1
exit /b
:EndGetCurrenrFolderName
echo Current FolderName = "%TargetFolderName%"
echo.


:: 終了処理を起動条件により分岐(エクスプローラーから起動されていた場合は選択処理);
:EndProcess
echo %CMDCMDLINE%|find /i "%~f0">NUL
if "%ERRORLEVEL%" neq "0" (goto :eof)
choice /t 10 /c qa /d q /m "10秒待機します。即閉じる場合はQ、待機はAを押してください。"
if "%ERRORLEVEL%" equ "2" (
  echo %ESC%[1A%ESC%[2K%ESC%[1A
  pause
)
goto :eof

おわりに

他にも「⧉Windowsのバッチファイルのテクニックをご紹介します」にてご紹介させて頂いております。
お時間ありましたら覗いてみてください
お粗末様でした。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?