I believe this should stop, not continue. Why am I mistaken?
$ErrorActionPreference = "Stop"
$VerbosePreference = "continue"
#creating a file for first run only
if(-Not (Test-Path test.txt))
{
new-item test.txt -Verbose
}
#create the same file
new-item test.txt -Verbose
Write-output 'This will never output because of the error above... or will it'
new-item test.txt
Write-output 'This will ALSO never output because of the error above'
The default value of the VerbosePreference variable is SilentlyContinue. This will be used in place of the ErrorActionPreference variable when the -verbose switch is used, unless you specify the ErrorAction on the command.
This will work the way you think it should
$ErrorActionPreference = "Stop"
$VerbosePreference = "continue"
#creating a file for first run only
if(-Not (Test-Path test.txt))
{
new-item test.txt -Verbose
}
#create the same file
new-item test.txt -Verbose -ErrorAction Stop
Write-output 'This will never output because of the error above... or will it'
new-item test.txt
Write-output 'This will ALSO never output because of the error above'
It depends on how the command is coded internally. When -Verbose is enabled, it’s possible that the command - internally - isn’t following a code path that can throw an exception. That’s not a good command design, and it isn’t a universal shell behavior. If you’ve verified the behavior, I’d suggest opening a ticket on UserVoice for the PowerShell team. Or, since New-Item is part of PowerShell Core, you might review the code on the PowerShell Core GitHub, and see if you can find the problem and propose a fix.