Amit
Amit

Reputation: 3478

How to declare and get array value

I am new to Powershell, first time using it.

I have declared an array and use array value but using below code, I am not able to retrieve the array value...Any idea what I am missing here?

Just FYI.. I am executing script in ADOBE ILLUSTRATOR and for testing I am using 3 here in condition (for loop)... will use $array later

$array = "a.jpg","b.jpg","c.jpg";

for ($i=1; $i-le=3; $i++)  
{
    $.writeln("This is line number " + $array[$i]);
    var targetFileName =  $array[$i]+'.png';
    $.writeln(targetFileName);
}

I tried $array[$i].toString() as well but still not getting values... I am getting 0

Any help is appreciated and thanks in advance to all for your help

Upvotes: 0

Views: 536

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

for ($i=1; $i-le=3; $i++)

The condition in the above line doesn't have a valid comparison operator. Change that to

for ($i=1; $i -le 3; $i++)

if you want the loop to terminate after 3 cycles.


$.writeln("This is line number " + $array[$i]);
var targetFileName = $array[$i]+'.png';
$.writeln(targetFileName);

This is not valid PowerShell. Looks more like JavaScript to me. In PowerShell it should probably look like this:

Write-Output "This is line number $i"
$targetFileName = $array[$i] + '.png'
Write-Output $targetFileName

or shorter

"This is line number $i"
$array[$i] + '.png'

Note that PowerShell arrays are zero-based, so the last iteration ($array[3]) will return $null instead of an element from the array. If you want to iterate over the elements of the array you should change your loop to this:

for ($i=0; $i -lt $array.Length; $i++) {
  "This is line number $($i+1)"
  $array[$i] + '.png'
}

or (better) pipe your array into a foreach loop:

$i = 0
$array | % {
  "This is line number " + ++$i
  $_ + '.png'
}

Upvotes: 3

Related Questions