Change a collection variable dynamically with Newman

I would like to know if there is any way to change a collection variable in the cmd. I already found the --env-var “variable=value” command, but is there a similar thing for collection variables?

Hey @spaceflight-adminis5 :wave:

Welcome to the Postman Community! :postman:

There isn’t a direct flag to change the Collection Variable from the command line, like with the environment or globals.

It would work if you did something like this, not ideal as you’re changing things that you might not want too.

Add a placeholder variable to the Collection Variable like this:

And then use the --env-var flag in the Newman Command

newman run <collection> --env-var "fromNewman=Danny"

It would resolve that placeholder variable to the one added in the command:

1 Like

Thanks for the helping, i tried here and it works when the variable is used in the URL, but could you confirm me that this works when i use the variable in the pre/test-scripts? Because when i tried here i noticed that in the scripts didnt change, my example is like this:

const testVar = JSON.parse(pm.collectionVariables.get('testVariable'))

and the error is this:

Unexpected token 't' at 1:3 {{testVariable}}

Like if it did not change. Besides everything, thanks for the awnser, i will try to adapt the code here, but your response helped me a lot! :grin:

1 Like

I’m not sure what value you have set as testVariable on the command line and why that needs to be parse that way. :thinking:

Also, at that point it would just be the string {{testVariable}} because that’s what you have set as the variable. You’d need to use .replaceIn() to resolve that value.

Using my example:

let non_resolved_var = pm.collectionVariables.get("testing");
let resolved_var = pm.variables.replaceIn(pm.collectionVariables.get("testing"));

console.log(non_resolved_var)
console.log(resolved_var)

Would display this if logged out the console:

Ohh thanks, i think that this can resolve my problem! Just to explain, I use these collections variables to decide if some requests will be skipped or not, so i defined with “true” in the example, that’s why i have to use the JSON.parse

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.