Question:
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.
1 2 3 4 5 6 7 8 9 |
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.
Answer:
The $services
within the function block is scoped to the function. You can do something like the following instead:
1 2 3 4 5 6 7 |
Function ListRunningServices { Get-Service | ?{$_.Status -eq "Running"} | sort Name | select Name } $services = ListRunningServices $services |
Else, you may explicitly use
global:
to alter the scope:
1 2 3 4 5 6 7 8 |
Function ListRunningServices { $global:services = Get-Service | ?{$_.Status -eq "Running"} | sort Name | select Name } $services = @() ListRunningServices $services |