0

I have an array of users. But when I try to access the array in a function it isn't complete.

$script:users = @()

Function check-user{
  foreach($user in $users){
    write-host $user
  }
}

foreach($img in $newImages){
    $users += $username
}

If I check $users it has 2 objects. But when I debug the code and check the function it can only see 1 of those two objects. How do I amend this so PowerShell can see both objects?

4
  • 1
    Where does $newImages and $username come from? Commented Apr 12, 2021 at 9:47
  • @MathiasR.Jessen I just simplified the code for the example. $newImages comes from another away and $username is a variable that is created in the last foreach Commented Apr 12, 2021 at 9:50
  • So if you have 10 items in $newImages, you want 10 copies of $username in $users? It's a bit unclear what is supposed to happen here. Please also review this help center article about how to put together simplified examples Commented Apr 12, 2021 at 9:53
  • Yes that’s correct. When it loops in the function it only seems to be accessing the first object. Commented Apr 12, 2021 at 9:55

1 Answer 1

2

In your example, you used a scope modifier $Script:users = @() but after that, you don't use the $Script: scope to reference that variable. It could happen that you would have another $users variable but that's unclear from your example.

What you should do is either

  • be consistent about the scope modifier, i.e. use $Script: everywhere
  • Use a parameter in your function and pass the $users variable to it
Function check-user{
  [CmdletBinding()] 
  param(
     [Parameter()]
     $Users
  )
  foreach($user in $Users){
    write-host $user
  }
}

# and use it like this
check-user -Users $users

If you are not comfortable with PowerShell, I think you shouldn't be using scopes. Define variables like this: $foo = bar.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.