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.
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.
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.
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..
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
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