public static void SubscribeSync(CimSession cimSession, string cimNamespace) { try { string query = QueryInstanceCore(); //Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Press <Enter> to abort the subscription"); //Console.ResetColor(); CancellationTokenSource cts = new CancellationTokenSource(); CimOperationOptions cimOperationOptions = new CimOperationOptions { CancellationToken = cts.Token }; IEnumerable<CimSubscriptionResult> queryInstances = cimSession.Subscribe(cimNamespace, "WQL", query, cimOperationOptions); IEnumerator<CimSubscriptionResult> queryEnumerator = queryInstances.GetEnumerator(); Thread waitUserInputThread = new Thread(SubscribeSyncReal); waitUserInputThread.Start(queryEnumerator); Console.ReadLine(); cts.Cancel(); queryEnumerator.Dispose(); } catch (CimException ex) { PrintCimException(ex); } catch( Exception ex) { Console.WriteLine(ex.Message); } }
internal static void SetCustomOptions(CimOperationOptions operationOptions, IEnumerable<KeyValuePair<string, object>> customOptions) { if (customOptions != null) { foreach (KeyValuePair<string, object> customOption in customOptions) { CimOperationOptionsHelper.SetCustomOption(operationOptions, customOption.Key, customOption.Value); } } }
public CimOperationOptions(CimOperationOptions optionsToClone) { if (optionsToClone == null) { throw new ArgumentNullException("optionsToClone"); } this._operationCallback = optionsToClone.GetOperationCallbacks(); this._writeMessageCallback = optionsToClone._writeMessageCallback; this._writeProgressCallback = optionsToClone._writeProgressCallback; this._writeErrorCallback = optionsToClone._writeErrorCallback; this._promptUserCallback = optionsToClone._promptUserCallback; }
internal static void SetCustomOption(CimOperationOptions operationOptions, string optionName, object optionValue) { if (optionValue != null) { object cim = CimValueConverter.ConvertFromDotNetToCim(optionValue); CimType cimType = CimConverter.GetCimType(CimValueConverter.GetCimType(optionValue.GetType())); operationOptions.SetCustomOption(optionName, cim, cimType, false); return; } else { return; } }
internal static CimOperationOptions GetOperationOptions() { CimOperationOptions options = new CimOperationOptions(); options.Timeout = new TimeSpan( 0, // Hours 0, // Minutes 30 // Seconds ); options.WriteMessage = CimExtension.WriteMessage; options.WriteProgress = CimExtension.WriteProgress; options.WriteError = CimExtension.WriteError; options.PromptUser = CimExtension.PromptUser; return options; }
public CimAsyncMultipleResults<CimInstance> EnumerateInstancesAsync(string namespaceName, string className, CimOperationOptions options) { this.AssertNotDisposed(); IObservable<CimInstance> cimAsyncInstanceObservable = new CimAsyncInstanceObservable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.EnumerateInstancesCore(namespaceName, className, options, asyncCallbacksReceiver)); return new CimAsyncMultipleResults<CimInstance>(cimAsyncInstanceObservable); }
internal void Apply(CimOperationOptions cimOperationOptions) { CimOperationOptionsHelper.SetCustomOptions(cimOperationOptions, this.GetSnapshot()); }
internal static void SetCustomOptions( CimOperationOptions operationOptions, IEnumerable<KeyValuePair<string, object>> customOptions, CimSensitiveValueConverter cimSensitiveValueConverter) { if (customOptions != null) { foreach (KeyValuePair<string, object> queryOption in customOptions) { SetCustomOption(operationOptions, queryOption.Key, queryOption.Value, cimSensitiveValueConverter); } } }
public IEnumerable<CimInstance> EnumerateAssociatedInstances(string namespaceName, CimInstance sourceInstance, string associationClassName, string resultClassName, string sourceRole, string resultRole, CimOperationOptions options) { this.AssertNotDisposed(); if (sourceInstance != null) { return new CimSyncInstanceEnumerable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.EnumerateAssociatedInstancesCore(namespaceName, sourceInstance, associationClassName, resultClassName, sourceRole, resultRole, options, asyncCallbacksReceiver)); } else { throw new ArgumentNullException("sourceInstance"); } }
// Method: AddRole - Adding a list of server components to a live computer // Parameters: componentUniqueNames - The list of unique names of the server components to install. // Returns: The list of server components that are installed. public List<CimInstance> AddRole(List<string> componentUniqueNames) { CimInstance guidInstance = RequestGuidCreator.CreateRequestGuid(); RequestStateEnum addRoleRequestState = RequestStateEnum.Failed; List<CimInstance> serverComponentInstances = new List<CimInstance>(); List<CimInstance> componentDescriptors = new List<CimInstance>(); Console.WriteLine("Getting Components information..."); // First performs a GetRole operation to get the MSFT_ServerManagerServerComponent CIM classes on the computer GetRoleSample getRoleSample = new GetRoleSample(); List<CimInstance> serverComponents = getRoleSample.GetRole(); // Retrieves the list of MSFT_ServerManagerServerComponentDescriptor CIM classes for the roles to add foreach (CimInstance cimInstance in serverComponents) { CimProperty uniqueNameProperty = cimInstance.CimInstanceProperties["UniqueName"]; if (uniqueNameProperty != null && componentUniqueNames.Contains((string)uniqueNameProperty.Value)) { CimProperty descriptorProperty = cimInstance.CimInstanceProperties["Descriptor"]; if (descriptorProperty != null) { componentDescriptors.Add((CimInstance)descriptorProperty.Value); } } } Console.Write("Start installing components."); // Creates a CIM session to the local computer and invoke the AddServerComponentAsync CIM method using (CimSession cimSession = CimSession.Create(null)) { CimOperationOptions operationOptions = new CimOperationOptions() { EnableMethodResultStreaming = true }; CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); methodParameters.Add(CimMethodParameter.Create("RequestGuid", guidInstance, CimType.Instance, CimFlags.In)); methodParameters.Add(CimMethodParameter.Create("Source", null, CimType.StringArray, CimFlags.In)); methodParameters.Add(CimMethodParameter.Create("ScanForUpdates", false, CimType.Boolean, CimFlags.In)); methodParameters.Add(CimMethodParameter.Create("ServerComponentDescriptors", componentDescriptors.ToArray(), CimType.InstanceArray, CimFlags.In)); IObservable<CimMethodResultBase> observable = cimSession.InvokeMethodAsync("root\\Microsoft\\Windows\\ServerManager", "MSFT_ServerManagerDeploymentTasks", "AddServerComponentAsync", methodParameters, operationOptions); DeploymentObserver observer = new DeploymentObserver(); using (IDisposable cancellationDisposable = observable.Subscribe(observer)) { observer.GetResults(out serverComponentInstances, out addRoleRequestState); } } int timeout = 600000; // timeout in 10 minutes int startTime = Environment.TickCount; // Executes the Loop to query the method invocation results until the RequestState is Completed or Failed while (addRoleRequestState == RequestStateEnum.InProgress && Environment.TickCount < startTime + timeout) { using (CimSession cimSession = CimSession.Create(null)) { CimOperationOptions operationOptions = new CimOperationOptions() { EnableMethodResultStreaming = true }; CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); methodParameters.Add(CimMethodParameter.Create("RequestGuid", guidInstance, CimType.Instance, CimFlags.In)); methodParameters.Add(CimMethodParameter.Create("KeepAlterationStateOnRestartRequired", false, CimType.Boolean, CimFlags.In)); IObservable<CimMethodResultBase> observable = cimSession.InvokeMethodAsync("root\\Microsoft\\Windows\\ServerManager", "MSFT_ServerManagerDeploymentTasks", "GetAlterationRequestState", methodParameters, operationOptions); DeploymentObserver observer = new DeploymentObserver(); using (IDisposable cancellationDisposable = observable.Subscribe(observer)) { observer.GetResults(out serverComponentInstances, out addRoleRequestState); } } Console.Write("."); Thread.Sleep(1000); } Console.WriteLine(); if (addRoleRequestState == RequestStateEnum.Completed) { Console.WriteLine("Components successfully installed!"); } else if (addRoleRequestState == RequestStateEnum.Failed) { Console.WriteLine("AddServerComponentAsync request failed!"); } return serverComponentInstances; }
internal static List<string> TestWmiConnectionUsingWsman(List<string> computerNames, List<string> nextTestList, CancellationToken token, PSCredential credential, string wsmanAuthentication, PSCmdlet cmdlet) { bool flag = false; List<string> strs = new List<string>(); CimOperationOptions cimOperationOption = new CimOperationOptions(); cimOperationOption.Timeout = TimeSpan.FromMilliseconds(2000); cimOperationOption.CancellationToken = new CancellationToken?(token); CimOperationOptions cimOperationOption1 = cimOperationOption; foreach (string computerName in computerNames) { try { if (!token.IsCancellationRequested) { CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computerName, credential, wsmanAuthentication, token, cmdlet); using (cimSession) { IEnumerable<CimInstance> cimInstances = cimSession.QueryInstances("root/cimv2", "WQL", "Select * from Win32_Service Where name = 'Winmgmt'", cimOperationOption1); foreach (CimInstance cimInstance in cimInstances) { flag = true; if (!LanguagePrimitives.IsTrue(cimInstance.CimInstanceProperties["Started"].Value)) { strs.Add(computerName); } else { nextTestList.Add(computerName); } } if (!flag) { strs.Add(computerName); } } } else { break; } } catch (CimException cimException) { strs.Add(computerName); } catch (Exception exception1) { Exception exception = exception1; CommandProcessorBase.CheckForSevereException(exception); strs.Add(computerName); } } return strs; }
private List<string> SetUpComputerInfoUsingWsman(IEnumerable<string> computerNames, CancellationToken token) { bool flag = false; List<string> strs = new List<string>(); CimOperationOptions cimOperationOption = new CimOperationOptions(); cimOperationOption.Timeout = TimeSpan.FromMilliseconds(2000); cimOperationOption.CancellationToken = new CancellationToken?(token); CimOperationOptions cimOperationOption1 = cimOperationOption; foreach (string computerName in computerNames) { try { CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computerName, this.Credential, this.WsmanAuthentication, token, this); using (cimSession) { IEnumerable<CimInstance> cimInstances = cimSession.QueryInstances("root/cimv2", "WQL", "Select * from Win32_OperatingSystem", cimOperationOption1); foreach (CimInstance cimInstance in cimInstances) { flag = true; if (this._computerInfos.ContainsKey(computerName)) { continue; } RestartComputerCommand.ComputerInfo computerInfo = new RestartComputerCommand.ComputerInfo(); computerInfo.LastBootUpTime = cimInstance.CimInstanceProperties["LastBootUpTime"].Value.ToString(); computerInfo.RebootComplete = false; RestartComputerCommand.ComputerInfo computerInfo1 = computerInfo; this._computerInfos.Add(computerName, computerInfo1); strs.Add(computerName); } if (!flag) { string str = StringUtil.Format(ComputerResources.RestartComputerSkipped, computerName, ComputerResources.CannotGetOperatingSystemObject); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str), "RestartComputerSkipped", ErrorCategory.OperationStopped, computerName); base.WriteError(errorRecord); } } } catch (CimException cimException1) { CimException cimException = cimException1; string str1 = StringUtil.Format(ComputerResources.RestartComputerSkipped, computerName, cimException.Message); ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str1), "RestartComputerSkipped", ErrorCategory.OperationStopped, computerName); base.WriteError(errorRecord1); } catch (Exception exception1) { Exception exception = exception1; CommandProcessorBase.CheckForSevereException(exception); string str2 = StringUtil.Format(ComputerResources.RestartComputerSkipped, computerName, exception.Message); ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str2), "RestartComputerSkipped", ErrorCategory.OperationStopped, computerName); base.WriteError(errorRecord2); } } return strs; }
public CimAsyncMultipleResults<CimMethodResultBase> InvokeMethodAsync(string namespaceName, string className, string methodName, CimMethodParametersCollection methodParameters, CimOperationOptions options) { this.AssertNotDisposed(); if (!string.IsNullOrWhiteSpace(methodName)) { IObservable<CimMethodResultBase> cimAsyncMethodResultObservable = new CimAsyncMethodResultObservable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.InvokeMethodCore(namespaceName, className, null, methodName, methodParameters, options, asyncCallbacksReceiver)); return new CimAsyncMultipleResults<CimMethodResultBase>(cimAsyncMethodResultObservable); } else { throw new ArgumentNullException("methodName"); } }
public CimMethodResult InvokeMethod(string namespaceName, string className, string methodName, CimMethodParametersCollection methodParameters, CimOperationOptions options) { this.AssertNotDisposed(); if (!string.IsNullOrWhiteSpace(methodName)) { IEnumerable<CimInstance> cimSyncInstanceEnumerable = new CimSyncInstanceEnumerable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.InvokeMethodCore(namespaceName, className, null, methodName, methodParameters, options, asyncCallbacksReceiver)); CimInstance cimInstance = cimSyncInstanceEnumerable.SingleOrDefault<CimInstance>(); if (cimInstance == null) { return null; } else { return new CimMethodResult(cimInstance); } } else { throw new ArgumentNullException("methodName"); } }
private OperationHandle GetClassCore(string namespaceName, string className, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.GetClass(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, className, options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
public CimAsyncResult<CimClass> GetClassAsync(string namespaceName, string className, CimOperationOptions options) { this.AssertNotDisposed(); IObservable<CimClass> cimAsyncClassObservable = new CimAsyncClassObservable(options, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.GetClassCore(namespaceName, className, options, asyncCallbacksReceiver)); return new CimAsyncResult<CimClass>(cimAsyncClassObservable); }
public CimClass GetClass(string namespaceName, string className, CimOperationOptions options) { this.AssertNotDisposed(); IEnumerable<CimClass> cimSyncClassEnumerable = new CimSyncClassEnumerable(options, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.GetClassCore(namespaceName, className, options, asyncCallbacksReceiver)); return cimSyncClassEnumerable.Single<CimClass>(); }
private OperationHandle EnumerateReferencingInstancesCore(string namespaceName, CimInstance sourceInstance, string associationClassName, string sourceRole, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.ReferenceInstances(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, sourceInstance.InstanceHandle, associationClassName, sourceRole, options.GetKeysOnly(), options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
public CimAsyncMultipleResults<CimInstance> EnumerateReferencingInstancesAsync(string namespaceName, CimInstance sourceInstance, string associationClassName, string sourceRole, CimOperationOptions options) { this.AssertNotDisposed(); if (sourceInstance != null) { IObservable<CimInstance> cimAsyncInstanceObservable = new CimAsyncInstanceObservable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.EnumerateReferencingInstancesCore(namespaceName, sourceInstance, associationClassName, sourceRole, options, asyncCallbacksReceiver)); return new CimAsyncMultipleResults<CimInstance>(cimAsyncInstanceObservable); } else { throw new ArgumentNullException("sourceInstance"); } }
private OperationHandle TestConnectionCore(CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.TestConnection(this._handle, options.GetOperationFlags(), options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private OperationHandle SubscribeCore(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions operationOptions, CimSubscriptionDeliveryOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.Subscribe(this._handle, operationOptions.GetOperationFlags(), operationOptions.GetOperationOptionsHandle(), namespaceName, queryDialect, queryExpression, options.GetSubscriptionDeliveryOptionsHandle(), operationOptions.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private OperationHandle InvokeMethodCore(string namespaceName, string className, CimInstance instance, string methodName, CimMethodParametersCollection methodParameters, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; InstanceHandle instanceHandle; InstanceHandle instanceHandleForMethodInvocation; SessionHandle sessionHandle = this._handle; MiOperationFlags operationFlags = options.GetOperationFlags(); OperationOptionsHandle operationOptionsHandle = options.GetOperationOptionsHandle(); string str = namespaceName; string str1 = className; string str2 = methodName; if (instance != null) { instanceHandle = instance.InstanceHandle; } else { instanceHandle = null; } if (methodParameters != null) { instanceHandleForMethodInvocation = methodParameters.InstanceHandleForMethodInvocation; } else { instanceHandleForMethodInvocation = null; } SessionMethods.Invoke(sessionHandle, operationFlags, operationOptionsHandle, str, str1, str2, instanceHandle, instanceHandleForMethodInvocation, options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private List<string> TestRestartStageUsingWsman(IEnumerable<string> computerNames, List<string> nextTestList, CancellationToken token) { bool flag = false; List<string> strs = new List<string>(); CimOperationOptions cimOperationOption = new CimOperationOptions(); cimOperationOption.Timeout = TimeSpan.FromMilliseconds(2000); cimOperationOption.CancellationToken = new CancellationToken?(token); CimOperationOptions cimOperationOption1 = cimOperationOption; foreach (string computerName in computerNames) { try { if (!token.IsCancellationRequested) { CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computerName, this.Credential, this.WsmanAuthentication, token, this); using (cimSession) { IEnumerable<CimInstance> cimInstances = cimSession.QueryInstances("root/cimv2", "WQL", "Select * from Win32_OperatingSystem", cimOperationOption1); foreach (CimInstance cimInstance in cimInstances) { flag = true; string str = cimInstance.CimInstanceProperties["LastBootUpTime"].Value.ToString(); string lastBootUpTime = this._computerInfos[computerName].LastBootUpTime; if (string.Compare(str, lastBootUpTime, StringComparison.OrdinalIgnoreCase) == 0) { strs.Add(computerName); } else { this._computerInfos[computerName].RebootComplete = true; nextTestList.Add(computerName); } } if (!flag) { strs.Add(computerName); } } } else { break; } } catch (CimException cimException) { strs.Add(computerName); } catch (Exception exception1) { Exception exception = exception1; CommandProcessorBase.CheckForSevereException(exception); strs.Add(computerName); } } return strs; }
public CimAsyncResult<CimInstance> ModifyInstanceAsync(string namespaceName, CimInstance instance, CimOperationOptions options) { this.AssertNotDisposed(); if (instance != null) { IObservable<CimInstance> cimAsyncInstanceObservable = new CimAsyncInstanceObservable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.ModifyInstanceCore(namespaceName, instance, options, asyncCallbacksReceiver)); return new CimAsyncResult<CimInstance>(cimAsyncInstanceObservable); } else { throw new ArgumentNullException("instance"); } }
internal static bool RestartOneComputerUsingWsman(PSCmdlet cmdlet, bool isLocalhost, string computerName, object[] flags, PSCredential credential, string authentication, CancellationToken token) { bool flag; string str; string str1; PSCredential pSCredential; object obj; string str2; bool flag1 = false; if (isLocalhost) { str = "localhost"; } else { str = computerName; } string str3 = str; if (isLocalhost) { str1 = null; } else { str1 = authentication; } string str4 = str1; if (isLocalhost) { pSCredential = null; } else { pSCredential = credential; } PSCredential pSCredential1 = pSCredential; Win32Native.TOKEN_PRIVILEGE tOKENPRIVILEGE = new Win32Native.TOKEN_PRIVILEGE(); CimOperationOptions cimOperationOption = new CimOperationOptions(); cimOperationOption.Timeout = TimeSpan.FromMilliseconds(10000); cimOperationOption.CancellationToken = new CancellationToken?(token); CimOperationOptions cimOperationOption1 = cimOperationOption; try { try { if ((!isLocalhost || !ComputerWMIHelper.EnableTokenPrivilege("SeShutdownPrivilege", ref tOKENPRIVILEGE)) && (isLocalhost || !ComputerWMIHelper.EnableTokenPrivilege("SeRemoteShutdownPrivilege", ref tOKENPRIVILEGE))) { string privilegeNotEnabled = ComputerResources.PrivilegeNotEnabled; string str5 = computerName; if (isLocalhost) { obj = "SeShutdownPrivilege"; } else { obj = "SeRemoteShutdownPrivilege"; } string str6 = StringUtil.Format(privilegeNotEnabled, str5, obj); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str6), "PrivilegeNotEnabled", ErrorCategory.InvalidOperation, null); cmdlet.WriteError(errorRecord); flag = false; return flag; } else { CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(str3, pSCredential1, str4, token, cmdlet); using (cimSession) { CimMethodParametersCollection cimMethodParametersCollection = new CimMethodParametersCollection(); cimMethodParametersCollection.Add(CimMethodParameter.Create("Flags", flags[0], Microsoft.Management.Infrastructure.CimType.SInt32, (CimFlags)((long)0))); cimMethodParametersCollection.Add(CimMethodParameter.Create("Reserved", flags[1], Microsoft.Management.Infrastructure.CimType.SInt32, (CimFlags)((long)0))); CimMethodResult cimMethodResult = cimSession.InvokeMethod("root/cimv2", "Win32_OperatingSystem", "Win32shutdown", cimMethodParametersCollection, cimOperationOption1); int num = Convert.ToInt32(cimMethodResult.ReturnValue.Value, CultureInfo.CurrentCulture); if (num == 0) { flag1 = true; } else { Win32Exception win32Exception = new Win32Exception(num); string str7 = StringUtil.Format(ComputerResources.RestartcomputerFailed, computerName, win32Exception.Message); ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str7), "RestartcomputerFailed", ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(errorRecord1); } } } } catch (CimException cimException1) { CimException cimException = cimException1; string str8 = StringUtil.Format(ComputerResources.RestartcomputerFailed, computerName, cimException.Message); ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str8), "RestartcomputerFailed", ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(errorRecord2); } catch (Exception exception1) { Exception exception = exception1; CommandProcessorBase.CheckForSevereException(exception); string str9 = StringUtil.Format(ComputerResources.RestartcomputerFailed, computerName, exception.Message); ErrorRecord errorRecord3 = new ErrorRecord(new InvalidOperationException(str9), "RestartcomputerFailed", ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(errorRecord3); } return flag1; } finally { if (isLocalhost) { str2 = "SeShutdownPrivilege"; } else { str2 = "SeRemoteShutdownPrivilege"; } ComputerWMIHelper.RestoreTokenPrivilege(str2, ref tOKENPRIVILEGE); } return flag; }
private OperationHandle ModifyInstanceCore(string namespaceName, CimInstance instance, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.ModifyInstance(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, instance.InstanceHandle, options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
public CimAsyncMultipleResults<CimInstance> QueryInstancesAsync(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions options) { this.AssertNotDisposed(); if (!string.IsNullOrWhiteSpace(queryDialect)) { if (!string.IsNullOrWhiteSpace(queryExpression)) { IObservable<CimInstance> cimAsyncInstanceObservable = new CimAsyncInstanceObservable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.QueryInstancesCore(namespaceName, queryDialect, queryExpression, options, asyncCallbacksReceiver)); return new CimAsyncMultipleResults<CimInstance>(cimAsyncInstanceObservable); } else { throw new ArgumentNullException("queryExpression"); } } else { throw new ArgumentNullException("queryDialect"); } }
public IEnumerable<CimClass> EnumerateClasses(string namespaceName, string className, CimOperationOptions options) { this.AssertNotDisposed(); return new CimSyncClassEnumerable(options, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.EnumerateClassesCore(namespaceName, className, options, asyncCallbacksReceiver)); }
internal void Apply(CimOperationOptions cimOperationOptions, CimSensitiveValueConverter cimSensitiveValueConverter) { CimOperationOptionsHelper.SetCustomOptions(cimOperationOptions, this.GetSnapshot(), cimSensitiveValueConverter); }
private List<string> SetUpComputerInfoUsingWsman(IEnumerable<string> computerNames, CancellationToken token) { var validComputerNameList = new List<string>(); var operationOptions = new CimOperationOptions { Timeout = TimeSpan.FromMilliseconds(2000), CancellationToken = token }; foreach (var computer in computerNames) { try { using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, token, this)) { bool itemRetrieved = false; IEnumerable<CimInstance> mCollection = cimSession.QueryInstances( ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.CimQueryDialect, "Select * from " + ComputerWMIHelper.WMI_Class_OperatingSystem, operationOptions); foreach (CimInstance os in mCollection) { itemRetrieved = true; if (!_computerInfos.ContainsKey(computer)) { var info = new ComputerInfo { LastBootUpTime = os.CimInstanceProperties["LastBootUpTime"].Value.ToString(), RebootComplete = false }; _computerInfos.Add(computer, info); validComputerNameList.Add(computer); } } if (!itemRetrieved) { string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ComputerResources.CannotGetOperatingSystemObject); var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped", ErrorCategory.OperationStopped, computer); this.WriteError(error); } } } catch (CimException ex) { string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message); var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped", ErrorCategory.OperationStopped, computer); this.WriteError(error); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message); var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped", ErrorCategory.OperationStopped, computer); this.WriteError(error); } } return validComputerNameList; }
internal static void SetCustomOption( CimOperationOptions operationOptions, string optionName, object optionValue, CimSensitiveValueConverter cimSensitiveValueConverter) { Dbg.Assert(!string.IsNullOrWhiteSpace(optionName), "Caller should verify optionName != null"); if (optionValue == null) { return; } object cimValue = cimSensitiveValueConverter.ConvertFromDotNetToCim(optionValue); CimType cimType = CimConverter.GetCimType(CimSensitiveValueConverter.GetCimType(optionValue.GetType())); operationOptions.SetCustomOption(optionName, cimValue, cimType, mustComply: false); }
private void ProcessWSManProtocolForTestConnection() { if (AsJob) { // TODO: Need job for MI.Net WSMan protocol // Early return of job object. throw new PSNotSupportedException(); } var operationOptions = new CimOperationOptions { Timeout = TimeSpan.FromMilliseconds(2000), CancellationToken = cancel.Token }; int destCount = 0; int sourceCount = 0; foreach (string sourceComp in Source) { try { sourceCount++; string sourceMachine; if ((sourceComp.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) || (sourceComp.Equals(".", StringComparison.OrdinalIgnoreCase))) { sourceMachine = Dns.GetHostName(); } else { sourceMachine = sourceComp; } foreach (var tocomp in ComputerName) { destCount++; string querystring = QueryString(new string[] { tocomp }, true, true); using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(sourceComp, this.Credential, WsmanAuthentication, cancel.Token, this)) { for (int echoRequestCount = 0; echoRequestCount < Count; echoRequestCount++) { IEnumerable<CimInstance> mCollection = cimSession.QueryInstances( ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.CimQueryDialect, querystring, operationOptions); int total = mCollection.ToList().Count; int cimInsCount = 1; foreach (CimInstance obj in mCollection) { ProcessPingStatus(obj); cimInsCount++; // to delay the request, if case to avoid the delay for the last pingrequest if (cimInsCount < total || echoRequestCount < Count - 1 || sourceCount < Source.Length || destCount < ComputerName.Length) Thread.Sleep(Delay * 1000); } } } } } catch (CimException ex) { ErrorRecord errorRecord = new ErrorRecord(ex, "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); } } }
private OperationHandle QueryInstancesCore(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.QueryInstances(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, queryDialect, queryExpression, options.GetKeysOnly(), options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
public IEnumerable<CimInstance> EnumerateInstances(string namespaceName, string className, CimOperationOptions options) { this.AssertNotDisposed(); return new CimSyncInstanceEnumerable(options, this.InstanceId, this.ComputerName, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.EnumerateInstancesCore(namespaceName, className, options, asyncCallbacksReceiver)); }
private List<string> TestRestartStageUsingWsman(IEnumerable<string> computerNames, List<string> nextTestList, CancellationToken token) { var restartStageTestList = new List<string>(); var operationOptions = new CimOperationOptions { Timeout = TimeSpan.FromMilliseconds(2000), CancellationToken = token }; foreach (var computer in computerNames) { try { if (token.IsCancellationRequested) { break; } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, token, this)) { bool itemRetrieved = false; IEnumerable<CimInstance> mCollection = cimSession.QueryInstances( ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.CimQueryDialect, "Select * from " + ComputerWMIHelper.WMI_Class_OperatingSystem, operationOptions); foreach (CimInstance os in mCollection) { itemRetrieved = true; string newLastBootUpTime = os.CimInstanceProperties["LastBootUpTime"].Value.ToString(); string oldLastBootUpTime = _computerInfos[computer].LastBootUpTime; if (string.Compare(newLastBootUpTime, oldLastBootUpTime, StringComparison.OrdinalIgnoreCase) != 0) { _computerInfos[computer].RebootComplete = true; nextTestList.Add(computer); } else { restartStageTestList.Add(computer); } } if (!itemRetrieved) { restartStageTestList.Add(computer); } } } catch (CimException) { restartStageTestList.Add(computer); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); restartStageTestList.Add(computer); } } return restartStageTestList; }
public IEnumerable<CimSubscriptionResult> Subscribe(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions operationOptions) { return this.Subscribe(namespaceName, queryDialect, queryExpression, operationOptions, null); }
internal static List<string> TestWmiConnectionUsingWsman(List<string> computerNames, List<string> nextTestList, CancellationToken token, PSCredential credential, string wsmanAuthentication, PSCmdlet cmdlet) { // Check if the WMI service "Winmgmt" is started const string wmiServiceQuery = "Select * from " + ComputerWMIHelper.WMI_Class_Service + " Where name = 'Winmgmt'"; var wmiTestList = new List<string>(); var operationOptions = new CimOperationOptions { Timeout = TimeSpan.FromMilliseconds(2000), CancellationToken = token }; foreach (var computer in computerNames) { try { if (token.IsCancellationRequested) { break; } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, credential, wsmanAuthentication, token, cmdlet)) { bool itemRetrieved = false; IEnumerable<CimInstance> mCollection = cimSession.QueryInstances( ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.CimQueryDialect, wmiServiceQuery, operationOptions); foreach (CimInstance service in mCollection) { itemRetrieved = true; if (LanguagePrimitives.IsTrue(service.CimInstanceProperties["Started"].Value)) { nextTestList.Add(computer); } else { wmiTestList.Add(computer); } } if (!itemRetrieved) { wmiTestList.Add(computer); } } } catch (CimException) { wmiTestList.Add(computer); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); wmiTestList.Add(computer); } } return wmiTestList; }
public CimAsyncMultipleResults<CimSubscriptionResult> SubscribeAsync(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions operationOptions) { return this.SubscribeAsync(namespaceName, queryDialect, queryExpression, operationOptions, null); }
/// <summary> /// Invokes the Win32Shutdown command on provided target computer using WSMan /// over a CIMSession. The flags parameter determines the type of shutdown operation /// such as shutdown, reboot, force etc. /// </summary> /// <param name="cmdlet">Cmdlet host for reporting errors</param> /// <param name="isLocalhost">True if local host computer</param> /// <param name="computerName">Target computer</param> /// <param name="flags">Win32Shutdown flags</param> /// <param name="credential">Optional credential</param> /// <param name="authentication">Optional authentication</param> /// <param name="formatErrorMessage">Error message format string that takes two parameters</param> /// <param name="ErrorFQEID">Fully qualified error Id</param> /// <param name="cancelToken">Cancel token</param> /// <returns>True on success</returns> internal static bool InvokeWin32ShutdownUsingWsman( PSCmdlet cmdlet, bool isLocalhost, string computerName, object[] flags, PSCredential credential, string authentication, string formatErrorMessage, string ErrorFQEID, CancellationToken cancelToken) { Dbg.Diagnostics.Assert(flags.Length == 2, "Caller need to verify the flags passed in"); bool isSuccess = false; string targetMachine = isLocalhost ? "localhost" : computerName; string authInUse = isLocalhost ? null : authentication; PSCredential credInUse = isLocalhost ? null : credential; var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); var operationOptions = new CimOperationOptions { Timeout = TimeSpan.FromMilliseconds(10000), CancellationToken = cancelToken, //This prefix works against all versions of the WinRM server stack, both win8 and win7 ResourceUriPrefix = new Uri(ComputerWMIHelper.CimUriPrefix) }; try { if (!(isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_SHUTDOWN_NAME, ref currentPrivilegeState)) && !(!isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState))) { string message = StringUtil.Format(ComputerResources.PrivilegeNotEnabled, computerName, isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(message), "PrivilegeNotEnabled", ErrorCategory.InvalidOperation, null); cmdlet.WriteError(errorRecord); return false; } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(targetMachine, credInUse, authInUse, cancelToken, cmdlet)) { var methodParameters = new CimMethodParametersCollection(); methodParameters.Add(CimMethodParameter.Create( "Flags", flags[0], Microsoft.Management.Infrastructure.CimType.SInt32, CimFlags.None)); methodParameters.Add(CimMethodParameter.Create( "Reserved", flags[1], Microsoft.Management.Infrastructure.CimType.SInt32, CimFlags.None)); CimMethodResult result = cimSession.InvokeMethod( ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.WMI_Class_OperatingSystem, ComputerWMIHelper.CimOperatingSystemShutdownMethod, methodParameters, operationOptions); int retVal = Convert.ToInt32(result.ReturnValue.Value, CultureInfo.CurrentCulture); if (retVal != 0) { var ex = new Win32Exception(retVal); string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); ErrorRecord error = new ErrorRecord( new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } else { isSuccess = true; } } } catch (CimException ex) { string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } finally { // Restore the previous privilege state if something unexpected happened PlatformInvokes.RestoreTokenPrivilege( isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState); } return isSuccess; }
public CimAsyncMultipleResults<CimSubscriptionResult> SubscribeAsync(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions operationOptions, CimSubscriptionDeliveryOptions options) { this.AssertNotDisposed(); if (!string.IsNullOrWhiteSpace(queryDialect)) { if (!string.IsNullOrWhiteSpace(queryExpression)) { IObservable<CimSubscriptionResult> cimAsyncIndicationObservable = new CimAsyncIndicationObservable(operationOptions, (CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) => this.SubscribeCore(namespaceName, queryDialect, queryExpression, operationOptions, options, asyncCallbacksReceiver)); return new CimAsyncMultipleResults<CimSubscriptionResult>(cimAsyncIndicationObservable); } else { throw new ArgumentNullException("queryExpression"); } } else { throw new ArgumentNullException("queryDialect"); } }