I want a PowerShell one-liner that acts just like
[MyType]$var = My-Cmdlet -MyParam MyArg
...but suppresses stderr.
No, the following does not work:
([MyType]$var = My-Cmdlet -MyParam MyArg) 2>&1>$null
...as evidenced by the following example:
PS C:\> ($var = Get-installedModule "hooha") 2>&1>$null
PS C:\> $var.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True ErrorRecord System.Object
PS C:\> $var
Get-Package: No match was found for the specified search criteria and module names 'hooha'.
PS C:\> $var = Get-installedModule "hooha"
Get-Package: No match was found for the specified search criteria and module names 'hooha'.
PS C:\> $var.GetType()
InvalidOperation: You cannot call a method on a null-valued expression.
PS C:\>
Edit, for people who marked this as a duplicate of a not-equivalent question, and have left somewhat irrelevant comments: No, this is not the same question as Powershell: How can I stop errors from being displayed in a script? . I am trying to suppress both stderr and stdout for a command, and assign its returned value to a variable, in the same command line, and have the assignment behave the same way as an uncomplicated assignment including in the error case -- i.e. assign $null
if the command fails.