Setting a variable value from a collection level script

How do I set a variable from a postman script at the collection level, or from a package script? Using the postman app.

The

pm.environment.set('FOO', 'BAR-ENV');
pm.globals.set('FOO', 'BAR-GLOBALS');

Adding this to a collection level script has no impact, and the values do not show up anywhere? Is this possible? Or is there any work around? Currently right now I have to return the data to the request script and then set the variable.

Hey @tim-cartwright :wave:

Welcome to the Postman Community! :postman:

You would need to use the pm.collectionVariables.set() syntax for those to go to the Collection scoped variable section.


For your script, if you don’t have an active environment set, that wouldn’t go anywhere as it wouldn’t have anywhere to “store” it.

For the Global variables - You could see them by either opening the All variables menu from the top right icon:

Or opening the Environments section from the let sidebar and selecting Globals

I do have an environment set. It just does not work. No error. No value change. Nothing. I tried pm.collectionVariables.set with the same result.

So apparently this issue only arises when the variable is set from a function created at the collection level. If the script sets the variables outside of a function it works.

I have created an example repro workspace:

https://www.postman.com/svapi4/testing/request/40551444-f2662dca-35ac-459d-b7e5-32dba3e0f605?tab=body

Hey @tim-cartwright,

Your original question is missing a lot of contextual detail that’s actually quite relevant here. You didn’t mention that you had created a global utility function and you were creating variables within that, by calling it in the request script.

Those work slightly differently and is an older method of reusing functions within scripts.

In order to get your function working with the pm.* functions, you need to add pm as an argument:

SetInfo: function(pm)

This also needs to be in the function at the script level:

utils.SetInfo(pm);

I would recommend taking a look at the Package Library feature.

People still use those global functions and have no issues but the Package Library allows the whole team to use your scripts within any Workspace.

1 Like