Forum Discussion
Catching errors
Trying to wrap my head around this. Let's say I execute the following, WITHOUT defining the variables:
try { New-SmbShare -Description "$SmbShareDescription" -FullAccess 'everyone' -Name "$SmbShareName" -Path "$SmbSharePath" | Out-Null } catch { Write-Warning $_ }
The code in the try block will fail with a ParameterBindingValidationException, and the catch block will execute, as expected.
Now, if I define the variables first and execute, the try code executes and succeeds, no need for the catch code to run. If I run it again, with the same values, the try code fails with a CimException ("the name has already been shared"), as expected, but throws a visible exception error, and the catch block does NOT execute.
Obviously I can set ErrorAction to SilentlyContinue to suppress the visible exception error, but I'm curious why the catch block doesn't execute?
Yup, you need to throw a terminating error, which in this case can be done by adding the -ErrorAction Stop parameter.
[10:05:49]# try { New-SmbShare test -Path \ } catch {"aaa"} New-SmbShare : The filename, directory name, or volume label syntax is incorrect. At line:1 char:7 + try { New-SmbShare test -Path \ } catch {"aaa"} + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (MSFT_SMBShare:ROOT/Microsoft/Windows/SMB/MSFT_SMBShare) [New-SmbShare], CimException + FullyQualifiedErrorId : Windows System Error 123,New-SmbShare [10:06:00]# try { New-SmbShare test -Path \ -ErrorAction Stop} catch {"aaa"} aaa
- BlackVBrass Contributor
It only runs on a terminating error.
Is share already exists a terminating error, possibly notYup, you need to throw a terminating error, which in this case can be done by adding the -ErrorAction Stop parameter.
[10:05:49]# try { New-SmbShare test -Path \ } catch {"aaa"} New-SmbShare : The filename, directory name, or volume label syntax is incorrect. At line:1 char:7 + try { New-SmbShare test -Path \ } catch {"aaa"} + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (MSFT_SMBShare:ROOT/Microsoft/Windows/SMB/MSFT_SMBShare) [New-SmbShare], CimException + FullyQualifiedErrorId : Windows System Error 123,New-SmbShare [10:06:00]# try { New-SmbShare test -Path \ -ErrorAction Stop} catch {"aaa"} aaa
- Thanks. I've looked around to see how to tell if an error will be terminating, and not finding a reference. Anyone have info?