Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing Powershell array index produces unexpected results when referenced with string

Tags:

powershell

I am trying to find out why the following occurs if you have

$arr = @("Filename1", "Filename2")
for($i =0; $i -le $arr.Length -1; $i++) {

   write-host ".\"$arr[$i]
   write-host ".\$arr[$i]"
   write-host $arr[$i] 
}

So taking just one loop through it produces:

".\ Filename1"
".\ Filename1 Filename2[0]"
"Filename1"

Just referencing the array[index] will produce the correct value, but if I concatenated with a string it places a space between the string and value. When placed within the string I assume it is dumping the entire contents because it is evaluating $array then evaluating $i ending up with

".\ filename1 filename2[index number]"

But if I assign the individual value to a separate variable and concatenate it with a string there is no space? Why is that:

Example:

 $name = $arr[$i]
 write-host ".\$name"

output = ".\filename1"

which is correct.

like image 762
pghtech Avatar asked Dec 21 '11 15:12

pghtech


2 Answers

You have to do:

write-host ".\$($arr[$i])"

so that it is evaluated as array indexing.

It would be the case with something like accessing properties of an object or key of hash etc within the string:

PS > $a = @{test="A";test2="B"}
PS > write-host "$a.test"
System.Collections.Hashtable.test
PS > write-host "$($a.test)"
A

Another alternative is to use string formatting, especially useful when you have lots of variables / objects in the string:

write-host (".\{0}" -f $arr[$i])
like image 195
manojlds Avatar answered Sep 25 '22 11:09

manojlds


Your code should look like this:

$arr = @("Filename1", "Filename2")
#for($i =0; $i -le $arr.Length-1; $i++) {
for($i =0; $i -le $arr.Length; $i++) {

   write-host ".\"$arr[$i]
   #write-host ".\$arr[$i]"
   write-host ".\$($arr[$i])"
   write-host $arr[$i] 
}
like image 29
Shay Levy Avatar answered Sep 23 '22 11:09

Shay Levy