我正在尝试创建要在批处理文件中使用的临时文件的路径.
有环境变量%TEMP%并%TMP%获取当前用户的临时目录.但是如何建立一个肯定还不存在的文件名呢?
当然我可以使用内置变量%RANDOM%并创建类似的东西bat~%RANDOM%.tmp,但是这个方法不能确保文件当前不存在(或者它会在我第一次在磁盘上创建并写入它之前由另一个应用程序巧妙地创建) - 虽然这一切都不太可能.
我知道我可以通过附加%DATE%/ %TIME%或仅添加多个%RANDOM%实例来减少此类冲突的可能性,但这不是我想要的......
注意:根据这篇文章,.NET(Path.GetTempFileName())中有一个方法可以完全满足我的要求(除了显然错误的编程语言).
尝试下一个代码段:
@echo off
setlocal EnableExtensions
rem get unique file name
:uniqLoop
set "uniqueFileName=%tmp%\bat~%RANDOM%.tmp"
if exist "%uniqueFileName%" goto :uniqLoop
Run Code Online (Sandbox Code Playgroud)
或创建程序
:uniqGet:创建修复文件名模板的文件(bat~%RANDOM%.tmp在您的情况下);:uniqGetByMask:创建一个可变文件名模板的文件.注意%random%过程调用中四倍的引用符号:prefix%%%%random%%%%suffix.ext.还要注意的高级用法:CALL荷兰国际集团内部命令在call set "_uniqueFileName=%~2"程序里面.代码可以如下:
@ECHO OFF
SETLOCAL enableextensions
call :uniqGet uniqueFile1 "%temp%"
call :uniqGet uniqueFile2 "%tmp%"
call :uniqGet uniqueFile3 d:\test\afolderpath\withoutspaces
call :uniqGet uniqueFile4 "d:\test\a folder path\with spaces"
call :uniqGetByMask uniqueFile7 d:\test\afolder\withoutspaces\prfx%%%%random%%%%sffx.ext
call :uniqGetByMask uniqueFile8 "d:\test\a folder\with spaces\prfx%%%%random%%%%sffx.ext"
set uniqueFile
pause
goto :continuescript
rem get unique file name procedure
rem usage: call :uniqGetByMask VariableName "folderpath\prefix%%%%random%%%%suffix.ext"
rem parameter #1=variable name where the filename save to
rem parameter #2=folder\file mask
:uniqGetByMask
rem in the next line (optional): create the "%~dp2" folder if does not exist
md "%~dp2" 2>NUL
call set "_uniqueFileName=%~2"
if exist "%_uniqueFileName%" goto :uniqGetByMask
set "%~1=%_uniqueFileName%"
rem want to create an empty file? remove the `@rem` word from next line
@rem type nul > "%_uniqueFileName%"
exit /B
goto :continuescript
@rem get unique file name procedure
@rem usage: call :uniqGet VariableName folder
@rem parameter #1=variable name where the filename save to
@rem parameter #2=folder where the file should be about
:uniqGet
@rem in the next line (optional): create the "%~2" folder if does not exist
md "%~2" 2>NUL
set "_uniqueFileName=%~2\bat~%RANDOM%.tmp"
if exist "%_uniqueFileName%" goto :uniqGet
set "%~1=%_uniqueFileName%"
@rem want to create empty file? remove the `@rem` word from next line
@rem type nul > "%_uniqueFileName%"
exit /B
:continueScript
Run Code Online (Sandbox Code Playgroud)
输出:
==>D:\bat\SO\32107998.bat
uniqueFile1=D:\tempUser\me\bat~21536.tmp
uniqueFile2=D:\tempUser\me\bat~15316.tmp
uniqueFile3=d:\test\afolderpath\withoutspaces\bat~12769.tmp
uniqueFile4=d:\test\a folder path\with spaces\bat~14000.tmp
uniqueFile7=d:\test\afolder\withoutspaces\prfx26641sffx.ext
uniqueFile8=d:\test\a folder\with spaces\prfx30321sffx.ext
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)