Turn an environment variable into an array

I need to pass an array to a PowerShell subprocess and was wondering how I can turn an environment variable (string) into a PowerShell array. Is there some convention I have to follow so PowerShell will do it for me automatically or do I just have to parse it myself?

I am looking for something similar that can do bash

. If I set an environment variable like:

MYARR = one two three

      

It will automatically be interpreted as bash

an array, so I can do:

for a in ${MYARR[@]} ; do
    echo Element: $a
done

      

And this will return:

Element: one
Element: two
Element: three

      

Is there a way to do the same in PowerShell?

+3


source to share


1 answer


Split the environment variable value on any delimiter. Example:

PS C: \> $ env: Path
C: \ WINDOWS \ system32; C: \ WINDOWS; C: \ WINDOWS \ System32 \ Wbem; C: \ WINDOWS \ System32 \ WindowsPowerShell \ v1.0 \
PS C: \> $ a = $ env: Path -split ';' 
PS C: \> $ a
C: \ WINDOWS \ system32
C: \ WINDOWS
C: \ WINDOWS \ System32 \ Wbem
C: \ WINDOWS \ System32 \ WindowsPowerShell \ v1.0 \
PS C: \> $ a.GetType (). FullName
System.String []

Edit: PowerShell notation equivalent bash

like this



for a in ${MYARR[@]} ; do
    echo Element: $a
done

      

will be

$MYARR -split '\s+' | ForEach-Object {
    "Element: $_"
}

      

Use $env:MYARR

instead $MYARR

if the variable is an actual environment variable instead of a PowerShell variable.

+4


source







All Articles