Skip to content

Commit

Permalink
Handle $ErrorActionPreference value (#4079)
Browse files Browse the repository at this point in the history
Handle $ErrorActionPreference in the same way as -ErrorAction cmdlet parameter is handled

Co-authored-by: Gautam Sheth <[email protected]>
  • Loading branch information
jackpoz and gautamdsheth authored Aug 9, 2024
1 parent 5a517b1 commit 0b8ae41
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
11 changes: 11 additions & 0 deletions src/Commands/Base/BasePSCmdlet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@ public bool ParameterSpecified(string parameterName)
return MyInvocation.BoundParameters.ContainsKey(parameterName);
}

protected string ErrorActionSetting
{
get
{
if (MyInvocation.BoundParameters.TryGetValue("ErrorAction", out object result))
return result.ToString() ?? "";
else
return SessionState.PSVariable.GetValue("ErrorActionPreference")?.ToString() ?? "";
}
}

protected virtual void ExecuteCmdlet()
{ }

Expand Down
2 changes: 1 addition & 1 deletion src/Commands/Base/ConnectOnline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ protected void Connect(ref CancellationToken cancellationToken)
}

// If the ErrorAction is not set to Stop, Ignore or SilentlyContinue throw an exception, otherwise just continue
if (!ParameterSpecified("ErrorAction") || !new [] { "stop", "ignore", "silentlycontinue" }.Contains(MyInvocation.BoundParameters["ErrorAction"].ToString().ToLowerInvariant()))
if (!new [] { "stop", "ignore", "silentlycontinue" }.Contains(ErrorActionSetting.ToLowerInvariant()))
{
throw new PSInvalidOperationException(errorMessage);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Commands/Base/PnPConnectedCmdlet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ protected override void ProcessRecord()
}

// If the ErrorAction is not set to Stop, Ignore or SilentlyContinue throw an exception, otherwise just continue
if (!ParameterSpecified("ErrorAction") || !(new [] { "stop", "ignore", "silentlycontinue" }.Contains(MyInvocation.BoundParameters["ErrorAction"].ToString().ToLowerInvariant())))
if (!(new [] { "stop", "ignore", "silentlycontinue" }.Contains(ErrorActionSetting.ToLowerInvariant())))
{
throw new PSInvalidOperationException(errorMessage);
}
Expand All @@ -107,7 +107,7 @@ protected override void ProcessRecord()
}

// With ErrorAction:Ignore, the $Error variable should not be populated with the error, otherwise it should
if (!ParameterSpecified("ErrorAction") || !new[] { "ignore" }.Contains(MyInvocation.BoundParameters["ErrorAction"].ToString().ToLowerInvariant()))
if (!new[] { "ignore" }.Contains(ErrorActionSetting.ToLowerInvariant()))
{
ex.Data["CorrelationId"] = Connection.Context.TraceCorrelationId;
ex.Data["TimeStampUtc"] = DateTime.UtcNow;
Expand Down

0 comments on commit 0b8ae41

Please sign in to comment.