Reputation: 1108
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 a convention I need to follow so PowerShell will do it for me automatically or I just need to parse it myself?
I'm looking for something similar to what bash
can do. If I set an environment variable such as:
MYARR = one two three
It'll be automatically interpreted by bash
as an array, so I can do:
for a in ${MYARR[@]} ; do
echo Element: $a
done
And that will return:
Element: one
Element: two
Element: three
Is there a way I can do the same in PowerShell?
Upvotes: 5
Views: 5886
Reputation: 200483
Split the value of the environment variable at whatever delimiter is used. 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: The PowerShell equivalent to bash
code like this
for a in ${MYARR[@]} ; do
echo Element: $a
done
would be
$MYARR -split '\s+' | ForEach-Object {
"Element: $_"
}
Use $env:MYARR
instead of $MYARR
if the variable is an actual environment variable instead of a PowerShell variable.
Upvotes: 8