切换两个特定文件(或文件夹)的名称

时间:2012-10-13 10:46:23

标签: windows vbscript batch-file

我需要切换存在于本地驱动器上特定路径的两个特定文件的名称,并想知道.bat或.vbs是否可以实现这一点。

换句话说,执行脚本一次将“文件A”与“文件B”交换(“C:\ Path A \ File A.txt”与“C:\ Path A \ File B” .txt“)并再次运行 将再次交换它们。

我也很想知道是否可以这样做:

1)在这种情况下 - >> “C:\ Some Path \ File A.txt”和“D:\ Some Other Path \ File B.txt”

2)如果我想切换两个文件夹而不是两个文件。

1 个答案:

答案 0 :(得分:3)

创建以下批处理文件并根据需要为其命名。我使用的名称是“myRename.bat”。

:: myRename.bat
@echo off
SETLOCAL

:: verify the first file exists
if not exist "%~1" ( echo ERROR: File not found "%~1" & goto endofscript )

:: verify the second file exists
if not exist "%~2" ( echo ERROR: File not found "%~2" & goto endofscript )

:: Create a guaranteed unique string for temporarily naming one file
set instance=%date:~-4,4%%date:~-10,2%%date:~-7,2%
set instance=%instance%-%time:~0,2%%time:~3,2%%time:~6,2%%time:~9,2%
set instance=%instance%-%RANDOM%

:: rename the first file to a temporary name
ren "%~1" "%~nx1.%instance%"
:: rename the second file to the first file name
ren "%~2" "%~nx1"
:: rename teh first file to the second file name
ren "%~1.%instance%" "%~nx2"

:endofscript

假设这两个文件存在于此路径中:

  • c:\ temp \重命名test \ File A.txt
  • c:\ temp \重命名test \ File B.txt

然后你可以运行下面的命令,他们将交换名称:

myRename "c:\temp\Rename test\File A.txt" "c:\temp\Rename test\File B.txt"

如果找不到文件A或文件B,则会在屏幕上报告该错误,并且该过程将停止。