Sqlcmd: Invalid argument - when trying to pass a variable to sqlcmd I'm trying to use a DOS command prompt on Server 2012R2 to run a batch with the following in it.  I want to run a SQL command (sqlcmd) and return the results to the command window.

This is what I'm currently trying but sqlcmd keeps throwing back Sqlcmd: 'test': Invalid argument. Enter '-?' for help.20:56:08.

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


However if I try it without params/variables it works perfectly!

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


Does anyone know a way around getting the variables passed to my sql query using sqlcmd, DOS CMD, as well as a FOR /F loop such as in my first example?
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
)