Aloehart
Aloehart

Reputation: 337

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.

Upvotes: 2

Views: 6370

Answers (3)

user2347380
user2347380

Reputation: 115

$buf = Get-Mailbox 2>&1 | Out-String

Will add warnings to $buf at front

Upvotes: 0

SebaOPL
SebaOPL

Reputation: 3

You can try this:

[System.Collections.ArrayList]$var = @();
Get-Mailbox -WarningVariable +var -ResultSize unlimited

Upvotes: 0

ravikanth
ravikanth

Reputation: 25800

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

Upvotes: 5

Related Questions