protected override void ProcessRecord() { // Validate parameters ValidateComputerNames(); object[] flags = new object[] { 2, 0 }; if (Force) flags[0] = 6; #if CORECLR if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase)) { #else // TODO:CORECLR Revisit if or when jobs are supported if (ParameterSetName.Equals(AsJobParameterSet, StringComparison.OrdinalIgnoreCase)) { string[] names = _validatedComputerNames.ToArray(); string strComputers = ComputerWMIHelper.GetMachineNames(names); if (!ShouldProcess(strComputers)) return; InvokeWmiMethod WmiInvokeCmd = new InvokeWmiMethod(); WmiInvokeCmd.Path = ComputerWMIHelper.WMI_Class_OperatingSystem + "=@"; WmiInvokeCmd.ComputerName = names; WmiInvokeCmd.Authentication = DcomAuthentication; WmiInvokeCmd.Impersonation = Impersonation; WmiInvokeCmd.Credential = Credential; WmiInvokeCmd.ThrottleLimit = ThrottleLimit; WmiInvokeCmd.Name = "Win32Shutdown"; WmiInvokeCmd.EnableAllPrivileges = SwitchParameter.Present; WmiInvokeCmd.ArgumentList = flags; PSWmiJob wmiJob = new PSWmiJob(WmiInvokeCmd, names, ThrottleLimit, Job.GetCommandTextFromInvocationInfo(this.MyInvocation)); this.JobRepository.Add(wmiJob); WriteObject(wmiJob); } else if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase)) { // CoreCLR does not support DCOM, so there is no point checking // it here. It was already validated in BeginProcessing(). bool dcomInUse = Protocol.Equals(ComputerWMIHelper.DcomProtocol, StringComparison.OrdinalIgnoreCase); ConnectionOptions options = ComputerWMIHelper.GetConnectionOptions(this.DcomAuthentication, this.Impersonation, this.Credential); #endif if (Wait && _timeout != 0) { _validatedComputerNames = #if !CORECLR dcomInUse ? SetUpComputerInfoUsingDcom(_validatedComputerNames, options) : #endif SetUpComputerInfoUsingWsman(_validatedComputerNames, _cancel.Token); } foreach (string computer in _validatedComputerNames) { bool isLocal = false; string compname; if (computer.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) { compname = _shortLocalMachineName; isLocal = true; #if !CORECLR if (dcomInUse) { // The local machine will always at the end of the list. If the current target // computer is the local machine, it's safe to set Username and Password to null. options.Username = null; options.SecurePassword = null; } #endif } else { compname = computer; } // Generate target and action strings string action = StringUtil.Format( ComputerResources.RestartComputerAction, isLocal ? ComputerResources.LocalShutdownPrivilege : ComputerResources.RemoteShutdownPrivilege); string target = isLocal ? StringUtil.Format(ComputerResources.DoubleComputerName, "localhost", compname) : compname; if (!ShouldProcess(target, action)) { continue; } bool isSuccess = #if !CORECLR dcomInUse ? RestartOneComputerUsingDcom(this, isLocal, compname, flags, options) : #endif ComputerWMIHelper.InvokeWin32ShutdownUsingWsman(this, isLocal, compname, flags, Credential, WsmanAuthentication, ComputerResources.RestartcomputerFailed, "RestartcomputerFailed", _cancel.Token); if (isSuccess && Wait && _timeout != 0) { _waitOnComputers.Add(computer); } }//end foreach if (_waitOnComputers.Count > 0) { var restartStageTestList = new List<string>(_waitOnComputers); var wmiTestList = new List<string>(); var winrmTestList = new List<string>(); var psTestList = new List<string>(); var allDoneList = new List<string>(); bool isForWmi = _waitFor.Equals(WaitForServiceTypes.Wmi); bool isForWinRm = _waitFor.Equals(WaitForServiceTypes.WinRM); bool isForPowershell = _waitFor.Equals(WaitForServiceTypes.PowerShell); int indicatorIndex = 0; int machineCompleteRestart = 0; int actualDelay = SecondsToWaitForRestartToBegin; bool first = true; bool waitComplete = false; _percent = 0; _status = ComputerResources.WaitForRestartToBegin; _activity = _waitOnComputers.Count == 1 ? StringUtil.Format(ComputerResources.RestartSingleComputerActivity, _waitOnComputers[0]) : ComputerResources.RestartMultipleComputersActivity; _timer = new Timer(OnTimedEvent, null, _timeoutInMilliseconds, System.Threading.Timeout.Infinite); while (true) { int loopCount = actualDelay * 4; // (delay * 1000)/250ms while (loopCount > 0) { WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); loopCount--; _waitHandler.Wait(250); if (_exit) { break; } } if (first) { actualDelay = _delay; first = false; if (_waitOnComputers.Count > 1) { _status = StringUtil.Format(ComputerResources.WaitForMultipleComputers, machineCompleteRestart, _waitOnComputers.Count); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } } do { // Test restart stage. // We check if the target machine has already rebooted by querying the LastBootUpTime from the Win32_OperatingSystem object. // So after this step, we are sure that both the Network and the WMI or WinRM service have already come up. if (_exit) { break; } if (restartStageTestList.Count > 0) { if (_waitOnComputers.Count == 1) { _status = ComputerResources.VerifyRebootStage; _percent = CalculateProgressPercentage(StageVerification); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } List<string> nextTestList = (isForWmi || isForPowershell) ? wmiTestList : winrmTestList; restartStageTestList = #if !CORECLR dcomInUse ? TestRestartStageUsingDcom(restartStageTestList, nextTestList, _cancel.Token, options) : #endif TestRestartStageUsingWsman(restartStageTestList, nextTestList, _cancel.Token); } // Test WMI service if (_exit) { break; } if (wmiTestList.Count > 0) { #if !CORECLR if (dcomInUse) { // CIM-DCOM is in use. In this case, restart stage checking is done by using WMIv1, // so the WMI service on the target machine is already up at this point. winrmTestList.AddRange(wmiTestList); wmiTestList.Clear(); if (_waitOnComputers.Count == 1) { // This is to simulate the test for WMI service _status = ComputerResources.WaitForWMI; _percent = CalculateProgressPercentage(WmiConnectionTest); loopCount = actualDelay * 4; // (delay * 1000)/250ms while (loopCount > 0) { WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); loopCount--; _waitHandler.Wait(250); if (_exit) { break; } } } } else #endif // This statement block executes for both CLRs. // In the "full" CLR, it serves as the else case. { if (_waitOnComputers.Count == 1) { _status = ComputerResources.WaitForWMI; _percent = CalculateProgressPercentage(WmiConnectionTest); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } wmiTestList = TestWmiConnectionUsingWsman(wmiTestList, winrmTestList, _cancel.Token, Credential, WsmanAuthentication, this); } } if (isForWmi) { break; } // Test WinRM service if (_exit) { break; } if (winrmTestList.Count > 0) { #if !CORECLR if (dcomInUse) { if (_waitOnComputers.Count == 1) { _status = ComputerResources.WaitForWinRM; _percent = CalculateProgressPercentage(WinrmConnectionTest); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } winrmTestList = TestWinrmConnection(winrmTestList, psTestList, _cancel.Token); } else #endif // This statement block executes for both CLRs. // In the "full" CLR, it serves as the else case. { // CIM-WSMan in use. In this case, restart stage checking is done by using WMIv2, // so the WinRM service on the target machine is already up at this point. psTestList.AddRange(winrmTestList); winrmTestList.Clear(); if (_waitOnComputers.Count == 1) { // This is to simulate the test for WinRM service _status = ComputerResources.WaitForWinRM; _percent = CalculateProgressPercentage(WinrmConnectionTest); loopCount = actualDelay * 4; // (delay * 1000)/250ms while (loopCount > 0) { WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); loopCount--; _waitHandler.Wait(250); if (_exit) { break; } } } } } if (isForWinRm) { break; } // Test PowerShell if (_exit) { break; } if (psTestList.Count > 0) { if (_waitOnComputers.Count == 1) { _status = ComputerResources.WaitForPowerShell; _percent = CalculateProgressPercentage(PowerShellConnectionTest); WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); } psTestList = TestPowerShell(psTestList, allDoneList, _powershell, this.Credential); } } while (false); // if time is up or Ctrl+c is typed, break out if (_exit) { break; } // Check if the restart completes switch (_waitFor) { case WaitForServiceTypes.Wmi: waitComplete = (winrmTestList.Count == _waitOnComputers.Count); machineCompleteRestart = winrmTestList.Count; break; case WaitForServiceTypes.WinRM: waitComplete = (psTestList.Count == _waitOnComputers.Count); machineCompleteRestart = psTestList.Count; break; case WaitForServiceTypes.PowerShell: waitComplete = (allDoneList.Count == _waitOnComputers.Count); machineCompleteRestart = allDoneList.Count; break; } // Wait is done or time is up if (waitComplete || _exit) { if (waitComplete) { _status = ComputerResources.RestartComplete; WriteProgress(_indicator[indicatorIndex % 4] + _activity, _status, 100, ProgressRecordType.Completed); _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); } break; } if (_waitOnComputers.Count > 1) { _status = StringUtil.Format(ComputerResources.WaitForMultipleComputers, machineCompleteRestart, _waitOnComputers.Count); _percent = machineCompleteRestart * 100 / _waitOnComputers.Count; } }// end while(true) if (_timeUp) { // The timeout expires. Write out timeout error messages for the computers that haven't finished restarting do { if (restartStageTestList.Count > 0) { WriteOutTimeoutError(restartStageTestList); } if (wmiTestList.Count > 0) { WriteOutTimeoutError(wmiTestList); } // Wait for WMI. All computers that finished restarting are put in "winrmTestList" if (isForWmi) { break; } // Wait for WinRM. All computers that finished restarting are put in "psTestList" if (winrmTestList.Count > 0) { WriteOutTimeoutError(winrmTestList); } if (isForWinRm) { break; } if (psTestList.Count > 0) { WriteOutTimeoutError(psTestList); } // Wait for PowerShell. All computers that finished restarting are put in "allDoneList" } while (false); } }// end if(waitOnComputer.Count > 0) }//end DefaultParameter }//End Processrecord
private void ProcessDCOMProtocol(object[] flags) { if (AsJob.IsPresent) { string strComputers = ComputerWMIHelper.GetMachineNames(ComputerName); if (!ShouldProcess(strComputers)) return; InvokeWmiMethod WmiInvokeCmd = new InvokeWmiMethod(); WmiInvokeCmd.Path = ComputerWMIHelper.WMI_Class_OperatingSystem + "=@"; WmiInvokeCmd.ComputerName = ComputerName; WmiInvokeCmd.Authentication = DcomAuthentication; WmiInvokeCmd.Impersonation = Impersonation; WmiInvokeCmd.Credential = Credential; WmiInvokeCmd.ThrottleLimit = _throttlelimit; WmiInvokeCmd.Name = "Win32Shutdown"; WmiInvokeCmd.EnableAllPrivileges = SwitchParameter.Present; WmiInvokeCmd.ArgumentList = flags; PSWmiJob wmiJob = new PSWmiJob(WmiInvokeCmd, ComputerName, _throttlelimit, Job.GetCommandTextFromInvocationInfo(this.MyInvocation)); this.JobRepository.Add(wmiJob); WriteObject(wmiJob); } else { string compname = string.Empty; string strLocal = string.Empty; foreach (string computer in ComputerName) { if ((computer.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) || (computer.Equals(".", StringComparison.OrdinalIgnoreCase))) { compname = Dns.GetHostName(); strLocal = "localhost"; } else { compname = computer; } if (!ShouldProcess(StringUtil.Format(ComputerResources.DoubleComputerName, strLocal, compname))) { continue; } else { try { ConnectionOptions options = ComputerWMIHelper.GetConnectionOptions(DcomAuthentication, this.Impersonation, this.Credential); ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), options); EnumerationOptions enumOptions = new EnumerationOptions(); enumOptions.UseAmendedQualifiers = true; enumOptions.DirectRead = true; ObjectQuery query = new ObjectQuery("select * from " + ComputerWMIHelper.WMI_Class_OperatingSystem); using (_searcher = new ManagementObjectSearcher(scope, query, enumOptions)) { foreach (ManagementObject obj in _searcher.Get()) { using (obj) { object result = obj.InvokeMethod("Win32shutdown", flags); int retVal = Convert.ToInt32(result.ToString(), CultureInfo.CurrentCulture); if (retVal != 0) { ComputerWMIHelper.WriteNonTerminatingError(retVal, this, compname); } } } } _searcher = null; } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord(e, "StopComputerException", ErrorCategory.InvalidOperation, compname); WriteError(errorRecord); continue; } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord(e, "StopComputerException", ErrorCategory.InvalidOperation, compname); WriteError(errorRecord); continue; } } } } }
protected override void ProcessRecord() { string hostName; ConnectionOptions connection = ComputerWMIHelper.GetConnection(this.Authentication, this.Impersonation, this.Credential); object[] objArray = new object[2]; objArray[0] = 1; objArray[1] = 0; object[] objArray1 = objArray; if (this._force.IsPresent) { objArray1[0] = 5; } if (!this._asjob.IsPresent) { string empty = string.Empty; string[] strArrays = this._computername; for (int i = 0; i < (int)strArrays.Length; i++) { string str = strArrays[i]; if (str.Equals("localhost", StringComparison.CurrentCultureIgnoreCase) || str.Equals(".", StringComparison.OrdinalIgnoreCase)) { hostName = Dns.GetHostName(); empty = "localhost"; } else { hostName = str; } if (base.ShouldProcess(StringUtil.Format(ComputerResources.DoubleComputerName, empty, hostName))) { try { ManagementScope managementScope = new ManagementScope(ComputerWMIHelper.GetScopeString(str, "\\root\\cimv2"), connection); EnumerationOptions enumerationOption = new EnumerationOptions(); enumerationOption.UseAmendedQualifiers = true; enumerationOption.DirectRead = true; ObjectQuery objectQuery = new ObjectQuery("select * from Win32_OperatingSystem"); this.searcher = new ManagementObjectSearcher(managementScope, objectQuery, enumerationOption); foreach (ManagementObject managementObject in this.searcher.Get()) { object obj = managementObject.InvokeMethod("Win32shutdown", objArray1); int num = Convert.ToInt32(obj.ToString(), CultureInfo.CurrentCulture); if (num == 0) { continue; } ComputerWMIHelper.WriteNonTerminatingError(num, this, hostName); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; ErrorRecord errorRecord = new ErrorRecord(managementException, "StopComputerException", ErrorCategory.InvalidOperation, hostName); base.WriteError(errorRecord); } catch (COMException cOMException1) { COMException cOMException = cOMException1; ErrorRecord errorRecord1 = new ErrorRecord(cOMException, "StopComputerException", ErrorCategory.InvalidOperation, hostName); base.WriteError(errorRecord1); } } } return; } else { string machineNames = ComputerWMIHelper.GetMachineNames(this.ComputerName); if (base.ShouldProcess(machineNames)) { InvokeWmiMethod invokeWmiMethod = new InvokeWmiMethod(); invokeWmiMethod.Path = "Win32_OperatingSystem=@"; invokeWmiMethod.ComputerName = this._computername; invokeWmiMethod.Authentication = this._authentication; invokeWmiMethod.Impersonation = this._impersonation; invokeWmiMethod.Credential = this._credential; invokeWmiMethod.ThrottleLimit = this._throttlelimit; invokeWmiMethod.Name = "Win32Shutdown"; invokeWmiMethod.EnableAllPrivileges = SwitchParameter.Present; invokeWmiMethod.ArgumentList = objArray1; PSWmiJob pSWmiJob = new PSWmiJob(invokeWmiMethod, this._computername, this._throttlelimit, Job.GetCommandTextFromInvocationInfo(base.MyInvocation)); base.JobRepository.Add(pSWmiJob); base.WriteObject(pSWmiJob); return; } else { return; } } }
protected override void ProcessRecord() { ManagementObject managementObject; if (!base.AsJob) { if (this.inputObject == null) { ConnectionOptions connectionOption = base.GetConnectionOption(); ManagementPath managementPath = null; object obj = null; if (this.path != null) { managementPath = new ManagementPath(this.path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (this.namespaceSpecified) { base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "NamespaceSpecifiedWithPath", ErrorCategory.InvalidOperation, base.Namespace)); } } else { managementPath.NamespacePath = base.Namespace; } if (managementPath.Server != "." && this.serverNameSpecified) { base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "ComputerNameSpecifiedWithPath", ErrorCategory.InvalidOperation, base.ComputerName)); } if (!(managementPath.Server == ".") || !this.serverNameSpecified) { string[] server = new string[1]; server[0] = managementPath.Server; string[] strArrays = server; base.ComputerName = strArrays; } } string[] computerName = base.ComputerName; for (int i = 0; i < (int)computerName.Length; i++) { string str = computerName[i]; obj = null; try { if (this.path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(str, base.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(this.className); managementObject = managementClass; managementObject.Scope = managementScope; } else { managementPath.Server = str; if (!managementPath.IsClass) { ManagementObject managementObject1 = new ManagementObject(managementPath); managementObject = managementObject1; } else { ManagementClass managementClass1 = new ManagementClass(managementPath); managementObject = managementClass1; } ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption); managementObject.Scope = managementScope1; } ManagementBaseObject methodParameters = managementObject.GetMethodParameters(this.methodName); if (this.argumentList != null) { int length = (int)this.argumentList.Length; foreach (PropertyData property in methodParameters.Properties) { if (length == 0) { break; } object obj1 = PSObject.Base(this.argumentList[(int)this.argumentList.Length - length]); if (!property.IsArray) { property.Value = obj1; } else { property.Value = InvokeWmiMethod.MakeBaseObjectArray(obj1); } length--; } } if (base.ShouldProcess(StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, managementObject["__CLASS"].ToString(), this.Name))) { obj = managementObject.InvokeMethod(this.methodName, methodParameters, null); } else { return; } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; ErrorRecord errorRecord = new ErrorRecord(managementException, "InvokeWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } catch (COMException cOMException1) { COMException cOMException = cOMException1; ErrorRecord errorRecord1 = new ErrorRecord(cOMException, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } if (obj != null) { base.WriteObject(obj); } } return; } else { object obj2 = null; try { ManagementBaseObject managementBaseObject = this.inputObject.GetMethodParameters(this.methodName); if (this.argumentList != null) { int num = (int)this.argumentList.Length; foreach (PropertyData propertyDatum in managementBaseObject.Properties) { if (num == 0) { break; } propertyDatum.Value = this.argumentList[(int)this.argumentList.Length - num]; num--; } } if (base.ShouldProcess(StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, this.inputObject["__CLASS"].ToString(), this.Name))) { obj2 = this.inputObject.InvokeMethod(this.methodName, managementBaseObject, null); } else { return; } } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; ErrorRecord errorRecord2 = new ErrorRecord(managementException2, "InvokeWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord2); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; ErrorRecord errorRecord3 = new ErrorRecord(cOMException2, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord3); } if (obj2 != null) { base.WriteObject(obj2); } } return; } else { base.RunAsJob("Invoke-WMIMethod"); return; } }
private void ConnectInvokeWmi() { ManagementObject managementObject; object obj; string str; InvokeWmiMethod invokeWmiMethod = (InvokeWmiMethod)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); if (invokeWmiMethod.InputObject == null) { ConnectionOptions connectionOption = invokeWmiMethod.GetConnectionOption(); ManagementPath managementPath = null; if (invokeWmiMethod.Path != null) { managementPath = new ManagementPath(invokeWmiMethod.Path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (invokeWmiMethod.namespaceSpecified) { InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath"); this.internalException = invalidOperationException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { managementPath.NamespacePath = invokeWmiMethod.Namespace; } if (!(managementPath.Server != ".") || !invokeWmiMethod.serverNameSpecified) { if (!(managementPath.Server == ".") || !invokeWmiMethod.serverNameSpecified) { this.computerName = managementPath.Server; } } else { InvalidOperationException invalidOperationException1 = new InvalidOperationException("ComputerNameSpecifiedWithPath"); this.internalException = invalidOperationException1; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } bool flag = false; bool enablePrivilege = false; Win32Native.TOKEN_PRIVILEGE tOKENPRIVILEGE = new Win32Native.TOKEN_PRIVILEGE(); try { try { enablePrivilege = this.NeedToEnablePrivilege(this.computerName, invokeWmiMethod.Name, ref flag); if (!enablePrivilege || flag && ComputerWMIHelper.EnableTokenPrivilege("SeShutdownPrivilege", ref tOKENPRIVILEGE) || !flag && ComputerWMIHelper.EnableTokenPrivilege("SeRemoteShutdownPrivilege", ref tOKENPRIVILEGE)) { if (invokeWmiMethod.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, invokeWmiMethod.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(invokeWmiMethod.Class); managementObject = managementClass; managementObject.Scope = managementScope; } else { managementPath.Server = this.computerName; if (!managementPath.IsClass) { ManagementObject managementObject1 = new ManagementObject(managementPath); managementObject = managementObject1; } else { ManagementClass managementClass1 = new ManagementClass(managementPath); managementObject = managementClass1; } ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption); managementObject.Scope = managementScope1; } ManagementBaseObject methodParameters = managementObject.GetMethodParameters(invokeWmiMethod.Name); if (invokeWmiMethod.ArgumentList != null) { int length = (int)invokeWmiMethod.ArgumentList.Length; foreach (PropertyData property in methodParameters.Properties) { if (length == 0) { break; } property.Value = invokeWmiMethod.ArgumentList[(int)invokeWmiMethod.ArgumentList.Length - length]; length--; } } if (!enablePrivilege) { managementObject.InvokeMethod(this.results, invokeWmiMethod.Name, methodParameters, null); } else { ManagementBaseObject managementBaseObject = managementObject.InvokeMethod(invokeWmiMethod.Name, methodParameters, null); int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if (num == 0) { this.ShutdownComplete.SafeInvoke <EventArgs>(this, null); } else { Win32Exception win32Exception = new Win32Exception(num); this.internalException = win32Exception; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } } else { string privilegeNotEnabled = ComputerResources.PrivilegeNotEnabled; string str1 = this.computerName; if (flag) { obj = "SeShutdownPrivilege"; } else { obj = "SeRemoteShutdownPrivilege"; } string str2 = StringUtil.Format(privilegeNotEnabled, str1, obj); InvalidOperationException invalidOperationException2 = new InvalidOperationException(str2); this.internalException = invalidOperationException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.internalException = cOMException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; this.internalException = unauthorizedAccessException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } finally { if (enablePrivilege) { if (flag) { str = "SeShutdownPrivilege"; } else { str = "SeRemoteShutdownPrivilege"; } ComputerWMIHelper.RestoreTokenPrivilege(str, ref tOKENPRIVILEGE); } } return; } else { try { ManagementBaseObject methodParameters1 = invokeWmiMethod.InputObject.GetMethodParameters(invokeWmiMethod.Name); if (invokeWmiMethod.ArgumentList != null) { int length1 = (int)invokeWmiMethod.ArgumentList.Length; foreach (PropertyData argumentList in methodParameters1.Properties) { if (length1 == 0) { break; } argumentList.Value = invokeWmiMethod.ArgumentList[(int)invokeWmiMethod.ArgumentList.Length - length1]; length1--; } } invokeWmiMethod.InputObject.InvokeMethod(this.results, invokeWmiMethod.Name, methodParameters1, null); } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; this.internalException = managementException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; this.internalException = cOMException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException3) { UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3; this.internalException = unauthorizedAccessException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; } }
protected override void ProcessRecord() { string str; object localShutdownPrivilege; string str1; bool flag; string restartMultipleComputersActivity; List<string> strs; List<string> strs1; List<string> strs2; this.ValidateComputerNames(); ConnectionOptions connection = ComputerWMIHelper.GetConnection(this.DcomAuthentication, this.Impersonation, this.Credential); object[] objArray = new object[2]; objArray[0] = 2; objArray[1] = 0; object[] objArray1 = objArray; if (this.Force) { objArray1[0] = 6; } if (!base.ParameterSetName.Equals("AsJobSet", StringComparison.OrdinalIgnoreCase)) { if (base.ParameterSetName.Equals("DefaultSet", StringComparison.OrdinalIgnoreCase)) { bool flag1 = this.Protocol.Equals("DCOM", StringComparison.OrdinalIgnoreCase); if (this.Wait && this._timeout != 0) { RestartComputerCommand restartComputerCommand = this; if (flag1) { strs2 = this.SetUpComputerInfoUsingDcom(this._validatedComputerNames, connection); } else { strs2 = this.SetUpComputerInfoUsingWsman(this._validatedComputerNames, this._cancel.Token); } restartComputerCommand._validatedComputerNames = strs2; } foreach (string _validatedComputerName in this._validatedComputerNames) { bool flag2 = false; if (!_validatedComputerName.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) { str = _validatedComputerName; } else { str = this._shortLocalMachineName; flag2 = true; if (flag1) { connection.Username = null; //connection.SecurePassword = null; } } string restartComputerAction = ComputerResources.RestartComputerAction; if (flag2) { localShutdownPrivilege = ComputerResources.LocalShutdownPrivilege; } else { localShutdownPrivilege = ComputerResources.RemoteShutdownPrivilege; } string str2 = StringUtil.Format(restartComputerAction, localShutdownPrivilege); if (flag2) { str1 = StringUtil.Format(ComputerResources.DoubleComputerName, "localhost", str); } else { str1 = str; } string str3 = str1; if (!base.ShouldProcess(str3, str2)) { continue; } if (flag1) { flag = RestartComputerCommand.RestartOneComputerUsingDcom(this, flag2, str, objArray1, connection); } else { flag = RestartComputerCommand.RestartOneComputerUsingWsman(this, flag2, str, objArray1, this.Credential, this.WsmanAuthentication, this._cancel.Token); } bool flag3 = flag; if (!flag3 || !this.Wait || this._timeout == 0) { continue; } this._waitOnComputers.Add(_validatedComputerName); } if (this._waitOnComputers.Count > 0) { List<string> strs3 = new List<string>(this._waitOnComputers); List<string> strs4 = new List<string>(); List<string> strs5 = new List<string>(); List<string> strs6 = new List<string>(); List<string> strs7 = new List<string>(); bool flag4 = this._waitFor.Equals(WaitForServiceTypes.Wmi); bool flag5 = this._waitFor.Equals(WaitForServiceTypes.WinRM); bool flag6 = this._waitFor.Equals(WaitForServiceTypes.PowerShell); int num = 0; int count = 0; int num1 = 25; bool flag7 = true; bool count1 = false; this._percent = 0; this._status = ComputerResources.WaitForRestartToBegin; RestartComputerCommand restartComputerCommand1 = this; if (this._waitOnComputers.Count == 1) { restartMultipleComputersActivity = StringUtil.Format(ComputerResources.RestartSingleComputerActivity, this._waitOnComputers[0]); } else { restartMultipleComputersActivity = ComputerResources.RestartMultipleComputersActivity; } restartComputerCommand1._activity = restartMultipleComputersActivity; this._timer = new System.Timers.Timer((double)this._timeoutInMilliseconds); this._timer.Elapsed += new ElapsedEventHandler(this.OnTimedEvent); this._timer.AutoReset = false; this._timer.Enabled = true; while (true) { int num2 = num1 * 4; do { if (num2 <= 0) { break; } int num3 = num; num = num3 + 1; this.WriteProgress(string.Concat(this._indicator[num3 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); num2--; this._waitHandler.Wait(250); } while (!this._exit); if (flag7) { num1 = this._delay; flag7 = false; if (this._waitOnComputers.Count > 1) { this._status = StringUtil.Format(ComputerResources.WaitForMultipleComputers, count, this._waitOnComputers.Count); int num4 = num; num = num4 + 1; this.WriteProgress(string.Concat(this._indicator[num4 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); } } if (!this._exit) { if (strs3.Count > 0) { if (this._waitOnComputers.Count == 1) { this._status = ComputerResources.VerifyRebootStage; this._percent = this.CalculateProgressPercentage("VerifyStage"); int num5 = num; num = num5 + 1; this.WriteProgress(string.Concat(this._indicator[num5 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); } if (flag4 || flag6) { strs = strs4; } else { strs = strs5; } List<string> strs8 = strs; if (flag1) { strs1 = this.TestRestartStageUsingDcom(strs3, strs8, this._cancel.Token, connection); } else { strs1 = this.TestRestartStageUsingWsman(strs3, strs8, this._cancel.Token); } strs3 = strs1; } if (!this._exit) { if (strs4.Count > 0) { if (!flag1) { if (this._waitOnComputers.Count == 1) { this._status = ComputerResources.WaitForWMI; this._percent = this.CalculateProgressPercentage("WMI"); int num6 = num; num = num6 + 1; this.WriteProgress(string.Concat(this._indicator[num6 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); } strs4 = RestartComputerCommand.TestWmiConnectionUsingWsman(strs4, strs5, this._cancel.Token, this.Credential, this.WsmanAuthentication, this); } else { strs5.AddRange(strs4); strs4.Clear(); if (this._waitOnComputers.Count == 1) { this._status = ComputerResources.WaitForWMI; this._percent = this.CalculateProgressPercentage("WMI"); num2 = num1 * 4; while (num2 > 0) { int num7 = num; num = num7 + 1; this.WriteProgress(string.Concat(this._indicator[num7 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); num2--; this._waitHandler.Wait(250); if (this._exit) { goto Label0; } } } } } Label0: if (!flag4 && !this._exit) { if (strs5.Count > 0) { if (!flag1) { strs6.AddRange(strs5); strs5.Clear(); if (this._waitOnComputers.Count == 1) { this._status = ComputerResources.WaitForWinRM; this._percent = this.CalculateProgressPercentage("WinRM"); num2 = num1 * 4; do { if (num2 <= 0) { break; } int num8 = num; num = num8 + 1; this.WriteProgress(string.Concat(this._indicator[num8 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); num2--; this._waitHandler.Wait(250); } while (!this._exit); } } else { if (this._waitOnComputers.Count == 1) { this._status = ComputerResources.WaitForWinRM; this._percent = this.CalculateProgressPercentage("WinRM"); int num9 = num; num = num9 + 1; this.WriteProgress(string.Concat(this._indicator[num9 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); } strs5 = RestartComputerCommand.TestWinrmConnection(strs5, strs6, this._cancel.Token); } } if (!flag5 && !this._exit && strs6.Count > 0) { if (this._waitOnComputers.Count == 1) { this._status = ComputerResources.WaitForPowerShell; this._percent = this.CalculateProgressPercentage("PowerShell"); int num10 = num; num = num10 + 1; this.WriteProgress(string.Concat(this._indicator[num10 % 4], this._activity), this._status, this._percent, ProgressRecordType.Processing); } strs6 = RestartComputerCommand.TestPowerShell(strs6, strs7, this._powershell, this.Credential); } } } } if (this._exit) { break; } WaitForServiceTypes waitForServiceType = this._waitFor; switch (waitForServiceType) { case WaitForServiceTypes.Wmi: { count1 = strs5.Count == this._waitOnComputers.Count; count = strs5.Count; break; } case WaitForServiceTypes.WinRM: { count1 = strs6.Count == this._waitOnComputers.Count; count = strs6.Count; break; } case WaitForServiceTypes.PowerShell: { count1 = strs7.Count == this._waitOnComputers.Count; count = strs7.Count; break; } } if (count1 || this._exit) { if (!count1) { break; } this._status = ComputerResources.RestartComplete; this.WriteProgress(string.Concat(this._indicator[num % 4], this._activity), this._status, 100, ProgressRecordType.Completed); this._timer.Enabled = false; break; } else { if (this._waitOnComputers.Count > 1) { this._status = StringUtil.Format(ComputerResources.WaitForMultipleComputers, count, this._waitOnComputers.Count); this._percent = count * 100 / this._waitOnComputers.Count; } } } if (this._timeUp) { if (strs3.Count > 0) { this.WriteOutTimeoutError(strs3); } if (strs4.Count > 0) { this.WriteOutTimeoutError(strs4); } if (!flag4) { if (strs5.Count > 0) { this.WriteOutTimeoutError(strs5); } if (!flag5) { if (strs6.Count > 0) { this.WriteOutTimeoutError(strs6); } } else { return; } } else { return; } } } } return; } else { string[] array = this._validatedComputerNames.ToArray(); string machineNames = ComputerWMIHelper.GetMachineNames(array); if (base.ShouldProcess(machineNames)) { InvokeWmiMethod invokeWmiMethod = new InvokeWmiMethod(); invokeWmiMethod.Path = "Win32_OperatingSystem=@"; invokeWmiMethod.ComputerName = array; invokeWmiMethod.Authentication = this.DcomAuthentication; invokeWmiMethod.Impersonation = this.Impersonation; invokeWmiMethod.Credential = this.Credential; invokeWmiMethod.ThrottleLimit = this.ThrottleLimit; invokeWmiMethod.Name = "Win32Shutdown"; invokeWmiMethod.EnableAllPrivileges = SwitchParameter.Present; invokeWmiMethod.ArgumentList = objArray1; PSWmiJob pSWmiJob = new PSWmiJob(invokeWmiMethod, array, this.ThrottleLimit, Job.GetCommandTextFromInvocationInfo(base.MyInvocation)); base.JobRepository.Add(pSWmiJob); base.WriteObject(pSWmiJob); return; } else { return; } } }