public Models.NetworkInterfacePerfInfo[] GetNetworkInterfacePerfInfos(out double overall) { String name = "n/a"; String serviceName = "n/a"; String adapterType = "n/a"; String macAddress = "n/a"; Boolean netEnabled = false; ManagementException managementException = null; String[] cards = GetNetworkCards(); Models.NetworkInterfacePerfInfo[] networkInterfacePerfInfos = new Models.NetworkInterfacePerfInfo[cards.Length]; double[] util = new double[cards.Length]; overall = 0; double dataSent = 0, dataReceived = 0, bandwidth = 0; for (int i = 0; i < cards.Length; i++) { util[i] = Double.IsNaN( GetNetworkUtilization(cards[i], out bandwidth, out dataSent, out dataReceived)) ? 0 : GetNetworkUtilization(cards[i], out bandwidth, out dataSent, out dataReceived); try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", //"SELECT * FROM Win32_NetworkAdapter WHERE NetEnabled='true'"); String.Format("SELECT * FROM CIM_NetworkAdapter WHERE Name = '{0}'", cards[i].Replace("[R]", "(R)"))); //String.Format("SELECT * FROM CIM_NetworkAdapter WHERE Name = '{0}'", cards[i])); foreach (ManagementObject obj in searcher.Get()) { name = Convert.ToString(obj["Name"]); serviceName = Convert.ToString(obj["ServiceName"]); adapterType = Convert.ToString(obj["AdapterType"]); macAddress = Convert.ToString(obj["MACAddress"]); netEnabled = Convert.ToBoolean(obj["NetEnabled"]); } } catch (ManagementException ex) { managementException = ex; } networkInterfacePerfInfos[i] = new Models.NetworkInterfacePerfInfo { NetworkCardName = cards[i], CIMName = name, ServiceName = serviceName == String.Empty ? "n/a" : serviceName, AdapterType = adapterType == String.Empty ? "n/a" : adapterType, MACAddress = macAddress == String.Empty ? "n/a" : macAddress, BytesReceived = dataReceived, BytesSent = dataSent, TotalBytes = dataSent + dataReceived, Bandwidth = bandwidth, Utilization = util[i], NetEnabled = netEnabled, ManagementExceptionMessage = managementException?.Message }; } foreach (double value in util) { overall += value; } overall = Math.Round(overall / util.Length, 2); return(networkInterfacePerfInfos); }
internal bool CreateObjectFromInfFile(ConnectionManagerBase connectionManager) { Dictionary <string, object> methodParameters = new Dictionary <string, object> { { "DriverPath", Path.GetDirectoryName(InfLocation) }, { "INFFile", Path.GetFileName(InfLocation) } }; IResultObject driverObject = null; try { log.Debug("CreateFromINF: " + InfLocation); using (IResultObject resultObject = connectionManager.ExecuteMethod("SMS_Driver", "CreateFromINF", methodParameters)) { log.Debug("CreateInstance: " + InfLocation); driverObject = connectionManager.CreateInstance(resultObject["Driver"].ObjectValue); } } catch (SmsQueryException ex) { // error 183 = driver exist, check if source content is ok. if (ex.ExtendStatusErrorCode == 183) { if (ex.InnerException is ManagementException managementException) { try { // update content source path if it dose not exist string query = string.Format("SELECT * FROM SMS_Driver WHERE CI_UniqueID='{0}'", managementException.ErrorInformation["ObjectInfo"].ToString()); driverObject = Utility.GetFirstWMIInstance(connectionManager, query); if (!Directory.Exists(driverObject["ContentSourcePath"].StringValue)) { log.Debug("UpdateContentSourcePath: " + driverObject["LocalizedDisplayName"].StringValue); driverObject["ContentSourcePath"].StringValue = Path.GetDirectoryName(InfLocation); } } catch (SmsQueryException ex1) { ManagementException mgmtException = ex.InnerException as ManagementException; Exception = new SystemException(mgmtException.ErrorInformation["Description"].ToString()); log.Error(string.Format("ContentSourcePath: {0}, {1}, {2}", InfLocation, ex1.GetType().Name, Exception.Message)); return(false); } } else { return(false); } } else if (ex.ExtendStatusErrorCode == 13L) { Exception = new SystemException("Invalid inf file."); log.Error(string.Format("InvalidInf: {0}", InfLocation)); return(false); } else { ManagementException mgmtException = ex.InnerException as ManagementException; Exception = new SystemException(mgmtException.ErrorInformation["Description"].ToString()); log.Error(string.Format("Error: {0}", Exception.Message)); return(false); } } if (driverObject == null) { log.Debug("NoObject: " + InfLocation); return(false); } driverObject["IsEnabled"].BooleanValue = true; try { driverObject.Put(); driverObject.Get(); } catch (SmsQueryException ex) { ManagementException mgmtException = ex.InnerException as ManagementException; Exception = new SystemException(mgmtException.ErrorInformation["Description"].ToString()); log.Error(string.Format("PutDriverObject: {0}, {1}, {2}", InfLocation, ex.GetType().Name, Exception.Message)); return(false); } Object = driverObject; return(true); }
protected override void BeginProcessing() { string str; if (!ComputerWMIHelper.SkipSystemRestoreOperationForARMPlatform(this)) { ManagementScope managementScope = new ManagementScope("\\root\\default"); managementScope.Connect(); this.WMIClass = new ManagementClass("SystemRestore"); this.WMIClass.Scope = managementScope; string[] strArrays = this._drive; for (int i = 0; i < (int)strArrays.Length; i++) { string str1 = strArrays[i]; if (base.ShouldProcess(str1)) { if (str1.EndsWith("\\", StringComparison.CurrentCultureIgnoreCase)) { str = str1; } else { str = string.Concat(str1, "\\"); } if (ComputerWMIHelper.IsValidDrive(str)) { try { object[] objArray = new object[1]; objArray[0] = str; object[] objArray1 = objArray; int num = Convert.ToInt32(this.WMIClass.InvokeMethod("Disable", objArray1), CultureInfo.CurrentCulture); if (!num.Equals(0) && !num.Equals(0x6b5)) { ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(StringUtil.Format(ComputerResources.NotDisabled, str1)), null, ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode.Equals(ManagementStatus.NotFound) || managementException.ErrorCode.Equals(ManagementStatus.InvalidClass)) { ErrorRecord errorRecord1 = new ErrorRecord(new ArgumentException(StringUtil.Format(ComputerResources.NotSupported, new object[0])), null, ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } else { ErrorRecord errorRecord2 = new ErrorRecord(managementException, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord2); } } catch (COMException cOMException1) { COMException cOMException = cOMException1; if (!string.IsNullOrEmpty(cOMException.Message)) { ErrorRecord errorRecord3 = new ErrorRecord(cOMException, "COMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord3); } else { Exception argumentException = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled, new object[0])); base.WriteError(new ErrorRecord(argumentException, "ServiceDisabled", ErrorCategory.InvalidOperation, null)); } } } else { ErrorRecord errorRecord4 = new ErrorRecord(new ArgumentException(StringUtil.Format(ComputerResources.NotValidDrive, str1)), null, ErrorCategory.InvalidData, null); base.WriteError(errorRecord4); } } } return; } else { return; } }
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); } } }
public override void PostApply(BackgroundWorker worker, DoWorkEventArgs e) { try { Dictionary <string, string> error = new Dictionary <string, string>(); List <string> successSUG = new List <string>(); List <string> successDP = new List <string>(); List <IResultObject> updates = (List <IResultObject>)UserData["UpdateItems"]; List <int> updateList = updates.Select(x => x["CI_ID"].IntegerValue).Distinct().ToList(); string query; foreach (IResultObject groupObject in Utility.SearchWMI(ConnectionManager, "SELECT * FROM SMS_AuthorizationList")) { // get wmi object instace groupObject.Get(); worker.ReportProgress(33, string.Format("Removing update(s) from software update group: {0}", groupObject["LocalizedDisplayName"].StringValue)); List <int> compare = updateList.Except(groupObject["Updates"].IntegerArrayValue).ToList(); List <int> keep = groupObject["Updates"].IntegerArrayValue.Except(updateList).ToList(); bool er = false; if (updateList.Except(compare).ToList().Count > 0) { groupObject["Updates"].IntegerArrayValue = keep.ToArray(); try { groupObject.Put(); groupObject.Get(); } catch (SmsQueryException ex) { ManagementException managementException = ex.InnerException as ManagementException; error.Add("Could not remove updates: " + managementException.ErrorInformation["Description"].ToString(), groupObject["LocalizedDisplayName"].StringValue); er = true; } if (!er) { successSUG.Add(groupObject["LocalizedDisplayName"].StringValue); } } } if (checkBoxRemoveContent.Checked == true) { worker.ReportProgress(50, "Querying package content for removal"); Dictionary <string, List <int> > packages = new Dictionary <string, List <int> >(); query = string.Format("SELECT SMS_PackageToContent.ContentID,SMS_PackageToContent.PackageID from SMS_PackageToContent JOIN SMS_CIToContent ON SMS_CIToContent.ContentID = SMS_PackageToContent.ContentID WHERE SMS_CIToContent.CI_ID IN ({0}) ORDER by PackageID", string.Join(",", updateList)); using (IResultObject resultObject = ConnectionManager.QueryProcessor.ExecuteQuery(query)) { foreach (IResultObject resultObject1 in resultObject) { string packageID = resultObject1["PackageID"].StringValue; if (!packages.ContainsKey(packageID)) { packages.Add(packageID, new List <int>()); } packages[packageID].Add(resultObject1["ContentID"].IntegerValue); } } foreach (KeyValuePair <string, List <int> > item in packages) { query = string.Format("SELECT * FROM SMS_SoftwareUpdatesPackage WHERE PackageID = '{0}'", item.Key); IResultObject package = Utility.GetFirstWMIInstance(ConnectionManager, query); worker.ReportProgress(66, string.Format("Removing content from deployment package: {0}", package["Name"].StringValue)); Dictionary <string, object> methodParameters = new Dictionary <string, object> { { "bRefreshDPs", true }, { "ContentIDs", item.Value.ToArray() } }; bool er = false; try { package.ExecuteMethod("RemoveContent", methodParameters); } catch (SmsQueryException ex) { ManagementException managementException = ex.InnerException as ManagementException; error.Add("Could not remove content: " + managementException.ErrorInformation["Description"].ToString(), package["Name"].StringValue); er = true; } if (!er) { successDP.Add(package["Name"].StringValue); } } } PrepareCompletion(successSUG, successDP, error); AddRefreshResultObject(null, PropertyDataUpdateAction.RefreshAll); base.PostApply(worker, e); } catch (Exception ex) { AddRefreshResultObject(null, PropertyDataUpdateAction.RefreshAll); PrepareError(ex.Message); throw; } }
public override void PostApply(BackgroundWorker worker, DoWorkEventArgs e) { try { int num = 0; Dictionary <string, string> error = new Dictionary <string, string>(); List <string> success = new List <string>(); List <IResultObject> applications = (List <IResultObject>)UserData["ApplicationItems"]; List <int> applicationsList = applications.Select(x => x["CI_ID"].IntegerValue).Distinct().ToList(); string query; query = string.Format("SELECT SMS_CIContentPackage.PackageID, SMS_Application.LocalizedDisplayName FROM SMS_CIContentPackage JOIN SMS_Application ON SMS_CIContentPackage.CI_ID = SMS_Application.CI_ID WHERE CI_ID IN ({0})", string.Join(",", applicationsList)); using (IResultObject resultObject = ConnectionManager.QueryProcessor.ExecuteQuery(query)) { foreach (IResultObject resultObject1 in resultObject) { List <IResultObject> value = new List <IResultObject>(); value = resultObject1.GenericsArray; worker.ReportProgress(num * 100 / value[0].Count, string.Format("Removing content for application: {0}", value[0]["LocalizedDisplayName"].StringValue)); bool er = false; try { query = string.Format("SELECT * FROM SMS_ContentPackage WHERE PackageID='{0}'", value[1]["PackageID"].StringValue); using (IResultObject package = Utility.GetFirstWMIInstance(ConnectionManager, query)) { package.Delete(); } } catch (SmsQueryException ex) { ManagementException managementException = ex.InnerException as ManagementException; error.Add("Could not remove content: " + managementException.ErrorInformation["Description"].ToString(), value[0]["LocalizedDisplayName"].StringValue); er = true; } if (!er) { success.Add(value[0]["LocalizedDisplayName"].StringValue); } num++; } } PrepareCompletion(success, error); AddRefreshResultObject(null, PropertyDataUpdateAction.RefreshAll); base.PostApply(worker, e); } catch (Exception ex) { AddRefreshResultObject(null, PropertyDataUpdateAction.RefreshAll); PrepareError(ex.Message); throw; } finally { } }
private void ConnectGetWMI() { string wmiQueryString; GetWmiObjectCommand getWmiObjectCommand = (GetWmiObjectCommand)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); ConnectionOptions connectionOption = getWmiObjectCommand.GetConnectionOption(); SwitchParameter list = getWmiObjectCommand.List; if (!list.IsPresent) { if (string.IsNullOrEmpty(getWmiObjectCommand.Query)) { wmiQueryString = this.GetWmiQueryString(); } else { wmiQueryString = getWmiObjectCommand.Query; } string str = wmiQueryString; ObjectQuery objectQuery = new ObjectQuery(str.ToString()); try { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, getWmiObjectCommand.Namespace), connectionOption); EnumerationOptions enumerationOption = new EnumerationOptions(); enumerationOption.UseAmendedQualifiers = getWmiObjectCommand.Amended; enumerationOption.DirectRead = getWmiObjectCommand.DirectRead; ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery, enumerationOption); for (int i = 0; i < this.cmdCount; i++) { managementObjectSearcher.Get(this.results); } } 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); } return; } else { if (getWmiObjectCommand.ValidateClassFormat()) { try { SwitchParameter recurse = getWmiObjectCommand.Recurse; if (!recurse.IsPresent) { ManagementScope managementScope1 = new ManagementScope(WMIHelper.GetScopeString(this.computerName, getWmiObjectCommand.Namespace), connectionOption); managementScope1.Connect(); ManagementObjectSearcher objectList = getWmiObjectCommand.GetObjectList(managementScope1); if (objectList != null) { objectList.Get(this.results); } else { throw new ManagementException(); } } else { ArrayList arrayLists = new ArrayList(); ArrayList arrayLists1 = new ArrayList(); ArrayList arrayLists2 = new ArrayList(); int num = 0; arrayLists.Add(getWmiObjectCommand.Namespace); bool flag = true; while (num < arrayLists.Count) { string item = (string)arrayLists[num]; ManagementScope managementScope2 = new ManagementScope(WMIHelper.GetScopeString(this.computerName, item), connectionOption); managementScope2.Connect(); ManagementClass managementClass = new ManagementClass(managementScope2, new ManagementPath("__Namespace"), new ObjectGetOptions()); foreach (ManagementBaseObject instance in managementClass.GetInstances()) { if (getWmiObjectCommand.IsLocalizedNamespace((string)instance["Name"])) { continue; } arrayLists.Add(string.Concat(item, "\\", instance["Name"])); } if (!flag) { arrayLists1.Add(this.Job.GetNewSink()); } else { flag = false; arrayLists1.Add(this.results); } arrayLists2.Add(managementScope2); num++; } if (arrayLists1.Count != arrayLists.Count || arrayLists2.Count != arrayLists.Count) { this.internalException = new InvalidOperationException(); this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } else { num = 0; while (num < arrayLists.Count) { ManagementObjectSearcher objectList1 = getWmiObjectCommand.GetObjectList((ManagementScope)arrayLists2[num]); if (objectList1 != null) { if (!flag) { objectList1.Get((ManagementOperationObserver)arrayLists1[num]); } else { flag = false; objectList1.Get(this.results); } num++; } else { num++; } } } } } 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; } else { object[] @class = new object[1]; @class[0] = getWmiObjectCommand.Class; ArgumentException argumentException = new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, "Class", @class)); this.internalException = argumentException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } }
private void DoAddComputerAction(string computer, string newName, bool isLocalhost, ConnectionOptions options, EnumerationOptions enumOptions, ObjectQuery computerSystemQuery) { string str; string userName; string stringFromSecureString; string userName1; string stringFromSecureString1; int num = 0; bool flag = false; if (isLocalhost) { str = this._shortLocalMachineName; } else { str = computer; } string str1 = str; if (base.ParameterSetName != "Domain") { string str2 = StringUtil.Format(ComputerResources.AddComputerActionWorkgroup, this._workgroupName); if (!base.ShouldProcess(str1, str2)) { return; } } else { string str3 = StringUtil.Format(ComputerResources.AddComputerActionDomain, this._domainName); if (!base.ShouldProcess(str1, str3)) { return; } } if (newName != null && newName.Length > 15) { string str4 = newName.Substring(0, 15); string str5 = StringUtil.Format(ComputerResources.TruncateNetBIOSName, str4); string truncateNetBIOSNameCaption = ComputerResources.TruncateNetBIOSNameCaption; if (!this.Force && !base.ShouldContinue(str5, truncateNetBIOSNameCaption)) { return; } } if (this.LocalCredential != null) { //options.SecurePassword = this.LocalCredential.Password; options.Username = ComputerWMIHelper.GetLocalAdminUserName(str1, this.LocalCredential); } if (isLocalhost) { options.Username = null; //options.SecurePassword = null; } ManagementObjectSearcher managementObjectSearcher = null; ManagementScope managementScope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, "\\root\\cimv2"), options); using (managementObjectSearcher) { try { managementObjectSearcher = new ManagementObjectSearcher(managementScope, computerSystemQuery, enumOptions); foreach (ManagementObject managementObject in managementObjectSearcher.Get()) { string item = (string)managementObject["DNSHostName"]; if (newName == null && item.Length > 15) { string str6 = item.Substring(0, 15); string str7 = StringUtil.Format(ComputerResources.TruncateNetBIOSName, str6); string truncateNetBIOSNameCaption1 = ComputerResources.TruncateNetBIOSNameCaption; if (!this.Force && !base.ShouldContinue(str7, truncateNetBIOSNameCaption1)) { continue; } } if (newName == null || !item.Equals(newName, StringComparison.OrdinalIgnoreCase)) { if (base.ParameterSetName != "Domain") { if (!(bool)managementObject["PartOfDomain"]) { string str8 = (string)LanguagePrimitives.ConvertTo(managementObject["Domain"], typeof(string), CultureInfo.InvariantCulture); if (!str8.Equals(this._workgroupName, StringComparison.OrdinalIgnoreCase)) { num = this.JoinWorkgroup(managementObject, str1, null); if (num == 0 && newName != null) { num = this.RenameComputer(managementObject, str1, newName); } flag = num == 0; } else { object[] objArray = new object[2]; objArray[0] = str1; objArray[1] = this._workgroupName; this.WriteErrorHelper(ComputerResources.AddComputerToSameWorkgroup, "AddComputerToSameWorkgroup", str1, ErrorCategory.InvalidOperation, false, objArray); continue; } } else { string removeComputerConfirm = ComputerResources.RemoveComputerConfirm; if (!this.Force && !base.ShouldContinue(removeComputerConfirm, null)) { continue; } string str9 = (string)LanguagePrimitives.ConvertTo(managementObject["Domain"], typeof(string), CultureInfo.InvariantCulture); if (this.Credential != null) { userName = this.Credential.UserName; } else { userName = null; } string str10 = userName; if (this.Credential != null) { stringFromSecureString = Utils.GetStringFromSecureString(this.Credential.Password); } else { stringFromSecureString = null; } string str11 = stringFromSecureString; num = this.UnjoinDomain(managementObject, str1, str9, str10, str11); if (num == 0) { num = this.JoinWorkgroup(managementObject, str1, str9); if (num == 0 && newName != null) { num = this.RenameComputer(managementObject, str1, newName); } } flag = num == 0; } } else { if (!(bool)managementObject["PartOfDomain"]) { string str12 = (string)LanguagePrimitives.ConvertTo(managementObject["Domain"], typeof(string), CultureInfo.InvariantCulture); num = this.JoinDomain(managementObject, str1, null, str12); if (num == 0 && newName != null) { num = this.RenameComputer(managementObject, str1, newName); } flag = num == 0; } else { string str13 = (string)LanguagePrimitives.ConvertTo(managementObject["Domain"], typeof(string), CultureInfo.InvariantCulture); string str14 = ""; if (str13.Contains(".")) { int num1 = str13.IndexOf(".", StringComparison.OrdinalIgnoreCase); str14 = str13.Substring(0, num1); } if (str13.Equals(this._domainName, StringComparison.OrdinalIgnoreCase) || str14.Equals(this._domainName, StringComparison.OrdinalIgnoreCase)) { object[] objArray1 = new object[2]; objArray1[0] = str1; objArray1[1] = this._domainName; this.WriteErrorHelper(ComputerResources.AddComputerToSameDomain, "AddComputerToSameDomain", str1, ErrorCategory.InvalidOperation, false, objArray1); continue; } else { PSCredential unjoinDomainCredential = this.UnjoinDomainCredential; PSCredential credential = unjoinDomainCredential; if (unjoinDomainCredential == null) { credential = this.Credential; } PSCredential pSCredential = credential; if (pSCredential != null) { userName1 = pSCredential.UserName; } else { userName1 = null; } string str15 = userName1; if (pSCredential != null) { stringFromSecureString1 = Utils.GetStringFromSecureString(pSCredential.Password); } else { stringFromSecureString1 = null; } string str16 = stringFromSecureString1; num = this.UnjoinDomain(managementObject, str1, str13, str15, str16); if (num == 0) { num = this.JoinDomain(managementObject, str1, str13, null); if (num == 0 && newName != null) { num = this.RenameComputer(managementObject, str1, newName); } } flag = num == 0; } } } if (!this._passThru) { continue; } base.WriteObject(ComputerWMIHelper.GetComputerStatusObject(num, str1)); } else { object[] objArray2 = new object[2]; objArray2[0] = str1; objArray2[1] = newName; this.WriteErrorHelper(ComputerResources.NewNameIsOldName, "NewNameIsOldName", newName, ErrorCategory.InvalidArgument, false, objArray2); } } if (flag && this._restart) { object[] objArray3 = new object[2]; objArray3[0] = 6; objArray3[1] = 0; object[] objArray4 = objArray3; RestartComputerCommand.RestartOneComputerUsingDcom(this, isLocalhost, str1, objArray4, options); } if (flag && !this._restart) { base.WriteWarning(StringUtil.Format(ComputerResources.RestartNeeded, null, str1)); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; object[] message = new object[2]; message[0] = str1; message[1] = managementException.Message; this.WriteErrorHelper(ComputerResources.FailToConnectToComputer, "AddComputerException", str1, ErrorCategory.OperationStopped, false, message); } catch (COMException cOMException1) { COMException cOMException = cOMException1; object[] message1 = new object[2]; message1[0] = str1; message1[1] = cOMException.Message; this.WriteErrorHelper(ComputerResources.FailToConnectToComputer, "AddComputerException", str1, ErrorCategory.OperationStopped, false, message1); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; object[] message2 = new object[2]; message2[0] = str1; message2[1] = unauthorizedAccessException.Message; this.WriteErrorHelper(ComputerResources.FailToConnectToComputer, "AddComputerException", str1, ErrorCategory.OperationStopped, false, message2); } } }
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; } }
private void ConnectRemoveWmi() { ManagementObject managementObject; RemoveWmiObject removeWmiObject = (RemoveWmiObject)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); if (removeWmiObject.InputObject == null) { ConnectionOptions connectionOption = removeWmiObject.GetConnectionOption(); ManagementPath managementPath = null; if (removeWmiObject.Path != null) { managementPath = new ManagementPath(removeWmiObject.Path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (removeWmiObject.namespaceSpecified) { InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath"); this.internalException = invalidOperationException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { managementPath.NamespacePath = removeWmiObject.Namespace; } if (!(managementPath.Server != ".") || !removeWmiObject.serverNameSpecified) { if (!(managementPath.Server == ".") || !removeWmiObject.serverNameSpecified) { this.computerName = managementPath.Server; } } else { InvalidOperationException invalidOperationException1 = new InvalidOperationException("ComputerNameSpecifiedWithPath"); this.internalException = invalidOperationException1; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } try { if (removeWmiObject.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, removeWmiObject.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(removeWmiObject.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; } managementObject.Delete(this.results); } 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); } return; } else { try { removeWmiObject.InputObject.Delete(this.results); } 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() { ManagementObject managementObject; if (!base.AsJob) { if (this.inputObject == null) { ConnectionOptions connectionOption = base.GetConnectionOption(); ManagementPath managementPath = 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]; 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; } if (base.ShouldProcess(managementObject["__PATH"].ToString())) { managementObject.Delete(); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; ErrorRecord errorRecord = new ErrorRecord(managementException, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } catch (COMException cOMException1) { COMException cOMException = cOMException1; ErrorRecord errorRecord1 = new ErrorRecord(cOMException, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } } return; } else { try { if (base.ShouldProcess(this.inputObject["__PATH"].ToString())) { this.inputObject.Delete(); } } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; ErrorRecord errorRecord2 = new ErrorRecord(managementException2, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord2); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; ErrorRecord errorRecord3 = new ErrorRecord(cOMException2, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord3); } return; } } else { base.RunAsJob("Remove-WMIObject"); return; } }
private void DoRemoveComputerAction(string computer, bool isLocalhost, ConnectionOptions options, EnumerationOptions enumOptions, ObjectQuery computerSystemQuery) { string str; string userName; string stringFromSecureString; bool flag = false; if (isLocalhost) { str = this._shortLocalMachineName; } else { str = computer; } string str1 = str; if (base.ShouldProcess(str1)) { if (this.LocalCredential != null) { //options.SecurePassword = this.LocalCredential.Password; options.Username = ComputerWMIHelper.GetLocalAdminUserName(str1, this.LocalCredential); } if (isLocalhost) { options.Username = null; //options.SecurePassword = null; } ManagementObjectSearcher managementObjectSearcher = null; ManagementScope managementScope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, "\\root\\cimv2"), options); using (managementObjectSearcher) { try { managementObjectSearcher = new ManagementObjectSearcher(managementScope, computerSystemQuery, enumOptions); foreach (ManagementObject managementObject in managementObjectSearcher.Get()) { if ((bool)managementObject["PartOfDomain"]) { string removeComputerConfirm = ComputerResources.RemoveComputerConfirm; if (!this.Force && !base.ShouldContinue(removeComputerConfirm, null)) { continue; } string str2 = (string)LanguagePrimitives.ConvertTo(managementObject["Domain"], typeof(string), CultureInfo.InvariantCulture); if (this.UnjoinDomainCredential != null) { userName = this.UnjoinDomainCredential.UserName; } else { userName = null; } string str3 = userName; if (this.UnjoinDomainCredential != null) { stringFromSecureString = Utils.GetStringFromSecureString(this.UnjoinDomainCredential.Password); } else { stringFromSecureString = null; } string str4 = stringFromSecureString; ManagementBaseObject methodParameters = managementObject.GetMethodParameters("UnjoinDomainOrWorkgroup"); methodParameters.SetPropertyValue("UserName", str3); methodParameters.SetPropertyValue("Password", str4); methodParameters.SetPropertyValue("FUnjoinOptions", 4); ManagementBaseObject managementBaseObject = managementObject.InvokeMethod("UnjoinDomainOrWorkgroup", methodParameters, null); int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if ((num == 0x54b || num == 53) && this.Force) { methodParameters.SetPropertyValue("FUnjoinOptions", 0); managementBaseObject = managementObject.InvokeMethod("UnjoinDomainOrWorkgroup", methodParameters, null); num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); } if (num == 0) { flag = true; if (this._workGroup != null) { ManagementBaseObject methodParameters1 = managementObject.GetMethodParameters("JoinDomainOrWorkgroup"); methodParameters1.SetPropertyValue("Name", this._workGroup); methodParameters1.SetPropertyValue("Password", null); methodParameters1.SetPropertyValue("UserName", null); methodParameters1.SetPropertyValue("FJoinOptions", 0); managementBaseObject = managementObject.InvokeMethod("JoinDomainOrWorkgroup", methodParameters1, null); num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if (num != 0) { Win32Exception win32Exception = new Win32Exception(num); object[] message = new object[4]; message[0] = str1; message[1] = str2; message[2] = this._workGroup; message[3] = win32Exception.Message; string str5 = StringUtil.Format(ComputerResources.FailToSwitchFromDomainToWorkgroup, message); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str5), "FailToJoinWorkGroup", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord); } } } else { Win32Exception win32Exception1 = new Win32Exception(num); object[] objArray = new object[3]; objArray[0] = str1; objArray[1] = str2; objArray[2] = win32Exception1.Message; string str6 = StringUtil.Format(ComputerResources.FailToUnjoinDomain, objArray); ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str6), "FailToUnjoinDomain", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord1); } if (!this._passThru) { continue; } base.WriteObject(ComputerWMIHelper.GetComputerStatusObject(num, str1)); } else { string str7 = StringUtil.Format(ComputerResources.ComputerNotInDomain, str1); ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str7), "ComputerNotInDomain", ErrorCategory.InvalidOperation, str1); base.WriteError(errorRecord2); } } if (flag && this._restart) { object[] objArray1 = new object[2]; objArray1[0] = 6; objArray1[1] = 0; object[] objArray2 = objArray1; RestartComputerCommand.RestartOneComputerUsingDcom(this, isLocalhost, str1, objArray2, options); } if (flag && !this._restart) { base.WriteWarning(StringUtil.Format(ComputerResources.RestartNeeded, null, str1)); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; string str8 = StringUtil.Format(ComputerResources.FailToConnectToComputer, str1, managementException.Message); ErrorRecord errorRecord3 = new ErrorRecord(new InvalidOperationException(str8), "RemoveComputerException", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord3); } catch (COMException cOMException1) { COMException cOMException = cOMException1; string str9 = StringUtil.Format(ComputerResources.FailToConnectToComputer, str1, cOMException.Message); ErrorRecord errorRecord4 = new ErrorRecord(new InvalidOperationException(str9), "RemoveComputerException", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord4); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; string str10 = StringUtil.Format(ComputerResources.FailToConnectToComputer, str1, unauthorizedAccessException.Message); ErrorRecord errorRecord5 = new ErrorRecord(new InvalidOperationException(str10), "RemoveComputerException", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord5); } } return; } else { return; } }
private void DoRenameComputerAction(string computer, string newName, bool isLocalhost) { string str; string userName; string stringFromSecureString; EnumerationOptions enumerationOption = new EnumerationOptions(); enumerationOption.UseAmendedQualifiers = true; enumerationOption.DirectRead = true; EnumerationOptions enumerationOption1 = enumerationOption; ObjectQuery objectQuery = new ObjectQuery("select * from Win32_ComputerSystem"); bool flag = false; if (isLocalhost) { str = this._shortLocalMachineName; } else { str = computer; } string str1 = str; if (base.ShouldProcess(str1)) { if (newName != null && newName.Length > 15) { string str2 = newName.Substring(0, 15); string str3 = StringUtil.Format(ComputerResources.TruncateNetBIOSName, str2); string truncateNetBIOSNameCaption = ComputerResources.TruncateNetBIOSNameCaption; if (!this.Force && !base.ShouldContinue(str3, truncateNetBIOSNameCaption)) { return; } } ConnectionOptions connectionOption = new ConnectionOptions(); connectionOption.Authentication = AuthenticationLevel.PacketPrivacy; connectionOption.Impersonation = ImpersonationLevel.Impersonate; connectionOption.EnablePrivileges = true; ConnectionOptions password = connectionOption; if (!isLocalhost) { if (this.LocalCredential == null) { if (this.DomainCredential != null) { //password.SecurePassword = this.DomainCredential.Password; password.Username = this.DomainCredential.UserName; } } else { //password.SecurePassword = this.LocalCredential.Password; password.Username = ComputerWMIHelper.GetLocalAdminUserName(str1, this.LocalCredential); } } else { password.Username = null; //password.SecurePassword = null; } ManagementScope managementScope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, "\\root\\cimv2"), password); try { try { this._searcher = new ManagementObjectSearcher(managementScope, objectQuery, enumerationOption1); foreach (ManagementObject managementObject in this._searcher.Get()) { string item = (string)managementObject["DNSHostName"]; if (!item.Equals(newName, StringComparison.OrdinalIgnoreCase)) { string str4 = null; string str5 = null; if ((bool)managementObject["PartOfDomain"]) { if (this.DomainCredential != null) { userName = this.DomainCredential.UserName; } else { userName = null; } str4 = userName; if (this.DomainCredential != null) { stringFromSecureString = Utils.GetStringFromSecureString(this.DomainCredential.Password); } else { stringFromSecureString = null; } str5 = stringFromSecureString; } ManagementBaseObject methodParameters = managementObject.GetMethodParameters("Rename"); methodParameters.SetPropertyValue("Name", newName); methodParameters.SetPropertyValue("UserName", str4); methodParameters.SetPropertyValue("Password", str5); ManagementBaseObject managementBaseObject = managementObject.InvokeMethod("Rename", methodParameters, null); int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if (num == 0) { flag = true; } else { Win32Exception win32Exception = new Win32Exception(num); object[] message = new object[3]; message[0] = str1; message[1] = newName; message[2] = win32Exception.Message; string str6 = StringUtil.Format(ComputerResources.FailToRename, message); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str6), "FailToRenameComputer", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord); } if (!this._passThru) { continue; } base.WriteObject(ComputerWMIHelper.GetRenameComputerStatusObject(num, newName, str1)); } else { string str7 = StringUtil.Format(ComputerResources.NewNameIsOldName, str1, newName); ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str7), "NewNameIsOldName", ErrorCategory.InvalidArgument, newName); base.WriteError(errorRecord1); } } if (flag && this._restart) { object[] objArray = new object[2]; objArray[0] = 6; objArray[1] = 0; object[] objArray1 = objArray; RestartComputerCommand.RestartOneComputerUsingDcom(this, isLocalhost, str1, objArray1, password); } if (flag && !this._restart) { base.WriteWarning(StringUtil.Format(ComputerResources.RestartNeeded, null, str1)); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; string str8 = StringUtil.Format(ComputerResources.FailToConnectToComputer, str1, managementException.Message); ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str8), "RenameComputerException", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord2); } catch (COMException cOMException1) { COMException cOMException = cOMException1; string str9 = StringUtil.Format(ComputerResources.FailToConnectToComputer, str1, cOMException.Message); ErrorRecord errorRecord3 = new ErrorRecord(new InvalidOperationException(str9), "RenameComputerException", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord3); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; string str10 = StringUtil.Format(ComputerResources.FailToConnectToComputer, str1, unauthorizedAccessException.Message); ErrorRecord errorRecord4 = new ErrorRecord(new InvalidOperationException(str10), "RenameComputerException", ErrorCategory.OperationStopped, str1); base.WriteError(errorRecord4); } } finally { this._searcher.Dispose(); } return; } else { return; } }
private bool SetAppRegistration(SlideBar.ApplicationRegistration req, bool registration) { bool result; try { byte[] array = new byte[(int)this.IOBytesLength]; array[0] = 1; array[1] = 16; switch (req) { case SlideBar.ApplicationRegistration.AP01_QuickButton0: { array[8] = 9; break; } case SlideBar.ApplicationRegistration.AP02_Reserved: { array[8] = 10; break; } default: { if (req != SlideBar.ApplicationRegistration.AP07_DebugConsole) { result = false; return(result); } array[8] = 15; break; } } array[9] = 3; array[10] = 0; if (registration) { array[16] = 1; } else { array[16] = 0; } result = this.WriteWMIACPI_IO(array); return(result); } catch (ManagementException arg_6C_0) { ManagementException ex = arg_6C_0; //base.DebugInfoTrace(ex); } catch (Exception arg_76_0) { Exception ex2 = arg_76_0; //base.DebugInfoTrace(ex2); } return(false); return(result); }
private void ConnectSetWmi() { ManagementObject value; SetWmiInstance setWmiInstance = (SetWmiInstance)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); if (setWmiInstance.InputObject == null) { ManagementPath managementPath = null; if (setWmiInstance.Class == null) { managementPath = new ManagementPath(setWmiInstance.Path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (setWmiInstance.namespaceSpecified) { InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath"); this.internalException = invalidOperationException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { managementPath.NamespacePath = setWmiInstance.Namespace; } if (!(managementPath.Server != ".") || !setWmiInstance.serverNameSpecified) { if (!managementPath.IsClass) { if (!setWmiInstance.flagSpecified) { setWmiInstance.PutType = PutType.UpdateOrCreate; } else { if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate) { InvalidOperationException invalidOperationException1 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); this.internalException = invalidOperationException1; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } } else { if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly) { setWmiInstance.PutType = PutType.CreateOnly; } else { InvalidOperationException invalidOperationException2 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } } else { InvalidOperationException invalidOperationException3 = new InvalidOperationException("ComputerNameSpecifiedWithPath"); this.internalException = invalidOperationException3; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { if (setWmiInstance.flagSpecified && setWmiInstance.PutType != PutType.CreateOnly) { InvalidOperationException invalidOperationException4 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException4; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } setWmiInstance.PutType = PutType.CreateOnly; } if (managementPath != null && (!(managementPath.Server == ".") || !setWmiInstance.serverNameSpecified)) { this.computerName = managementPath.Server; } ConnectionOptions connectionOption = setWmiInstance.GetConnectionOption(); try { if (setWmiInstance.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, setWmiInstance.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(setWmiInstance.Class); managementClass.Scope = managementScope; value = managementClass.CreateInstance(); } else { managementPath.Server = this.computerName; ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption); if (!managementPath.IsClass) { ManagementObject managementObject = new ManagementObject(managementPath); managementObject.Scope = managementScope1; try { managementObject.Get(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode == ManagementStatus.NotFound) { int num = setWmiInstance.Path.IndexOf(':'); if (num != -1) { int num1 = setWmiInstance.Path.Substring(num).IndexOf('.'); if (num1 != -1) { string str = setWmiInstance.Path.Substring(0, num1 + num); ManagementPath managementPath1 = new ManagementPath(str); ManagementClass managementClass1 = new ManagementClass(managementPath1); managementClass1.Scope = managementScope1; managementObject = managementClass1.CreateInstance(); } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } value = managementObject; } else { ManagementClass managementClass2 = new ManagementClass(managementPath); managementClass2.Scope = managementScope1; value = managementClass2.CreateInstance(); } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator enumerator = setWmiInstance.Arguments.GetEnumerator(); while (enumerator.MoveNext()) { value[enumerator.Key as string] = enumerator.Value; } } PutOptions putOption = new PutOptions(); putOption.Type = setWmiInstance.PutType; if (value == null) { InvalidOperationException invalidOperationException5 = new InvalidOperationException(); this.internalException = invalidOperationException5; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } else { value.Put(this.results, putOption); } } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; this.internalException = managementException2; 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); } } else { ManagementObject value1 = null; try { PutOptions putType = new PutOptions(); if (setWmiInstance.InputObject.GetType() != typeof(ManagementClass)) { if (!setWmiInstance.flagSpecified) { setWmiInstance.PutType = PutType.UpdateOrCreate; } else { if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate) { InvalidOperationException invalidOperationException6 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); this.internalException = invalidOperationException6; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } value1 = (ManagementObject)setWmiInstance.InputObject.Clone(); } else { if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly) { value1 = ((ManagementClass)setWmiInstance.InputObject).CreateInstance(); setWmiInstance.PutType = PutType.CreateOnly; } else { InvalidOperationException invalidOperationException7 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException7; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator dictionaryEnumerator = setWmiInstance.Arguments.GetEnumerator(); while (dictionaryEnumerator.MoveNext()) { value1[dictionaryEnumerator.Key as string] = dictionaryEnumerator.Value; } } putType.Type = setWmiInstance.PutType; if (value1 == null) { InvalidOperationException invalidOperationException8 = new InvalidOperationException(); this.internalException = invalidOperationException8; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } else { value1.Put(this.results, putType); } } catch (ManagementException managementException5) { ManagementException managementException4 = managementException5; this.internalException = managementException4; 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); } } }
public bool SetSlideBarStatus(byte address, byte value) { bool result; try { byte[] array = new byte[(int)this.IOBytesLength]; array[0] = 1; array[1] = 16; array[9] = 3; array[10] = 0; if (address == 1) { array[8] = 43; switch (value) { case 0: case 1: { break; } default: { switch (value) { case 16: case 17: { break; } default: { switch (value) { case 32: { result = this.SetAppRegistration(SlideBar.ApplicationRegistration.AP02_Reserved, false); return(result); } case 33: { result = this.SetAppRegistration(SlideBar.ApplicationRegistration.AP02_Reserved, true); return(result); } default: { result = false; return(result); } } break; } } break; } } array[16] = value; result = this.WriteWMIACPI_IO(array); return(result); } result = false; return(result); } catch (ManagementException arg_91_0) { ManagementException ex = arg_91_0; //base.DebugInfoTrace(ex); } catch (Exception arg_9B_0) { Exception ex2 = arg_9B_0; //base.DebugInfoTrace(ex2); } return(false); return(result); }
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; } }
protected override void ProcessRecord() { bool flag; string str; string str1; string str2; string hostName = Dns.GetHostName(); string str3 = null; Exception exception = null; if (base.ShouldProcess(hostName)) { try { ManagementObject managementObject = new ManagementObject(string.Concat("Win32_ComputerSystem.Name=\"", hostName, "\"")); if (!(bool)managementObject["PartOfDomain"]) { string testComputerNotInDomain = ComputerResources.TestComputerNotInDomain; ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(testComputerNotInDomain), "ComputerNotInDomain", ErrorCategory.InvalidOperation, hostName); base.ThrowTerminatingError(errorRecord); } str3 = (string)LanguagePrimitives.ConvertTo(managementObject["Domain"], typeof(string), CultureInfo.InvariantCulture); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; exception = managementException; } catch (COMException cOMException1) { COMException cOMException = cOMException1; exception = cOMException; } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; exception = unauthorizedAccessException; } if (exception != null) { string str4 = StringUtil.Format(ComputerResources.FailToGetDomainInformation, exception.Message); ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str4), "FailToGetDomainInformation", ErrorCategory.OperationStopped, hostName); base.ThrowTerminatingError(errorRecord1); } if (!this.Repair) { flag = this.VerifySecureChannel(str3, hostName); if (flag) { str1 = StringUtil.Format(ComputerResources.SecureChannelAlive, str3); } else { str1 = StringUtil.Format(ComputerResources.SecureChannelBroken, str3); } str = str1; } else { ResetComputerMachinePasswordCommand.ResetMachineAccountPassword(str3, hostName, this.Server, this.Credential, this); flag = this.ResetSecureChannel(str3); if (flag) { str2 = StringUtil.Format(ComputerResources.RepairSecureChannelSucceed, str3); } else { str2 = StringUtil.Format(ComputerResources.RepairSecureChannelFail, str3); } str = str2; } base.WriteObject(flag); base.WriteVerbose(str); return; } else { return; } }
internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string serverName) { ConnectionOptions connectionOption = this.GetConnectionOption(); ManagementObject value = null; if (base.GetType() == typeof(SetWmiInstance)) { SetWmiInstance setWmiInstance = (SetWmiInstance)this; if (setWmiInstance.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(serverName, setWmiInstance.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(setWmiInstance.Class); managementClass.Scope = managementScope; value = managementClass.CreateInstance(); } else { mPath.Server = serverName; ManagementScope managementScope1 = new ManagementScope(mPath, connectionOption); if (!mPath.IsClass) { ManagementObject managementObject = new ManagementObject(mPath); managementObject.Scope = managementScope1; try { managementObject.Get(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode == ManagementStatus.NotFound) { int num = setWmiInstance.Path.IndexOf(':'); if (num != -1) { int num1 = setWmiInstance.Path.Substring(num).IndexOf('.'); if (num1 != -1) { string str = setWmiInstance.Path.Substring(0, num1 + num); ManagementPath managementPath = new ManagementPath(str); ManagementClass managementClass1 = new ManagementClass(managementPath); managementClass1.Scope = managementScope1; managementObject = managementClass1.CreateInstance(); } else { throw; } } else { throw; } } else { throw; } } value = managementObject; } else { ManagementClass managementClass2 = new ManagementClass(mPath); managementClass2.Scope = managementScope1; value = managementClass2.CreateInstance(); } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator enumerator = setWmiInstance.Arguments.GetEnumerator(); while (enumerator.MoveNext()) { value[enumerator.Key as string] = enumerator.Value; } } } return(value); }
protected override void BeginProcessing() { if (!ComputerWMIHelper.SkipSystemRestoreOperationForARMPlatform(this)) { try { ConnectionOptions connection = ComputerWMIHelper.GetConnection(AuthenticationLevel.Packet, ImpersonationLevel.Impersonate, null); ManagementPath managementPath = new ManagementPath(); managementPath.Path = "\\root\\default"; ManagementScope managementScope = new ManagementScope(managementPath, connection); managementScope.Connect(); this.WMIClass = new ManagementClass("SystemRestore"); this.WMIClass.Scope = managementScope; ObjectQuery objectQuery = new ObjectQuery(string.Concat("select * from SystemRestore where SequenceNumber = ", this._restorepoint)); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); if (managementObjectSearcher.Get().Count != 0) { string machineName = Environment.MachineName; if (base.ShouldProcess(machineName)) { object[] objArray = new object[1]; objArray[0] = this._restorepoint; object[] objArray1 = objArray; this.WMIClass.InvokeMethod("Restore", objArray1); managementPath.Path = "\\root\\cimv2"; managementScope.Path = managementPath; ManagementClass managementClass = new ManagementClass("Win32_OperatingSystem"); managementClass.Scope = managementScope; ObjectQuery objectQuery1 = new ObjectQuery("Select * from Win32_OperatingSystem"); ManagementObjectSearcher managementObjectSearcher1 = new ManagementObjectSearcher(managementScope, objectQuery1); foreach (ManagementObject managementObject in managementObjectSearcher1.Get()) { string[] strArrays = new string[1]; strArrays[0] = ""; string[] strArrays1 = strArrays; managementObject.InvokeMethod("Reboot", strArrays1); } } } else { string str = StringUtil.Format(ComputerResources.InvalidRestorePoint, this._restorepoint); ArgumentException argumentException = new ArgumentException(str); ErrorRecord errorRecord = new ErrorRecord(argumentException, "InvalidRestorePoint", ErrorCategory.InvalidArgument, null); base.WriteError(errorRecord); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode.ToString().Equals("NotFound") || managementException.ErrorCode.ToString().Equals("InvalidClass")) { Exception exception = new ArgumentException(StringUtil.Format(ComputerResources.NotSupported, new object[0])); base.WriteError(new ErrorRecord(exception, "RestoreComputerNotSupported", ErrorCategory.InvalidOperation, null)); } else { ErrorRecord errorRecord1 = new ErrorRecord(managementException, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } } catch (COMException cOMException1) { COMException cOMException = cOMException1; if (!string.IsNullOrEmpty(cOMException.Message)) { ErrorRecord errorRecord2 = new ErrorRecord(cOMException, "COMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord2); } else { Exception argumentException1 = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled, new object[0])); base.WriteError(new ErrorRecord(argumentException1, "ServiceDisabled", ErrorCategory.InvalidOperation, null)); } } return; } else { return; } }
protected override void BeginProcessing() { ErrorRecord errorRecord; object[] message; string queryString; ConnectionOptions connectionOption = base.GetConnectionOption(); if (!base.AsJob) { if (!this.list.IsPresent) { SwitchParameter recurse = this.Recurse; if (!recurse.IsPresent || !string.IsNullOrEmpty(this.wmiClass)) { if (string.IsNullOrEmpty(this.Query)) { queryString = this.GetQueryString(); } else { queryString = this.Query; } string str = queryString; ObjectQuery objectQuery = new ObjectQuery(str.ToString()); string[] computerName = base.ComputerName; for (int i = 0; i < (int)computerName.Length; i++) { string str1 = computerName[i]; try { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(str1, base.Namespace), connectionOption); EnumerationOptions enumerationOption = new EnumerationOptions(); enumerationOption.UseAmendedQualifiers = this.amended; enumerationOption.DirectRead = this.directRead; ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery, enumerationOption); foreach (ManagementBaseObject managementBaseObject in managementObjectSearcher.Get()) { var exists = managementBaseObject.ObjectExits; if (exists) { base.WriteObject(managementBaseObject); } } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (!managementException.ErrorCode.Equals(ManagementStatus.InvalidClass)) { if (!managementException.ErrorCode.Equals(ManagementStatus.InvalidQuery)) { if (!managementException.ErrorCode.Equals(ManagementStatus.InvalidNamespace)) { errorRecord = new ErrorRecord(managementException, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); } else { message = new object[2]; message[0] = managementException.Message; message[1] = base.Namespace; string str2 = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, message); errorRecord = new ErrorRecord(new ManagementException(str2), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); } } else { message = new object[2]; message[0] = managementException.Message; message[1] = str; string str3 = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, message); errorRecord = new ErrorRecord(new ManagementException(str3), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); } } else { string classNameFromQuery = this.GetClassNameFromQuery(str); message = new object[2]; message[0] = managementException.Message; message[1] = classNameFromQuery; string str4 = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, message); errorRecord = new ErrorRecord(new ManagementException(str4), "GetWMIManagementException", ErrorCategory.InvalidType, null); } base.WriteError(errorRecord); } catch (COMException cOMException1) { COMException cOMException = cOMException1; ErrorRecord errorRecord1 = new ErrorRecord(cOMException, "GetWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } catch (Exception ex) { ErrorRecord errorRecord1 = new ErrorRecord(ex, "GetWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } } return; } else { object[] objArray = new object[1]; objArray[0] = "-Class"; string str5 = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiParameterMissing, objArray); ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str5), "InvalidOperationException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord2); return; } } else { if (this.ValidateClassFormat()) { string[] strArrays = base.ComputerName; for (int j = 0; j < (int)strArrays.Length; j++) { string str6 = strArrays[j]; SwitchParameter switchParameter = this.Recurse; if (!switchParameter.IsPresent) { ManagementScope managementScope1 = new ManagementScope(WMIHelper.GetScopeString(str6, base.Namespace), connectionOption); try { managementScope1.Connect(); } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; ErrorRecord errorDetail = new ErrorRecord(managementException2, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); object[] @namespace = new object[2]; @namespace[0] = base.Namespace; @namespace[1] = managementException2.Message; errorDetail.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", @namespace); base.WriteError(errorDetail); goto Label0; } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; ErrorRecord errorDetail1 = new ErrorRecord(cOMException2, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); object[] namespace1 = new object[2]; namespace1[0] = base.Namespace; namespace1[1] = cOMException2.Message; errorDetail1.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", namespace1); base.WriteError(errorDetail1); goto Label0; } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; ErrorRecord errorDetail2 = new ErrorRecord(unauthorizedAccessException, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); object[] message1 = new object[2]; message1[0] = base.Namespace; message1[1] = unauthorizedAccessException.Message; errorDetail2.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", message1); base.WriteError(errorDetail2); goto Label0; } ManagementObjectSearcher objectList = this.GetObjectList(managementScope1); if (objectList != null) { foreach (ManagementBaseObject managementBaseObject1 in objectList.Get()) { base.WriteObject(managementBaseObject1); } } } else { Queue queues = new Queue(); queues.Enqueue(base.Namespace); while (queues.Count > 0) { string str7 = (string)queues.Dequeue(); ManagementScope managementScope2 = new ManagementScope(WMIHelper.GetScopeString(str6, str7), connectionOption); try { managementScope2.Connect(); } catch (ManagementException managementException5) { ManagementException managementException4 = managementException5; ErrorRecord errorRecord3 = new ErrorRecord(managementException4, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); object[] objArray1 = new object[2]; objArray1[0] = str7; objArray1[1] = managementException4.Message; errorRecord3.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", objArray1); base.WriteError(errorRecord3); continue; } catch (COMException cOMException5) { COMException cOMException4 = cOMException5; ErrorRecord errorDetail3 = new ErrorRecord(cOMException4, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); object[] message2 = new object[2]; message2[0] = str7; message2[1] = cOMException4.Message; errorDetail3.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", message2); base.WriteError(errorDetail3); continue; } catch (UnauthorizedAccessException unauthorizedAccessException3) { UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3; ErrorRecord errorRecord4 = new ErrorRecord(unauthorizedAccessException2, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); object[] objArray2 = new object[2]; objArray2[0] = str7; objArray2[1] = unauthorizedAccessException2.Message; errorRecord4.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", objArray2); base.WriteError(errorRecord4); continue; } ManagementClass managementClass = new ManagementClass(managementScope2, new ManagementPath("__Namespace"), new ObjectGetOptions()); foreach (ManagementBaseObject instance in managementClass.GetInstances()) { if (this.IsLocalizedNamespace((string)instance["Name"])) { continue; } queues.Enqueue(string.Concat(str7, "\\", instance["Name"])); } ManagementObjectSearcher objectList1 = this.GetObjectList(managementScope2); if (objectList1 == null) { continue; } foreach (ManagementBaseObject managementBaseObject2 in objectList1.Get()) { base.WriteObject(managementBaseObject2); } } } Label0: continue; } return; } else { message = new object[1]; message[0] = this.Class; ErrorRecord errorDetail4 = new ErrorRecord(new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, "Class", message)), "INVALID_QUERY_IDENTIFIER", ErrorCategory.InvalidArgument, null); object[] @class = new object[1]; @class[0] = this.Class; errorDetail4.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiFilterInvalidClass", @class); base.WriteError(errorDetail4); return; } } } else { base.RunAsJob("Get-WMIObject"); return; } }
public WMIException(ManagementException ex) : base(GetExceptionText(ex), ex) { }
protected override void ProcessRecord() { if (!base.AsJob) { if (this.inputObject == null) { ManagementPath managementPath = base.SetWmiInstanceBuildManagementPath(); if (managementPath != null && (!(managementPath.Server == ".") || !this.serverNameSpecified)) { string[] server = new string[1]; server[0] = managementPath.Server; string[] strArrays = server; base.ComputerName = strArrays; } base.GetConnectionOption(); object obj = null; string[] computerName = base.ComputerName; for (int i = 0; i < (int)computerName.Length; i++) { string str = computerName[i]; obj = null; try { ManagementObject managementObject = base.SetWmiInstanceGetObject(managementPath, str); PutOptions putOption = new PutOptions(); putOption.Type = this.putType; if (managementObject == null) { InvalidOperationException invalidOperationException = new InvalidOperationException(); throw invalidOperationException; } else { if (base.ShouldProcess(managementObject.Path.Path.ToString())) { managementObject.Put(putOption); obj = managementObject; } else { goto Label0; } } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; ErrorRecord errorRecord = new ErrorRecord(managementException, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } catch (COMException cOMException1) { COMException cOMException = cOMException1; ErrorRecord errorRecord1 = new ErrorRecord(cOMException, "SetWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord1); } if (obj != null) { base.WriteObject(obj); } Label0: continue; } } else { object obj1 = null; try { PutOptions putOption1 = new PutOptions(); ManagementObject managementObject1 = base.SetWmiInstanceGetPipelineObject(); putOption1.Type = this.putType; if (managementObject1 == null) { InvalidOperationException invalidOperationException1 = new InvalidOperationException(); throw invalidOperationException1; } else { if (base.ShouldProcess(managementObject1.Path.Path.ToString())) { managementObject1.Put(putOption1); obj1 = managementObject1; } else { return; } } } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; ErrorRecord errorRecord2 = new ErrorRecord(managementException2, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord2); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; ErrorRecord errorRecord3 = new ErrorRecord(cOMException2, "SetWMICOMException", ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord3); } base.WriteObject(obj1); return; } return; } else { base.RunAsJob("Set-WMIInstance"); return; } }