This is a simple and very basic PowerShell trick, but it can be pretty confusing for someone who is just starting out or uses PowerShell only now and then.
In PowerShell there are so-called “terminating errors” and “non-terminating errors”. As their names suggest, some stop the running script when they happen and the others don’t, they just report the error. So far I’ve described the default behavior. Whether an error is “terminating” or “non-terminating” isn’t something we can control, and that can cause the odd headache now and then.
Today I was working on a script that did an Import-Module and then ran a series of other scripts, some related to the module I was trying to import and others not. To simplify, let’s imagine I had code like this:
Import-Module NombreDeModuloQueNoExiste
Write-Host "Here I would run code NOT related to the module"
Write-Host "Here I would run code related to the module"
In this case the module I was trying to import turned out not to exist on my machine, so when I tried the Import-Module, I got an error telling me the module couldn’t be found. The problem is that PowerShell’s behavior wasn’t exactly what I wanted:

As you can see, the result was that I got the error, but the two lines of code after it were also being run, and that wasn’t the behavior I wanted. Since I’m not working with PowerShell all day, this kind of thing sometimes happens to me and throws me off a bit, but in this case I remembered this kind of problem and could sort it out quickly.
It turns out PowerShell has a variable called $ErrorActionPreference that determines the behavior to follow for “non-terminating” errors. The default value is Continue, so it’s something like Visual Basic’s On Error Resume Next.
The possible values for this variable are Stop, Inquire, Continue, Suspend and SilentlyContinue, but I normally only use Stop and Continue.
So, by setting the variable before running Import-Module, you can get the behavior you want.
$ErrorActionPreference = "Stop"
Import-Module NombreDeModuloQueNoExiste
Write-Host "This code never gets called"
Personally, I’m in favor of setting the value to Stop at the beginning of scripts, together with Set-StrictMode, and then changing it for specific cases if I need to.