Joost
Joost

Reputation: 1216

Cannot capture warning output generated by Write-Warning (into a WarningVariable)

Consider this line:

Write-Warning "test" -wv +t

If I run this and verify the contents of $t afterwards, I get this:

Message   InvocationInfo                             PipelineIterationInfo
-------   --------------                             ---------------------
test      System.Management.Automation.Invocation... {0, 0, 0}

This is what I would indeed expect.

Now, if I turn this line of code into a script, like so:

function WarnTest {
    [CmdletBinding()]
    param()
    Write-Warning "test" 
}

and then make a simple function call like this:

WarnTest -wv +q
$q

$q remains empty. I'm a bit baffled by this - I was under the impression that [CmdletBinding()] made sure that any write-warning in the function would be sent to the warning stream, and could therefore be caught with the -WarningVariable parameter.

Can anyone shed a light on this?

The purpose for which I need this is a function to test which servers are online (and send these to the standard output) where I can also capture the warnings of those which are offline.

Upvotes: 1

Views: 1158

Answers (1)

Keith Hill
Keith Hill

Reputation: 201632

Try this instead on v2:

function WarnTest {
    [CmdletBinding()]
    param()
    $pscmdlet.WriteWarning("test")
}

Your original function seems to work correctly on PowerShell v3.

Upvotes: 2

Related Questions