Create unique file name Windows batch

前端 未结 10 1456
闹比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:24

    A long time ago in a galax..newsgroup called alt.msdos.batch, a contributor insisted on posting a QBASIC solution to each issue raised, wrapped in a batch shell and claiming it was batch because it only used standard Microsoft-supplied software.

    After a long time, he was cured of his errant ways, but I've been severely allergic to hybrid methods ever since. Sure - if it cures the problem, blah,blah - and sometimes there's no escaping that course (run batch silently, for instance.) Apart from that, I really don't want thebother of learning a new language or two...So that's why I eschew *script solutions. YMMV.

    So - here's another approach...

    @ECHO OFF
    SETLOCAL
    :rndtitle
    SET "progtitle=My Batch File x%random%x"
    TITLE "%progtitle%"
    SET "underline="
    SET "targetline="
    FOR /f "delims=" %%a IN ('TASKLIST /v^|findstr /i /L /c:"======" /c:"%progtitle%"') DO (
     IF DEFINED underline (
      IF DEFINED targetline GOTO rndtitle
      SET "targetline=%%a"
     ) ELSE (SET "underline=%%a")
    )
    
    :: Here be a trap. The first column expands to fit the longest image name...
    :pidloop
    IF "%underline:~0,1%"=="=" SET "underline=%underline:~1%"&SET "targetline=%targetline:~1%"&GOTO pidloop
    FOR /f %%a IN ("%targetline%") DO SET /a pid=%%a
    ECHO %pid%
    
    GOTO :EOF
    

    Essentially, set the title to something random. Note that x%random%x is used, not simply %random% so that a search for "x123x" won't detect "x1234x".

    Next, get a verbose tasklist, locating the line underlining the heading and the title. The first line returned by findstr will be the underline, the next will set targetline and any further returns indicate that the title is not unique, so go back, change it and try again until it is unique.

    Finally, get the process ID which is in the second column, noting that the first is of unknown width (hence why the underline is grabbed.)

    Result : this process's PID which must be unique and hence can be used as the basis for a unique tempfile name - build it in a directory reserved for the purpose.

提交回复
热议问题