To complement Mathias' helpful answer:
You can alternatively use a 3>
redirection, namely 3>$null
to silence warnings:
... | Stop-Service 3>$null
PowerShell's output streams are numbered (with streams 1
(success), and 2
(error) corresponding to the system-level stdout and stderr streams when communicating with the outside world), and 3
refers to the warning stream, which can be targeted >
, the redirection operator; redirecting to $null
effectively discards the targeted stream's output, if any.
This works with any of the output streams (>
being implicitly the same as 1>
, i.e. targeting the success output stream), and PowerShell even offers redirection *>
to redirect all streams.
Targeting a file name or path rather than $null
(quietly) saves the stream output to a plain-text file with the same formatting you would see in the terminal, except that stream-specific prefixes such as "WARNING: " are omitted.
Using something like 3>
has one advantage over using the common -WarningAction
parameter:
Only cmdlets and advanced functions and scripts support -WarningAction
, whereas 3>$null
is also effective with simple functions and scripts that use Write-Warning
.
By contrast, the $WarningPreference
preference variable is equally effective for all PowerShell commands.
However, preference variables, notably the $ErrorActionPreference
preference variable, do not apply to external programs: streams 3
and higher do not apply to external programs, and an external program's stderr output is (sensibly) not considered error output by default (though such output can be targeted as stream number 2
); to silence an external program's stderr output, you must use 2>$null
As an aside: Additional warning-related functionality that is also only supported by cmdlets and advanced functions/scripts is the ability to collect warnings in a variable, via the common -WarningVariable
parameter; the closest approximation of this functionality with a 3>
redirection is to target a file to write the warnings to (which would necessitate displaying that file's content after the fact to also print the warnings).
While technically distinct, a stream-targeted redirection such as 3>
should behave the same as the equivalent -WarningAction SilentlyContinue
parameter, and - with the exception of 2>
/ -ErrorAction
- equally applies to -*Action Ignore
.
-ErrorAction Ignore
-like 2>$null
/ -ErrorAction SilentlyContinue
- suppresses error-stream output, but - unlike the latter - additionally prevents the (non-terminating) errors that occur from getting recorded in the automatic $Error
variable, which is a session-wide collection of errors that have occurred so far.
- In rare edge cases (for reasons unknown to me),
-ErrorAction SilentlyContinue
can fail to record $Error
, whereas 2>$null
still does - see this answer for an example.