Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell array scope; why is my array empty?

I want to have an array and add elements to it from different functions in my script. My example below illustrates where I might be misunderstanding something regarding scope. My understanding currently is that if an array is defined outside the function, and then elements are added inside the function, those elements should be available outside the function.

Function ListRunningServices
{
    $services+= Get-Service | ?{$_.Status -eq "Running"} | sort Name | select Name;
}

$services = @();
ListRunningServices;
$services;

What am I missing here? Perhaps my style is completely wrong.

like image 218
Mark Allison Avatar asked Dec 11 '13 13:12

Mark Allison


People also ask

How do you initialize an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

Do PowerShell arrays start at 0 or 1?

Arrays in PowerShell can contain one or more items. An item can be a string, an integer, an object, or even another array, and one array can contain any combination of these items. Each of these items has an index, which always starts (sometimes confusingly) at 0.

How do I read an array in PowerShell?

Retrieve items from an Array To retrieve an element, specify its number, PowerShell automatically numbers the array elements starting at 0. Think of the index number as being an offset from the staring element. so $myArray[1,2+4..


1 Answers

You can solve this with global variables, but using globals is genereally considered bad practice. If you use a generic collection type, like arraylist, instead of an array then you have an add() method that will update the collection in a parent scope without needing to explicitly scope it in the function:

Function ListRunningServices
{
    Get-Service | ?{$_.Status -eq "Running"} | sort Name | select Name |
     ForEach-Object {$services.add($_)}
}

$services = New-Object collections.arraylist
ListRunningServices
$services
like image 172
mjolinor Avatar answered Sep 18 '22 17:09

mjolinor