mhu
mhu

Reputation: 18051

$ErrorActionPreference ignored by New-SmbShare

Setting $ErrorActionPreference to Stop seems to be ignored by New-SmbShare in specific use cases:

This can be tested with the following script (test.ps1):

$ErrorActionPreference = "Stop" 
New-SmbShare -Name "Test" -Path "C:\NonExistingPath" 
Write-Host "Should not be reached"

The following call shows the error "The system cannot find the file specified", but also shows "Should never be reached", which is incorrect:

powershell.exe -Command .\test.ps1

The following call just throws the "The system cannot find the file specified" exception, which is correct:

powershell.exe -File .\test.ps1

Tested with:

Am I missing something here, or is this a PowerShell bug? I've already raised a uservoice, but maybe you have an explanation?

Upvotes: 1

Views: 308

Answers (1)

RiverHeart
RiverHeart

Reputation: 872

Odd you're the only person who seems to have noticed this issue.

I ran into this while calling one script from another in Powershell ISE. The script I was calling had $ErrorActionPreference = 'Stop' defined inside but was ignored.

I tried to find source code online and failing to do so I went to look at the module files in C:\Windows\System32\WindowsPowerShell\v1.0\Modules\SmbShare and discovered that New-SmbShare and family are CIM-based Cmdlet Definition XML (CDXML) cmdlets (that I'd not heard of before).

After looking into it, it seems to be an issue of variable scoping with "script" modules. The functions of the module can't see $ErrorActionPreference. Setting $Global:ErrorActionPreference = 'Stop' gives the correct behavior as does setting -ErrorAction Stop directly on the cmdlet.

I believe this thread represents the ongoing discussion of the issue.

Upvotes: 1

Related Questions