Sqlcmd: Invalid argument - when trying to pass a variable to sqlcmd
In your command that works, you don't have an equal sign (=).  When you run the command that fails and look at the output, you should notice the equal sign disappears.  That's because that character needs to be escaped with a caret. (in my example below, notice the caret before the equal sign)

Try:

FOR /F "tokens=* USEBACKQ" %%F IN (`sqlcmd -S localhost -E -i "backup.sql" -v dbname^="test"`) DO (
    Echo %%F
)