数组导致 'system.outofmemoryexception'

Array causing 'system.outofmemoryexception'

我是 运行 下面的脚本,它导致 'system.outofmemoryexception' 类型的异常被抛出

我认为这是由于@Results 数组增长超过了分配给windows shell 的2gb。是否有可能遍历结果的方法,或者我是否坚持分配更多内存(最终可能会很多......)?

$Path = "path to output" 

### Get all PF
$publicFolders = Get-PublicFolder "Public Folder Name" -Recurse -resultsize unlimited | Select-Object *


### Array to contain results
$results = @()

###Begin looping through each PF and grab each user/group with AccessRights to that folder
$final = ForEach($pf in $publicFolders){    
    $perms     = Get-PublicFolderClientPermission -Identity $pf.Identity | Where-Object {$_.User -notmatch "Default|Anonymous|S-X-X-XX"} 
    
    Foreach($perm in $perms){
        $temp = [PSCustomObject]@{
                    MailFolderName = $pf.Identity 
                    UserWithPerms  = $perm.User
                    AccessRights   = $perm | Select-Object -ExpandProperty AccessRights

                }
                $results += $temp
    }
                   
}

$final | Export-Csv $path -NoTypeInformation
                  

我是不是找错树了?

提前致谢。

使用 ForEach-Object cmdlet 而不是外循环的 foreach(){} 循环语句 - 这样您就可以立即开始将输出通过管道传输到 Export-Csv 而不是将其缓冲到数组中:

$publicFolders |ForEach-Object {
    $pf    = $_
    $perms = Get-PublicFolderClientPermission -Identity $pf.Identity | Where-Object {$_.User -notmatch "Default|Anonymous|S-X-X-XX"} 
    
    Foreach($perm in $perms){
        [PSCustomObject]@{
            MailFolderName = $pf.Identity 
            UserWithPerms  = $perm.User
            AccessRights   = $perm | Select-Object -ExpandProperty AccessRights
        }
    }                   
} | Export-Csv $path -NoTypeInformation

或者,在枚举每个文件夹的权限后将部分结果集刷新到文件中:

ForEach($pf in $publicFolders){    
    $perms     = Get-PublicFolderClientPermission -Identity $pf.Identity | Where-Object {$_.User -notmatch "Default|Anonymous|S-X-X-XX"} 
    
    $results = Foreach($perm in $perms){
        [PSCustomObject]@{
            MailFolderName = $pf.Identity 
            UserWithPerms  = $perm.User
            AccessRights   = $perm | Select-Object -ExpandProperty AccessRights
        }
    }

    # flush the buffer before moving to the next set of permissions
    $results |Export-Csv $path -NoTypeInformation -Append
}