Hello Experts,
I need some guidance to move variables from Environment to collections how can i do it?
Hello Experts,
I need some guidance to move variables from Environment to collections how can i do it?
Hey @adoddam
Welcome to the Postman Community!
I guess the first thing I would ask is why? Is there a specific reason to make those Environment scoped variables, avaible at the Collection level?
You could do this a number of different ways, doing it manually 1 by 1 would be the slowest method
You can use a function like this in the Pre-request script to copy the variables in your selected Environment and then replicate that in the Collections:
(function moveEnvVarsToCollectionVars() {
// Get all environment variables
let envVars = pm.environment.toObject();
console.log("Environment Variables:", envVars);
let updatedVarsCount = 0;
for (let key in envVars) {
if (!pm.collectionVariables.has(key)) {
// Set the variable in the collection if it doesn't already exist
pm.collectionVariables.set(key, envVars[key]);
console.log(`Moved variable: ${key} = ${envVars[key]} to collection variables.`);
updatedVarsCount++;
}
}
if (updatedVarsCount > 0) {
console.log(`${updatedVarsCount} variables moved to collection variables.`);
} else {
console.log("No new variables to move to collection variables.");
}
})();
This will grab all the Environment variables as an object and store them in a local variable. Then it will loop through the Collection variables to check that it doesn’t contain the same key, if it doesn’t, it will create a new Collection Variable.
This method would only copy the data of the Current Value so if you had an environment variable that has data only in the Initial Value, it would only move the Variable Key across.
Another method would be to use the Postman API and the routes (Get an environment and Update a Collection) available and write a script to copy those Environment values to the Collection - This method would use the Initial Value though as that’s the value that is synced.
Cheers @danny-dainton ,
I can use that code to work around the current limitations of sharing collections with users with a viewer role.
We prefer to use Environment variables as they are way more flexible and you can hide sensitive data.
Thanks again,