Search code examples
variablespowershellscriptingwarnings

Saving Warnings to a variable in powershell


So what I'm trying to do is this

 $corruptAccounts = Get-Mailbox | select-string -pattern WARNING

The intent is to fill the variable $corruptAccounts with the warnings from Get-Mailbox. What actually happens is it processes the Get-Mailbox command, displaying the warnings, and puts nothing into the variable.

I'm new to powershell so I'm still trying to learn some of the basics.


Solution

  • Try this:

    Get-MailBox -WarningVariable wv
    $wv
    

    -WarningVariable is a common parameter available for all advanced functions and binary cmdlets.

    Here is a generic example:

    Function TestWarning {
        [CmdletBinding()]
        param (
    
        )
    
        Write-Warning "This is a warning"
    }
    
    PS C:\> TestWarning -WarningVariable wv
    WARNING: This is a warning
    
    PS C:\> $wv
    This is a warning