Exemplo n.º 1
0
 /// <summary>
 /// Start this cmdlet as a WMI job...
 /// </summary>
 internal void RunAsJob(string cmdletName)
 {
     PSWmiJob wmiJob = new PSWmiJob(this, ComputerName, this.ThrottleLimit, Job.GetCommandTextFromInvocationInfo(this.MyInvocation));
     if (_context != null)
     {
         ((System.Management.Automation.Runspaces.LocalRunspace)_context.CurrentRunspace).JobRepository.Add(wmiJob);
     }
     WriteObject(wmiJob);
 }
Exemplo n.º 2
0
        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;
                        }
                    }
                }
            }
        }
Exemplo n.º 3
0
        private void processDCOMProtocolForTestConnection()
        {
            ConnectionOptions options = ComputerWMIHelper.GetConnectionOptions(DcomAuthentication, this.Impersonation, this.Credential);
            if (AsJob)
            {
                string filter = QueryString(ComputerName, true, false);
                GetWmiObjectCommand WMICmd = new GetWmiObjectCommand();
                WMICmd.Filter = filter.ToString();
                WMICmd.Class = ComputerWMIHelper.WMI_Class_PingStatus;
                WMICmd.ComputerName = Source;
                WMICmd.Authentication = DcomAuthentication;
                WMICmd.Impersonation = Impersonation;
                WMICmd.ThrottleLimit = throttlelimit;
                PSWmiJob wmiJob = new PSWmiJob(WMICmd, Source, throttlelimit, this.MyInvocation.MyCommand.Name, Count);
                this.JobRepository.Add(wmiJob);
                WriteObject(wmiJob);
            }
            else
            {
                int sourceCount = 0;
                foreach (string fromcomp in Source)
                {
                    try
                    {
                        sourceCount++;
                        EnumerationOptions enumOptions = new EnumerationOptions();
                        enumOptions.UseAmendedQualifiers = true;
                        enumOptions.DirectRead = true;

                        int destCount = 0;
                        foreach (var tocomp in ComputerName)
                        {
                            destCount++;
                            string querystring = QueryString(new string[] { tocomp }, true, true);
                            ObjectQuery query = new ObjectQuery(querystring);
                            ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(fromcomp, ComputerWMIHelper.WMI_Path_CIM), options);
                            scope.Options.EnablePrivileges = true;
                            scope.Connect();

                            using (searcher = new ManagementObjectSearcher(scope, query, enumOptions))
                            {
                                for (int j = 0; j <= Count - 1; j++)
                                {
                                    using (ManagementObjectCollection mobj = searcher.Get())
                                    {
                                        int mobjCount = 0;
                                        foreach (ManagementBaseObject obj in mobj)
                                        {
                                            using (obj)
                                            {
                                                mobjCount++;

                                                ProcessPingStatus(obj);

                                                // to delay the request, if case to avoid the delay for the last pingrequest
                                                if (mobjCount < mobj.Count || j < Count - 1 || sourceCount < Source.Length || destCount < ComputerName.Length)
                                                    Thread.Sleep(Delay * 1000);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        searcher = null;
                    }
                    catch (ManagementException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "TestConnectionException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                        continue;
                    }
                    catch (System.Runtime.InteropServices.COMException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "TestConnectionException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                        continue;
                    }
                }
            }

            if (quiet)
            {
                foreach (string destinationAddress in this.ComputerName)
                {
                    bool destinationResult = false;
                    this.quietResults.TryGetValue(destinationAddress, out destinationResult);
                    WriteObject(destinationResult);
                }
            }
        }
Exemplo n.º 4
0
        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;
                }
            }
        }
Exemplo n.º 5
0
        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
Exemplo n.º 6
0
		internal void RunAsJob(string cmdletName)
		{
			PSWmiJob pSWmiJob = new PSWmiJob(this, this.ComputerName, this.ThrottleLimit, Job.GetCommandTextFromInvocationInfo(base.MyInvocation));
			if (this._context != null)
			{
				((LocalRunspace)this._context.CurrentRunspace).JobRepository.Add(pSWmiJob);
			}
			base.WriteObject(pSWmiJob);
		}
Exemplo n.º 7
0
        protected override void ProcessRecord()
        {
            ConnectionOptions connection = ComputerWMIHelper.GetConnection(this.Authentication, this.Impersonation, this.Credential);

            if (!this.asjob)
            {
                int      num       = 0;
                string[] strArrays = this.source;
                for (int i = 0; i < (int)strArrays.Length; i++)
                {
                    string str = strArrays[i];
                    try
                    {
                        num++;
                        string          str1            = this.QueryString(this.destination, true, true);
                        ObjectQuery     objectQuery     = new ObjectQuery(str1);
                        ManagementScope managementScope = new ManagementScope(ComputerWMIHelper.GetScopeString(str, "\\root\\cimv2"), connection);
                        managementScope.Options.EnablePrivileges = true;
                        managementScope.Connect();
                        EnumerationOptions enumerationOption = new EnumerationOptions();
                        enumerationOption.UseAmendedQualifiers = true;
                        enumerationOption.DirectRead           = true;
                        this.searcher = new ManagementObjectSearcher(managementScope, objectQuery, enumerationOption);
                        for (int j = 0; j <= this.count - 1; j++)
                        {
                            ManagementObjectCollection managementObjectCollections = this.searcher.Get();
                            int num1 = 0;
                            foreach (ManagementBaseObject managementBaseObject in managementObjectCollections)
                            {
                                num1++;
                                this.ProcessPingStatus(managementBaseObject);
                                if (num1 >= managementObjectCollections.Count && j >= this.count - 1 && num >= (int)this.Source.Length)
                                {
                                    continue;
                                }
                                Thread.Sleep(this.delay * 0x3e8);
                            }
                        }
                    }
                    catch (ManagementException managementException1)
                    {
                        ManagementException managementException = managementException1;
                        ErrorRecord         errorRecord         = new ErrorRecord(managementException, "TestConnectionException", ErrorCategory.InvalidOperation, null);
                        base.WriteError(errorRecord);
                    }
                    catch (COMException cOMException1)
                    {
                        COMException cOMException = cOMException1;
                        ErrorRecord  errorRecord1 = new ErrorRecord(cOMException, "TestConnectionException", ErrorCategory.InvalidOperation, null);
                        base.WriteError(errorRecord1);
                    }
                }
            }
            else
            {
                string str2 = this.QueryString(this.destination, true, false);
                GetWmiObjectCommand getWmiObjectCommand = new GetWmiObjectCommand();
                getWmiObjectCommand.Filter         = str2.ToString();
                getWmiObjectCommand.Class          = "Win32_PingStatus";
                getWmiObjectCommand.ComputerName   = this.source;
                getWmiObjectCommand.Authentication = this.Authentication;
                getWmiObjectCommand.Impersonation  = this.Impersonation;
                getWmiObjectCommand.ThrottleLimit  = this.throttlelimit;
                PSWmiJob pSWmiJob = new PSWmiJob(getWmiObjectCommand, this.source, this.throttlelimit, base.MyInvocation.MyCommand.Name, this.count);
                base.JobRepository.Add(pSWmiJob);
                base.WriteObject(pSWmiJob);
            }
            if (this.quiet)
            {
                string[] strArrays1 = this.destination;
                for (int k = 0; k < (int)strArrays1.Length; k++)
                {
                    string str3 = strArrays1[k];
                    bool   flag = false;
                    this.quietResults.TryGetValue(str3, out flag);
                    base.WriteObject(flag);
                }
            }
        }
Exemplo n.º 8
0
		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;
				}
			}
		}
Exemplo n.º 9
0
		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;
				}
			}
		}
Exemplo n.º 10
0
		protected override void ProcessRecord()
		{
			ConnectionOptions connection = ComputerWMIHelper.GetConnection(this.Authentication, this.Impersonation, this.Credential);
			if (!this.asjob)
			{
				int num = 0;
				string[] strArrays = this.source;
				for (int i = 0; i < (int)strArrays.Length; i++)
				{
					string str = strArrays[i];
					try
					{
						num++;
						string str1 = this.QueryString(this.destination, true, true);
						ObjectQuery objectQuery = new ObjectQuery(str1);
						ManagementScope managementScope = new ManagementScope(ComputerWMIHelper.GetScopeString(str, "\\root\\cimv2"), connection);
						managementScope.Options.EnablePrivileges = true;
						managementScope.Connect();
						EnumerationOptions enumerationOption = new EnumerationOptions();
						enumerationOption.UseAmendedQualifiers = true;
						enumerationOption.DirectRead = true;
						this.searcher = new ManagementObjectSearcher(managementScope, objectQuery, enumerationOption);
						for (int j = 0; j <= this.count - 1; j++)
						{
							ManagementObjectCollection managementObjectCollections = this.searcher.Get();
							int num1 = 0;
							foreach (ManagementBaseObject managementBaseObject in managementObjectCollections)
							{
								num1++;
								this.ProcessPingStatus(managementBaseObject);
								if (num1 >= managementObjectCollections.Count && j >= this.count - 1 && num >= (int)this.Source.Length)
								{
									continue;
								}
								Thread.Sleep(this.delay * 0x3e8);
							}
						}
					}
					catch (ManagementException managementException1)
					{
						ManagementException managementException = managementException1;
						ErrorRecord errorRecord = new ErrorRecord(managementException, "TestConnectionException", ErrorCategory.InvalidOperation, null);
						base.WriteError(errorRecord);
					}
					catch (COMException cOMException1)
					{
						COMException cOMException = cOMException1;
						ErrorRecord errorRecord1 = new ErrorRecord(cOMException, "TestConnectionException", ErrorCategory.InvalidOperation, null);
						base.WriteError(errorRecord1);
					}
				}
			}
			else
			{
				string str2 = this.QueryString(this.destination, true, false);
				GetWmiObjectCommand getWmiObjectCommand = new GetWmiObjectCommand();
				getWmiObjectCommand.Filter = str2.ToString();
				getWmiObjectCommand.Class = "Win32_PingStatus";
				getWmiObjectCommand.ComputerName = this.source;
				getWmiObjectCommand.Authentication = this.Authentication;
				getWmiObjectCommand.Impersonation = this.Impersonation;
				getWmiObjectCommand.ThrottleLimit = this.throttlelimit;
				PSWmiJob pSWmiJob = new PSWmiJob(getWmiObjectCommand, this.source, this.throttlelimit, base.MyInvocation.MyCommand.Name, this.count);
				base.JobRepository.Add(pSWmiJob);
				base.WriteObject(pSWmiJob);
			}
			if (this.quiet)
			{
				string[] strArrays1 = this.destination;
				for (int k = 0; k < (int)strArrays1.Length; k++)
				{
					string str3 = strArrays1[k];
					bool flag = false;
					this.quietResults.TryGetValue(str3, out flag);
					base.WriteObject(flag);
				}
			}
		}