0

I try to improve the speed of my Exchange Online script by using runspaces. My problem is the fact that the script-block could not call the Get-MailboxFolderStatistics because this cmdlet is provided by the Exchange Online module.

Therefore have I tried to use an delegate, see following sample code.

function getData() {
    param(
        [Parameter(Mandatory)]
        [int]
        $Number,

        [Parameter(Mandatory)]
        [Func[int, System.Object]] 
        $func_GetMailboxFolderStatistics
    )

    $result = $func_GetMailboxFolderStatistics.Invoke($Number)

    "test -> $result"
}


$runspacePool = [RunspaceFactory]::CreateRunspacePool(1, 20)

$runspacePool.Open()

$asyncJobs = @()
$n = 0

[Func[int, System.Object]] $func = { 
    param($num)  
    Start-Sleep 5
    "$num +++> $num" 
}


0..3 | ForEach-Object {

    $thread = [powershell]::Create()

    [void]$thread.AddScript($function:getData)
    [void]$thread.AddArgument($_)
    [void]$thread.AddArgument($func)
    $thread.RunspacePool = $runspacePool

    $asyncJobs += New-Object PSObject -Property @{
        RunNum = $n
        Pipe = $thread
        Result = $thread.BeginInvoke()
    }

    $n++
}


do {
    Write-Host "." -NoNewline
    Start-Sleep -Seconds 1
 } 
 while ( $asyncJobs.Result.IsCompleted -contains $false )

 Write-Host "All jobs completed!"


 $outcome = foreach($job in $asyncJobs){ $job.Pipe.EndInvoke($job.Result) }

 $outcome

The idea is that i call Get-MailboxFolderStatistics inside my delegate. It actually works, but it seems like my code is executed in sync- instead of async-mode one i call .Invoke

thuld
  • 680
  • 3
  • 10
  • 29
  • `[Func[int, System.Object]] $func = {` -> `[Func[int, System.Object]] $func = [scriptblock]::Create{` – user4003407 Apr 09 '18 at 17:52
  • @PetSerAI: this does not solve the problem, becuase "Get-MailboxFolderStatistics" is undefined when using a script-block: [Func[string, System.Object]] $func = [scriptblock]::Create({ param($smtp) Get-MailboxFolderStatistics -Identity $smtp -FolderScope Calendar }) – thuld Apr 09 '18 at 18:21

0 Answers0