Colyn1337
Colyn1337

Reputation: 1723

How do you redirect error output in Powershell when executing .net methods?

Why does powershell stream redirection not work with .Net calls? I'm specifically attempting the following:

[system.net.dns]::Resolve("bla") 2>$null

That should redirect error output to null, but it doesn't. There's tons of other ways to suppress the error, but why isn't redirection working? How do you redirect .net output?

Upvotes: 2

Views: 625

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

There's tons of other ways to suppress the error, but why isn't redirection working? How do you redirect .net output?

by placing your expression inside a PowerShell language construct, like a script-block:

&{ [System.Net.Dns]::Resolve('bla') } 2>$null

Output from the expression will still behave as expected:

PS> $IPHost = &{ [System.Net.DNS]::Resolve('bla') } 2>$null
PS> $IPHost -eq $null
True
PS> $IPHost = &{ [System.Net.DNS]::Resolve('www.stackoverflow.com') } 2>$null
PS> $IPHost

HostName          Aliases                 AddressList
--------          -------                 -----------
stackoverflow.com {www.stackoverflow.com} {104.16.35.249, 104.16.33.249, 104.16.37.249, 104.16.36.249...}

Upvotes: 4

Related Questions