This requires PowerShell v7
$sub=New-Object System.Collections.ArrayList
$destSubs = [System.Collections.ArrayList]::Synchronized($sub)
$allsubs=@(1,2,3,4,5)
$externalVariable=3
$AllSubs | Sort-Object -Property Name | ForEach-Object -Parallel {
# Any external variable reference needs to be localized using "using"
$localVariable = $using:externalVariable
($_ -lt $localVariable)
# Obtain reference to the bag with `using` modifier
$localCostsVariable = $using:destsubs
# Add to bag
$localCostsVariable.Add($_)
}
$destSubs
write-host ""
$sub
# NOTE: many AD object properties won't be visible inside of a parallel script block.
# Need to trigger PS AD adapter driver to populate the result set first
# https://stackoverflow.com/questions/75851412/powershell-foreach-object-parallel-not-all-properties-of-piped-in-object-are-a
#
$users = get-aduser -filter $filter -properties samAccountName,lastLogonTimestamp
#$users=$users|select * # uncomment this line in order to make below work
$users|foreach -parallel {
[do something with $_.samAccountName] # --> this works fine. samAccountName can be read properly
[do something with $_.lastLogonTimestamp] # --> this doesn't work. lastLogonTimestamp is always NULL regardless if it is actually populated
}