Quastion about Try and Catch

Hi guys, trying to figure out if i understand the ErrorActionPreference variable,
Here is my script (this is my third tool that i’ve made (google helped me abit i admit…) and used the IT Department in our company, i’m honestly have to admit that i’m very proud :slight_smile: )

(The script is working so no need to fix any thing)

$ErrorActionPreference = 'stop'

try {

$companypcs =(Read-Host -Prompt "Please insert the computer names of the computers you want to retrieve the MAC Address, with comma separated
`n (you can combine IP's and pc's to: 192.168.2.1,pc-01 etc..)").split(',') | ForEach-Object {$_.trim()}



foreach ($pc in $companypcs) {


        Get-WmiObject -class Win32_NetworkAdapterConfiguration -ComputerName $pc |
        Where-Object IpEnabled -EQ "True" |
        Select-Object PSComputerName, description,MACAddress |
        Format-Table -AutoSize 
                           }

    }

catch {
write-host "`n"
Write-Warning  "Sorry, I can't reach to $pc, please check connectivity"

      }
write-host "`n"
Pause

My quastion is this:

Do I have to set the “$ErrorActionPreference” at the top of the script or I can make it a part of the “try” block as a parameter
like this (and make the “catch” action to work properly)?

foreach ($pc in companypcs) {


        Get-WmiObject -class Win32_NetworkAdapterConfiguration -ComputerName $pc |
        Where-Object IpEnabled -EQ "True" |
        Select-Object PSComputerName, description,MACAddress |
        Format-Table -AutoSize -ErrorAction Stop
                           }

    }

Hi Lev,

You should set $ErrorActionPreference to “Stop” when doing your WMI call using the ErrorAction parameter. The code you have now only stops, if your Format-Table command fails.

You could do something like:

foreach ($pc in $companypcs) {
try {
    Get-WmiObject -class Win32_NetworkAdapterConfiguration -ComputerName $pc -ErrorAction stop |
    Where-Object IpEnabled -EQ "True" |
    Select-Object PSComputerName, description,MACAddress |
    Format-Table -AutoSize
}
catch {
    Write-Warning  "Sorry, I can't reach to $pc, please check connectivity"
}
Hi Lev,

You should set $ErrorActionPreference to “Stop” when doing your WMI call using the ErrorAction parameter. The code you have now only stops, if your Format-Table command fails.

Now I see,
i just didn’t place it in the right place in my second example.

As the “Great” philosopher Ed Sheeran have said "Everyday discovering something brand new "

Thanks a lot Axel