How to do it...

  1. Let us run a command that would result in an error. For now, let us not focus on the syntax of the command; our only goal for now is to generate an error. At the first line of the script window, type in:
Get-ChildItem /home/ram/random-directory
Write-Host "Hello world!"
  1. Run the two-liner script using the F5 key.

PowerShell is prompt to show an error. It also displays the Hello world! string.

  1. Now, let us set the error action preference, using the variable, ErrorActionPreference. We know there's such a variable from the previous recipe. First, though, restart PowerShell. The easiest way is to click on the little bin icon at the top of the Integrated Console window. When VS Code asks if you would like to restart the session, click on Yes.
  1. Now, set the ErrorActionPreference variable. At the PowerShell Integrated Console, enter:
PS> Set-Variable ErrorActionPreference SilentlyContinue
  1. Run the two-liner script again.

There is no error this time. And we see Hello world! at the console.

If you do not want the entire script appear at the prompt, make the first line of the script, Clear-Host; this would clear the screen before showing the output.
  1. What if you were to check whether an error was generated at all? We check the value of the automatic variable, Error.
PS> Get-Variable Error
  1. The Value column contains some text. Let's select and expand the contents of Value.
Get-Variable Error | Select-Object -ExpandProperty Value

The output text is the same as what we received before we set the error action preference.

You can also simply call the Error variable to read all the errors that occurred in the current session.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.125.171