windowsbatch-filemklink

Listing non symbolic link on Windows


I'm trying to list non-symbolic links in an specific directory and then delete them.

non-symbolic links definition: any file besides the ones that have been created using the command MKLINK /H

To identify those non-symbolic links I used the following approach:

#> fsutil hardlink list %file% | find /c /v ""

When the specified %file% is a symbolic link it returns a number bigger than 1, when it is just a simple file, it returns 1. So far so good!

My problem starts when I need to automate this process and get such return to compare if it is bigger than 1

That's is the code I'm trying to get running property:

@echo off    
set some_dir=C:\TEMP\    
for /f %%a in ('dir /b %some_dir%') do (
    set count=fsutil hardlink list %%a | find /c /v ""
    if %count% -EQU 1 del /Q %%a        
)

Would someone explain me how such attribution and comparison on %count% variable could be done, please?


Solution

  • There are some problems in your code:

    Here is the fixed script:

    @echo off
    setlocal EnableDelayedExpansion
    pushd "C:\TEMP\" || exit /B 1
    for /F "eol=| delims=" %%a in ('dir /B "."') do (
        for /F %%b in ('
            fsutil hardlink list "%%a" ^| find /C /V ""
        ') do (
            set "count=%%b"
        )
        if !count! EQU 1 del "%%a"
    )
    popd
    endlocal
    

    This can even be simplified:

    @echo off
    pushd "C:\TEMP\" || exit /B 1
    for /F "eol=| delims=" %%a in ('dir /B "."') do (
        for /F %%b in ('
            fsutil hardlink list "%%a" ^| find /C /V ""
        ') do (
            if %%b EQU 1 del "%%a"
        )
    )
    popd
    

    Since the inner for /F loop iterates always once only, we can move the if query inside, thus avoiding the definition of an auxiliary variable which is the only one we needed delayed expansion for.