1

So i have this code to output the filesize of a file, then replace the file and check the size again:

FOR %%A IN (%userprofile%\remove.me) DO (
    set size=%%~zA
)
pause
echo  before:%size%
copy %userprofile%\copy.me %userprofile%\remove.me
pause
FOR %%B IN (%userprofile%\remove.me) DO (
    set size2=%%~zB
)
pause
echo after:%size2%
pause
exit

It works perfectly fine, but when i try to check if the remove.me file exists before executing the code it wont output the filesizes:

if EXIST %userprofile%\remove.me (
FOR %%A IN (%userprofile%\remove.me) DO (
    set size=%%~zA
)
pause
echo  before:%size%
copy %userprofile%\copy.me %userprofile%\remove.me
pause
FOR %%B IN (%userprofile%\remove.me) DO (
    set size2=%%~zB
)
pause
echo after:%size2%
pause
exit
)

It will just say

before:

after:

without the filesizes. If i try to escape the brackets inside the code that gets run by the if-statement it will just return that (C:\Users\Myaccountname\remove.me) does not follow the syntax.

I can't figure out why this is happening and how to fix this. Don't judge me, im new to batch .-.

5
  • try with if EXIST "%userprofile%\remove.me" and FOR %%A IN ("%userprofile%\remove.me") Commented Dec 17, 2017 at 13:12
  • @npocmaka nothing changed :/ Commented Dec 17, 2017 at 13:20
  • Ooh you need delayed expansion Commented Dec 17, 2017 at 13:25
  • @npocmaka added a setlocal ENABLEDELAYEDEXPANSION at the start of the script, nothing changed. Commented Dec 17, 2017 at 13:28
  • check my answer. Commented Dec 17, 2017 at 13:29

1 Answer 1

1

You are changing and accessing value inside brackets context.So you need delayed expansion

setlocal enableDelayedExpansion
if EXIST "%userprofile%\remove.me" (
    FOR %%A IN ("%userprofile%\remove.me") DO (
        set size=%%~zA
    )
    pause
    echo  before:!size!
    copy "%userprofile%\copy.me" "%userprofile%\remove.me"
    pause
    FOR %%B IN ("%userprofile%\remove.me") DO (
        set size2=%%~zB
    )
    pause
    echo after:!size2!
    pause
    exit

)
Sign up to request clarification or add additional context in comments.

2 Comments

with this code the batch console instantly closes after running "setlocal enableDelayedExpansion" :/
@Temm - check it now. By accidend I've left the last closing bracket outside of the code block.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.