diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 8f7e42dd9ae..3aec30c9e4c 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -1187,8 +1187,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession // // Build xpath for // - Hashtable suppresshash = hash[hashkey_supress_lc] as Hashtable; - if (suppresshash != null) + if (hash[hashkey_supress_lc] is Hashtable suppresshash) { xpathStringSuppress = BuildXPathFromHashTable(suppresshash); } @@ -1255,8 +1254,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession private static string HandleEventIdHashValue(object value) { StringBuilder ret = new(); - Array idsArray = value as Array; - if (idsArray != null) + if (value is Array idsArray) { ret.Append('('); for (int i = 0; i < idsArray.Length; i++) @@ -1285,8 +1283,7 @@ private static string HandleEventIdHashValue(object value) private static string HandleLevelHashValue(object value) { StringBuilder ret = new(); - Array levelsArray = value as Array; - if (levelsArray != null) + if (value is Array levelsArray) { ret.Append('('); for (int i = 0; i < levelsArray.Length; i++) @@ -1317,8 +1314,7 @@ private string HandleKeywordHashValue(object value) long keywordsMask = 0; long keywordLong = 0; - Array keywordArray = value as Array; - if (keywordArray != null) + if (value is Array keywordArray) { foreach (object keyword in keywordArray) { @@ -1473,8 +1469,7 @@ private string HandleEndTimeHashValue(object value, Hashtable hash) private static string HandleDataHashValue(object value) { StringBuilder ret = new(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1504,8 +1499,7 @@ private static string HandleDataHashValue(object value) private static string HandleNamedDataHashValue(string key, object value) { StringBuilder ret = new(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1752,8 +1746,7 @@ private void CheckHashTablesForNullValues() } else { - Array eltArray = value as Array; - if (eltArray != null) + if (value is Array eltArray) { foreach (object elt in eltArray) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 8da4d7f4c78..3e26b2e2e98 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -491,8 +491,7 @@ private IEnumerable GetSessionsToActAgainst(QueryBuilder queryBuilder) return this.Session; } - var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder; - if (sessionBoundQueryBuilder != null) + if (queryBuilder is ISessionBoundQueryBuilder sessionBoundQueryBuilder) { TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession(); if (sessionOfTheQueryBuilder != null) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 4ad6ecc9698..b4d4a7bbbe7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -98,16 +98,14 @@ internal static CimJobException CreateFromAnyException( Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); Dbg.Assert(inner != null, "Caller should verify inner != null"); - CimException cimException = inner as CimException; - if (cimException != null) + if (inner is CimException cimException) { return CreateFromCimException(jobDescription, jobContext, cimException); } string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); CimJobException cimJobException = new(message, inner); - var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (inner is IContainsErrorRecord containsErrorRecord) { cimJobException.InitializeErrorRecord( jobContext, @@ -356,8 +354,7 @@ internal bool IsTerminatingError { get { - var cimException = this.InnerException as CimException; - if ((cimException == null) || (cimException.ErrorData == null)) + if ((this.InnerException is not CimException cimException) || (cimException.ErrorData == null)) { return false; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index 9aa254212a6..9eaac2b3d7f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -66,8 +66,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m methodParameter.Value = dotNetValue; cmdletOutput.Add(methodParameter.Name, methodParameter); - var cimInstances = dotNetValue as CimInstance[]; - if (cimInstances != null) + if (dotNetValue is CimInstance[] cimInstances) { foreach (var instance in cimInstances) { @@ -75,8 +74,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m } } - var cimInstance = dotNetValue as CimInstance; - if (cimInstance != null) + if (dotNetValue is CimInstance cimInstance) { CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); } @@ -191,15 +189,13 @@ public override void OnNext(CimMethodResultBase item) this.ExceptionSafeWrapper( delegate { - var methodResult = item as CimMethodResult; - if (methodResult != null) + if (item is CimMethodResult methodResult) { this.OnNext(methodResult); return; } - var streamedResult = item as CimMethodStreamedResult; - if (streamedResult != null) + if (item is CimMethodStreamedResult streamedResult) { this.OnNext(streamedResult); return; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs index deb3a0ff103..6b716fa5501 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -53,8 +53,7 @@ private static int GetNumberOfSessions(InvocationInfo invocationInfo) int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1; foreach (object cmdletArgument in invocationInfo.BoundParameters.Values) { - CimInstance[] array = cmdletArgument as CimInstance[]; - if (array != null) + if (cmdletArgument is CimInstance[] array) { int numberOfSessionsAssociatedWithArgument = array .Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index 8a973c7af64..d787389e9f0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -623,8 +623,7 @@ internal void ReportJobFailure(IContainsErrorRecord exception) } else { - CimJobException cje = exception as CimJobException; - if ((cje != null) && (cje.IsTerminatingError)) + if ((exception is CimJobException cje) && (cje.IsTerminatingError)) { terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated); isThisTerminatingError = true; @@ -1013,8 +1012,7 @@ internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) internal static void AddShowComputerNameMarker(PSObject pso) { - PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo; - if (psShowComputerNameProperty != null) + if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty) { psShowComputerNameProperty.Value = true; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index 731007eb618..e8e4d46e075 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -36,8 +36,7 @@ public NotFoundError(string propertyName, object propertyValue, bool wildcardsEn if (wildcardsEnabled) { - var propertyValueAsString = propertyValue as string; - if ((propertyValueAsString != null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) + if ((propertyValue is string propertyValueAsString) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) { this.ErrorMessageGenerator = (queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className); @@ -466,8 +465,7 @@ protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object } else { - string expectedPropertyValueAsString = cimTypedExpectedPropertyValue as string; - if (expectedPropertyValueAsString != null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) + if (cimTypedExpectedPropertyValue is string expectedPropertyValueAsString && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) { return BehaviorOnNoMatch.SilentlyContinue; } @@ -504,8 +502,7 @@ private static bool NonWildcardEqual(string propertyName, object actualPropertyV actualPropertyValue = actualPropertyValue.ToString(); } - var expectedPropertyValueAsString = expectedPropertyValue as string; - if (expectedPropertyValueAsString != null) + if (expectedPropertyValue is string expectedPropertyValueAsString) { var actualPropertyValueAsString = (string)actualPropertyValue; return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 0253cee5e39..a9cba537a5a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -903,8 +903,7 @@ internal bool DoStartService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING) { exception = e; @@ -1020,9 +1019,7 @@ internal List DoStopService(ServiceController serviceControll } catch (InvalidOperationException e) { - Win32Exception eInner = - e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { exception = e; @@ -1117,8 +1114,7 @@ internal bool DoPauseService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { serviceNotRunning = true; @@ -1198,8 +1194,7 @@ internal bool DoResumeService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { serviceNotRunning = true; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index 8ddd95e6b82..29aa870fd1e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -560,9 +560,8 @@ private sealed class ValidateNotePropertyNameAttribute : ValidateArgumentsAttrib { protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { - string notePropertyName = arguments as string; PSMemberTypes memberType; - if (notePropertyName != null && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) + if (arguments is string notePropertyName && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) { switch (memberType) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index 2f1e5cca314..2c530a8ab93 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -502,9 +502,8 @@ protected override void BeginProcessing() MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]); WarningRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -553,16 +552,14 @@ private void WriteColumns(List mshParams) foreach (MshParameter p in mshParams) { COLTag.Append(" reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output); } @@ -447,8 +445,7 @@ private void HandlePipelineOutputDataReady(object sender, EventArgs e) private void HandlePipelineErrorDataReady(object sender, EventArgs e) { - PipelineReader reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error); } @@ -538,8 +535,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) // Only enable and disable the host's runspace if we are in process attach mode. if (_debugger is ServerRemoteDebugger) { - LocalRunspace localRunspace = runspace as LocalRunspace; - if ((localRunspace != null) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) + if ((runspace is LocalRunspace localRunspace) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) { try { @@ -552,8 +548,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) private static void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode) { - ServerRemoteDebugger remoteDebugger = debugger as ServerRemoteDebugger; - if (remoteDebugger != null) + if (debugger is ServerRemoteDebugger remoteDebugger) { remoteDebugger.LocalDebugMode = localMode; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 3db37f3528e..974188c2f74 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -33,15 +33,13 @@ internal override object GetValue(PSObject liveObject) // The live object has the liveObjectPropertyName property. object liveObjectValue = propertyInfo.Value; - ICollection collectionValue = liveObjectValue as ICollection; - if (collectionValue != null) + if (liveObjectValue is ICollection collectionValue) { liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); } else { - PSObject psObjectValue = liveObjectValue as PSObject; - if (psObjectValue != null) + if (liveObjectValue is PSObject psObjectValue) { // Since PSObject implements IComparable there is a need to verify if its BaseObject actually implements IComparable. if (psObjectValue.BaseObject is IComparable) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index 5f231780055..43e24e8b5b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -180,8 +180,7 @@ protected override void ProcessRecord() return; } - IDictionary dictionary = InputObject.BaseObject as IDictionary; - if (dictionary != null) + if (InputObject.BaseObject is IDictionary dictionary) { // Dictionaries should be enumerated through because the pipeline does not enumerate through them. foreach (DictionaryEntry entry in dictionary) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index d9de50ef52c..b406c2bc78c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -71,8 +71,7 @@ internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] t catch (TargetInvocationException ex) { // Verify if this is an error loading the System.Core dll. - FileNotFoundException fileNotFoundEx = ex.InnerException as FileNotFoundException; - if (fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) + if (ex.InnerException is FileNotFoundException fileNotFoundEx && fileNotFoundEx.FileName.Contains("System.Core")) { _parentCmdlet.ThrowTerminatingError( new ErrorRecord(new InvalidOperationException( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 25b18dfd80e..9213484d332 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -69,8 +69,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod if (token != null) { - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { // If Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName ??= fpt.expression.expressionValue; @@ -98,8 +97,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod } else { - TextToken tt = token as TextToken; - if (tt != null) + if (token is TextToken tt) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index 21c078648f2..2ba36f5faf2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -139,22 +139,19 @@ protected override void ProcessRecord() PSControl control; - var tableControlBody = definition.mainControl as TableControlBody; - if (tableControlBody != null) + if (definition.mainControl is TableControlBody tableControlBody) { control = new TableControl(tableControlBody, definition); } else { - var listControlBody = definition.mainControl as ListControlBody; - if (listControlBody != null) + if (definition.mainControl is ListControlBody listControlBody) { control = new ListControl(listControlBody, definition); } else { - var wideControlBody = definition.mainControl as WideControlBody; - if (wideControlBody != null) + if (definition.mainControl is WideControlBody wideControlBody) { control = new WideControl(wideControlBody, definition); if (writeOldWay) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index cfd380853b9..0b11af84200 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -230,8 +230,7 @@ protected override void ProcessRecord() { if (!Force) { - PSMethod memberAsPSMethod = member as PSMethod; - if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial)) + if ((member is PSMethod memberAsPSMethod) && (memberAsPSMethod.IsSpecial)) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 003b1bf1e3d..1631bb18762 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -726,8 +726,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti // // handle recognized types of exceptions first // - RemoteException remoteException = runtimeException as RemoteException; - if ((remoteException != null) && (remoteException.SerializedRemoteException != null)) + if ((runtimeException is RemoteException remoteException) && (remoteException.SerializedRemoteException != null)) { if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException))) { @@ -1575,8 +1574,7 @@ private PowerShell BuildPowerShellForGetFormatData() powerShell.AddParameter("TypeName", this.FormatTypeName); // For remote PS version 5.1 and greater, we need to include the new -PowerShellVersion parameter - RemoteRunspace remoteRunspace = Session.Runspace as RemoteRunspace; - if ((remoteRunspace != null) && (remoteRunspace.ServerVersion != null) && + if ((Session.Runspace is RemoteRunspace remoteRunspace) && (remoteRunspace.ServerVersion != null) && (remoteRunspace.ServerVersion >= new Version(5, 1))) { powerShell.AddParameter("PowerShellVersion", PSVersionInfo.PSVersion); @@ -1942,20 +1940,17 @@ internal ImplicitRemotingCodeGenerator( /// Connection URI associated with the remote runspace. private string GetConnectionString() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo connectionInfo) { return connectionInfo.ConnectionUri.ToString(); } - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return vmConnectionInfo.ComputerName; } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return containerConnectionInfo.ComputerName; } @@ -2244,8 +2239,7 @@ private string GenerateNewPSSessionOption() { StringBuilder result = new("& $script:NewPSSessionOption "); - RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; - if (runspaceConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is RunspaceConnectionInfo runspaceConnectionInfo) { result.Append(null, $"-Culture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())}' "); result.Append(null, $"-UICulture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())}' "); @@ -2256,8 +2250,7 @@ private string GenerateNewPSSessionOption() result.Append(null, $"-OperationTimeOut {runspaceConnectionInfo.OperationTimeout} "); } - WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo) { if (!wsmanConnectionInfo.UseCompression) { @@ -2522,8 +2515,7 @@ private string GenerateReimportingOfModules() private string GenerateNewRunspaceExpression() { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { string vmConfigurationName = vmConnectionInfo.ConfigurationName; return string.Format( @@ -2535,8 +2527,7 @@ private string GenerateNewRunspaceExpression() } else { - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { string containerConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; return string.Format( @@ -2578,19 +2569,16 @@ private string GenerateNewRunspaceExpression() /// private string GenerateConnectionStringForNewRunspace() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo == null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo connectionInfo) { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, VMIdParameterTemplate, CodeGeneration.EscapeSingleQuotedStringContent(vmConnectionInfo.VMGuid.ToString())); } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, ContainerIdParameterTemplate, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index c9f99c524fa..f08c3a64aec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -571,15 +571,13 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso } else { - IDictionary dict = obj as IDictionary; - if (dict != null) + if (obj is IDictionary dict) { rv = ProcessDictionary(dict, currentDepth, in context); } else { - IEnumerable enumerable = obj as IEnumerable; - if (enumerable != null) + if (obj is IEnumerable enumerable) { rv = ProcessEnumerable(enumerable, currentDepth, in context); } @@ -626,9 +624,8 @@ private static object AddPsProperties(object psObj, object obj, int depth, bool } bool wasDictionary = true; - IDictionary dict = obj as IDictionary; - if (dict == null) + if (obj is not IDictionary dict) { wasDictionary = false; dict = new Dictionary(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index 55e98260779..b75c6be8735 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -33,15 +33,11 @@ protected override void ProcessRecord() // so we create the DebugRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteDebug(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { DebugRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -81,15 +77,11 @@ protected override void ProcessRecord() // so we create the VerboseRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteVerbose(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { VerboseRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -129,15 +121,11 @@ protected override void ProcessRecord() // so we create the WarningRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteWarning(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { WarningRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -361,8 +349,7 @@ protected override void ProcessRecord() // 2005/07/14-913791 "write-error output is confusing and misleading" // set InvocationInfo to the script not the command - InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (myInvocation != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo myInvocation) { errorRecord.SetInvocationInfo(myInvocation); errorRecord.PreserveInvocationInfoOnce = true; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 2d2009e56bc..b9c4e2d454a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -51,9 +51,7 @@ private string ProcessObject(object o) { if (o != null) { - string s = o as string; - IEnumerable enumerable = null; - if (s != null) + if (o is string s) { // strings are IEnumerable, so we special case them if (s.Length > 0) @@ -61,7 +59,7 @@ private string ProcessObject(object o) return s; } } - else if ((enumerable = o as IEnumerable) != null) + else if (o is IEnumerable enumerable) { // unroll enumerables, including arrays. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 0cd748c6139..5b0af6473f4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -764,12 +764,10 @@ internal void Import() while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); - PSObject psObject = result as PSObject; - if (psObject != null) + if (result is PSObject psObject) { - ICollection c = psObject.BaseObject as ICollection; - if (c != null) + if (psObject.BaseObject is ICollection c) { foreach (object o in c) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index d73df70a97a..91cb0d46abc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -512,8 +512,7 @@ public override int Write(object obj, bool enumerateCollection) private static ErrorRecord ConvertToErrorRecord(object obj) { ErrorRecord result = null; - PSObject mshobj = obj as PSObject; - if (mshobj != null) + if (obj is PSObject mshobj) { object baseObject = mshobj.BaseObject; if (baseObject is not PSCustomObject) @@ -522,8 +521,7 @@ private static ErrorRecord ConvertToErrorRecord(object obj) } } - ErrorRecord errorRecordResult = obj as ErrorRecord; - if (errorRecordResult != null) + if (obj is ErrorRecord errorRecordResult) { result = errorRecordResult; }