M365 powershell script uses a lot of memory

tarou chabi 731 Reputation points
2022-02-25T01:49:15.233+00:00

To export information to one file (csv), I know that I shouldn't refer to multiple DBs. Because that action crashes memory.
(Get-azureaduser, get-mailbox, get-mailboxstatistics etc.)

So, pelase teach me...
Please tell me how to improve.....

powershell version is the latest version.
Basically, how to write a script is as follows.
Invoke-Command -ScriptBlock {get-azureaduser |% {get- ........ $data += [pscustomobject]........... ]}}

Is there a best way to write or a service that should be stopped?
My environment can't install IDE, so I only use PowerShell ISE...........

Microsoft 365 Publishing
Microsoft 365 Publishing
Microsoft 365: Formerly Office 365, is a line of subscription services offered by Microsoft which adds to and includes the Microsoft Office product line. Publishing: The process of preparing, producing, and releasing content for distribution or sale.
595 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,362 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 31,571 Reputation points
    2022-02-25T03:13:23.587+00:00

    Try clearing variables that contain many objects when you are done with them. See if that makes a difference.

    Instead if this....

    get-azureaduser |% {get- ........}
    

    Do this...

    $AllUsers = get-azureaduser 
    foreach ($User in $AllUSers) {get- ........}
    Remove-Variable $AllUsers 
    

  2. Rich Matheisen 44,776 Reputation points
    2022-02-25T03:21:24.897+00:00

    Why are you using Invoke-Command?

    What is taking all the memory is the variable "$data". You're loading that with a PSCustomObject for each user.

    If you run the Get-AzureUser locally and use the pipeline things will probably work faster and use less memory Maybe something like this:

    get-azureaduser |  # sends one user object into the pipe at a time
        foreach-object{
            get- ........ 
            [pscustomobject]........... ]    # emits one PSCustomObject into the pipe at a time
        } | # continue with export-csv????