-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
Created from discussion started on #3768.
Description
If you invoke PowerShell using the System.Management.Automation.PowerShell class, and if you handle the errors in the command you invoke by indicating that they should be ignored, S.M.A.PowerShell will still set HadErrors to true. Below are some code samples illustrating the problem.
Sample 1: C#/.NET invocation of PowerShell commands/scripts
$ps = [PowerShell]::Create()
$ps.AddCommand('Get-Service').AddParameter('Name','Invalid').AddParameter('ErrorAction',[System.Management.Automation.ActionPreference]::Ignore) > $null
$ps.Invoke()
$ps.HadErrors # returns $true; expectation is that this would return false since the command was configured to ignore errorsSample 1: Expected behavior
$ps.HadErrors should return $false
Sample 1: Actual behavior
$ps.HadErrors returns $true, even when $ps.Streams.Error does not contain any errors (because there were no errors!)
Sample 2: Direct command invocation in PowerShell
Get-Service -Name Invalid -ErrorAction Ignore
$? # returns $false; shouldn't this return $true?Sample 2: Expected behavior
$? should return $true
Sample 2: Actual behavior
$? returns $false, even though there were no errors because the invoker of the command instructed PowerShell to ignore the error that would otherwise have been raised because it is a benign error for them (and therefore, not an error)
Additional Details
In both of these cases, -ErrorAction Ignore is being used to tell PowerShell that the error is actually not an error as far as this invocation is concerned, and therefore it can be completely ignored. Why then, do both $? and
Environment data
PS C:\> $PSVersionTable
Name Value
---- -----
PSVersion 6.0.0-beta
PSEdition Core
GitCommitId v6.0.0-beta.5
OS Microsoft Windows 10.0.16251
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0