How To (Truly) Get Rid of Output
I was creating a script today, and I wanted to create a way for "errors" to just go away, for usability purposes, since other people will be using the script (in Cimitra) and won't have a PowerShell console.
I tried all kinds of stderr output methods that I saw at stackoverflow. Nope!
Then I found this beauty: Invoke-Expression
Here's how I created a command with no output.
Invoke-Expression "Get-ADUser -Identity 'Rob Storey'" 2> $null
The combination Invoke-Expression and redirection of stderr (2>) to $null is the ticket!
Another idea I got:
try{Get-ADUser -Identity 'Rob Storey'}catch{}
Nice and tidy!
MD/CTO @DP Technologies
2 年Great article but I think it should be 6 in place of 2 (6>$null) ;)
Administrateur systèmes et réseau indépendant
4 年If you really need no output (no errors, but no console too), you can use *> for your command according to Micrsoft About_redirection paper. It's more readable and debugging will be easier. Otherwise, you can use a "&" block with each output going trough $null except 1. For example: ---- new-item "jason" ; remove-item "jason" ; remove-item "jason" --> show file creation and trow an error at second remove-item: ItemNotFoundException. ---- & { new-item "jason" remove-item "jason" remove-item "jason" } 2>$null 3>$null 4>$null 5>$null 6>$null --> show only file creation. No red/yellow block are spotted in the output. You can send them back to a file instead of $null of course.
Splunk | Ex-DocuSign
4 年Nice work. This is why you are a scripting black belt.
Senior Cloud Security Engineer | Powershell enthusiast
4 年At first I was skeptical because I have always used the -SilentlyContinue parameter but seeing this made me try it out and I realized that "SilentlyContinue" isn't very silent at all. Really cool and it works great if a command works properly, and if not there's no output.