Search code examples
powershellnewman

Powershell Newman run pass --env-var as string


Trying to run via powershell postman collection as following:

newman run $collPath -e $envPath $envVarsStr

where $envVarsStr is a string containg N number dynamically generated --env-var e.g.

--env-var "Base.Url=someurl" --env-var "Password=somepass"

But newman seems to ignore all my --env-vars Using extra file is really not an option for me.

Any ideas on how to pass env-var string correctly?


Solution

  • You cannot pass what an external program should see as multiple arguments via a single string, because PowerShell passes a string as a single argument, irrespective of the string's content.

    Instead, use an array of strings, each element of which is passed as a separate argument.

    Thus, if you control the creation of the arguments, use the following:

    # Construct an array of arguments.
    # Note: No *embedded* " quoting necessary - PowerShell will double-quote on demand.
    $envVarsArgs = 
      '--env-var',
      'Base.Url=someurl', # use variables or expressions as needed
      '--env-var',
      'Password=somepass'
    

    and then call newman as follows:

    # Note: @envVarsArgs would work too.
    newman run $collPath -e $envPath $envVarsArgs
    

    If you're given a single string encoding multiple arguments, you can split it into an array of individual arguments yourself, which in the simplest case means:

    newman run $collPath -e $envPath (-split $envVarsStr -replace '"')
    

    However, this is not enough if any of the double-quoted substrings contain spaces (e.g. --env-var "Foo=bar none"), because the unary form of -split splits by whitespace only.


    If you need to deal with a given string whose embedded quoted arguments have spaces, you can use Invoke-Expression with an expandable (double-quoted) string ("...") in a pinch.

    • Note: Invoke-Expression (iex) should generally be the last resort, due to its security risks: only ever use it on input you either provided yourself or fully trust - see this answer.
    # !! See warning re Invoke-Expression above.
    Invoke-Expression @"
    newman run "$collPath" -e "$envPath" $envVarsStr
    "@
    

    Note the use of an expandable here-string (@"<newline>...<newline>"@), which simplifies embedded quoting (no need to escape the embedded " chars.)

    Another option is to use --%, the stop-parsing token, which, however, requires you to define an auxiliary environment variable that duplicates the value of your $envVarsStr variable:

    # Duplicate the string stored in $envVarsStr
    # in an aux. environment variable, so it can be used with --%
    $env:__aux = $envVarsStr
    
    # Note the use of --% and the cmd.exe-style environment-variable
    # reference:
    newman run $collPath -e $envPath --% %__aux%