I encountered some issue in converting my existing vbs script to PowerShell script. I have illustrate here with some dummy codes instead of my original code. In example 1, I only have 1 set of elements in the array, upon return the array variable to the function, it will only display P.
However in example 2, where I have 2 set of elements in the array, upon return the array variable to the function, it will display the elements properly.
If you print the array inside the function in example 1 and 2. There isn't any issue in getting the results.
I have googled and not able to find any solution to it. Many thanks in advance for the kind help.
Example 1:
function testArray {
$array1 = @()
$array1 += ,@("Apple","Banana")
return $array1
}
$array2 = testArray
Write-Host $array2[0][1]
Result is "P".
Example 2:
function testArray {
$array1 = @()
$array1 += ,@("Apple","Banana")
$array1 += ,@("Orange","Pineapple")
return $array1
}
$array2 = testArray
Write-Host $array2[0][0]
Result is "Apple".
A whole array cannot be provided as a parameter to a function in C++.
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
We can also make a function return an array by declaring it inside a structure in C++. Let us see how. Here, note that we have declared the array arr inside the structure demo . And this time the function has a return type of the structure itself and return demo_mem (structure variable) instead of the array.
We can have a pointer to the two-dimensional arrays in C++. We can pass a 2D array to a function by specifying the size of columns of a 2D array. We can also pass a pointer to an array. We can also define a pointer as a pointer to pass in a function.
PowerShell unrolls arrays returned from a function. Prepend the returned array with the comma operator (,
, unary array construction operator) to wrap it in another array, which is unrolled on return, leaving the nested array intact.
function testArray {
$array1 = @()
$array1 += ,@("Apple","Banana")
return ,$array1
}
when you declare single line array like
$array1 = "Apple","Banana"
when you call :
$array1[0][1]
this will happen :
this code
function testArray {
$array1 = @()
$array1 += ,@("Apple","Banana")
return $array1
}
$array2 = testArray
Write-Host $array2[0][1]
exact the same of this:
$array1 = "Apple","Banana"
but when you declare 2 row of array like :
function testArray {
$array1 = @()
$array1 += ,@("Apple","Banana")
$array1 += ,@("Orange","Pineapple")
return $array1
}
$array2 = testArray
Write-Host $array2[0][0]
this will happen :
if you need apple in your first code just call array[0] not array[0][0]. array[0][0] return char for you.
sorry for my bad english i hope you understand
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With