简体   繁体   中英

Function is not populating global variable

Here is the code snippet I am trying, the potential problem is the array which is declared outside of the function cannot be used in the testobjarray() function. It will display the count as zero in the function testobjarray() , but in addobjects() I am able to add the object to array and display the contents of the object.

$Global:objectorray = @()

function addobjects() {
  $object = New-Object PSObject
  $object | Add-Member -MemberType NoteProperty -Name "Name" -Value "Pradeep RN"
  $object | Add-Member -MemberType NoteProperty -Name "Age" -Value 24
  $object | Add-Member -MemberType NoteProperty -Name "Profession" -Value "Software Engineer"
  $objectorray += $object
  Write-Host "in addobjects function" $objectorray
}

function testobjarray() {
  Write-Host "in the another function" $objectorray.Count
}

addobjects
testobjarray

Avoid using globals if you do not have to. In this case you do not have to. Change the scope of $objectorray so that it is just in the script scope. Then use the return value of of your function to populate $objectorray . Note that I have only changed what little I needed to to make this example work.

$objectorray = @()

function addobjects() {
  $object = New-Object PSObject
  $object | Add-Member -MemberType NoteProperty -Name "Name" -Value "Pradeep RN"
  $object | Add-Member -MemberType NoteProperty -Name "Age" -Value 24
  $object | Add-Member -MemberType NoteProperty -Name "Profession" -Value "Software Engineer"
  $object
  Write-Host "in addobjects function" $object
}

function testobjarray() {
  Write-Host "in the another function" $objectorray.Count
}

$objectorray += addobjects
testobjarray

As mentioned in comments you need to have a look and understand scopes in PowerShell. The reference for this is about_scopes . gvee's answer shows how to use the global scope properly. Your issue happened because PowerShell allows variables with the same name in different scopes.

$objectorray.Count works inside the function testobjarray because of access to the parent scope.

You are not assigning values to the Global array in your addobjects() function

Change:

$objectorray+=$object

To:

$global:objectorray+=$object

And the same change in your testobjarray() function:

Write-Host "in the another function" $global:objectorray.Count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM