Create unique file name Windows batch

前端 未结 10 1472
闹比i
闹比i 2020-12-16 15:57

I have seen many posts about creating a unique filename from the naive %TIME% to the plausible (but insufficient) %RANDOM%. Using wmic os get localdatetime is m

10条回答
  •  无人及你
    2020-12-16 16:21

    You could use certutil to base64 encode %date% %time% with a %random% seed like this:

    @echo off
    setlocal
    
    :: generate unique ID string
    >"%temp%\~%~n0.%username%.a" echo %username%%date%%time%%random%
    >NUL certutil -encode "%temp%\~%~n0.%username%.a" "%temp%\~%~n0.%username%.b"
    for /f "usebackq EOL=- delims==" %%I in ("%temp%\~%~n0.%username%.b") do set "unique_id=%%I"
    del "%temp%\~%~n0.%username%.a" "%temp%\~%~n0.%username%.b"
    
    echo %unique_id%
    

    In case the same script is being run from the same directory by multiple users, I added %username% to the temp files to avoid further conflict. I suppose you could replace %random% with %username% for the same effect. Then you'd only get a conflict if a single user executes the same code block twice concurrently.

    (Edit: added %username% as a seed for uniqueness.)

提交回复
热议问题