-2

I have the following array (as part of a script) which content looks like that:

Arr[0] ->  "$var1 = c:\Temp\aaa"  
Arr[1] ->  "$var2 = c:\Temp\abc"  
Arr[2] ->  "$var3 = c:\Temp\abc\xyz" 

I'd like to be able to use all array elements in my script.

Is it possible to load array elements to memory and use them in another script as defined variables?
Please note, variables are not part of the script. I build them into the array and it is stored there.

For example (running on another script):

Copy-Item -Path $var1 -Destination $var2
7
  • 1
    The code from your first snippet is not an array. Do you mean you have a couple variables defined in one script and want to use them in a second script? Commented Jul 18, 2017 at 13:57
  • 3
    Possible duplicate of Load variables from another powershell script Commented Jul 18, 2017 at 13:57
  • 1
    (?)Those are three separate variables, not an array. Commented Jul 18, 2017 at 14:01
  • 1
    What array? Where does that come from? Please provide a minimal reproducible example. Commented Jul 18, 2017 at 14:14
  • 1
    Perhaps look into utilizing hashtables? Commented Jul 18, 2017 at 14:41

1 Answer 1

0

You need to use single quotes for the entries in your array so that substitution is not used, and also wrap the paths in double quotes. Then you can use Invoke-Expression to set the variables from the entries:

$Arr = '$var1 = "c:\Temp\aaa"','$var2 = "c:\Temp\abc"','$var3 = "c:\Temp\abc\xyz"'
Invoke-Expression $Arr[0]

Example:

PS C:\> $Arr = '$var1 = "c:\Temp\aaa"','$var2 = "c:\Temp\abc"','$var3 = "c:\Temp\abc\xyz"'
PS C:\> "var1 = $var1"
var1 = 

PS C:\> Invoke-Expression $Arr[0]

PS C:\> "var1 = $var1"
var1 = c:\Temp\aaa

This is truly ugly code, and using a hashtable would be a much more elegant way of doing this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.