简体   繁体   中英

How can I get the value from a multidimentional array in Powershell

I am trying to pull some file paths from an array and use them to test if a folder is located on serval machines. I seem to get an error pulling the value from the 2-dimentional array and putting it in a variable.

Here is a striped down, very basic version of my script.

$PCS = "PC1","PC2","PC3"

$locations=     @("System32","Windows\System32"),
                 ("Public","Users\Public")


ForEach($PC in $PCS){



$i=0
Do
{

$fullpath = "\\" + $PC + "\C$\" + "$locations[$i][1]"
test-path $fullpath
$i++
}

While ($i -le ($locations.length-1) )





}

However when I use $fullpath to test if the folder is there, I get false, and upon further investigation, the actual value of $fullpath is:

 \\PC1\C$\System.Object[] System.Object[] System.Object[] System.Object[]

How can I get the value from the array, so I can use it as a filepath location?

$fullpath = "\\" + $PC + "\C$\" + "$($locations[$i][1])"

or

$fullpath = "\\" + $PC + "\C$\" + $locations[$i][1]

As arco444 points out, your code as posted seems incomplete, but I think your issue will be fixed by above.

Explanation

When you use "$locations[$i][1]" it only interprets $locations as a variable within the string. Using . to access properties or [] to access elements is interpreted as literal characters.

So in this case, you can use the second option (don't surround it in quotes) if the result of the lookup is already a string or can be coerced into one.

In the general sense, the first option uses $(...) which is a sub-expression. The ... can be any code, including entire pipelines and function calls and such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM