/// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="theNamespace"></param> /// <param name="theCollection"></param> /// <param name="theProxy"></param> internal CimInvokeCimMethodContext(string theNamespace, string theMethodName, CimMethodParametersCollection theCollection, CimSessionProxy theProxy) { this.proxy = theProxy; this.methodName = theMethodName; this.collection = theCollection; this.nameSpace = theNamespace; }
protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { this._backingMethodParametersCollection.Dispose(); this._backingMethodParametersCollection = null; } this._disposed = true; } }
/// <summary> /// Adds the given a computer to a collection. /// </summary> /// <param name="computerName">The name of the computer to add.</param> /// <param name="collectionId">The CollectionID of the collection to which the computer will be added.</param> public static bool AddComputerToCollection(string computerName, string collectionId) { /* * Dear Forgetful me. I will explain what happens here so that you NEVER have to figure this out ever again. took you long enough the first time. * * Step one: cimSession. cimSession is the overall session connection to the remote server. This is SCCM01 in this case. cimSession is also used to call methods * of any of the classes in any of the namespaces of the current connection to the current server. whew. * * Step two: The method that we're going to call takes in a parameter. that parameter in this case is SMS_CollectionRuleDirect. That class takes two properties. * since the direct rule that we are creating is a computer, then the two parameters are: SMS_R_System as the class, and the ResourceID of the computer. So the * first thing we do is create an instance of the cimCollectionRuleDirect class, and add the two properties that we need (ResourceClassName, ResourceID) * * Step three: Now that we have the parameter that we want to send to the method, we need to package it as a parameter fit to be sent. so we create a new * CimMethodParametersCollection and add cimCollectionRuleDirect to it as the only parameter. * * Step four: Ok, so now we have the parameter that we need all ready, and all we need to do is call the method and pass it the parameter. We want to call the method * on the actual collection that we want the computer added, so we must do a query to find it. * * Step five: Last step, call the method on the collection. we use the cimSession connection to invoke the method, and pass in the parameters: 1)the collection * whose method we are invoking 2) the name of the method that we are invoking, and 3) the parameter that we are passing. voila. */ CimSession cimSession = null; try { var resourceId = uint.Parse(GetComputerByName(computerName).ResourceID); cimSession = CimSession.Create(Properties.Resources.SCCMServerName); var cimCollectionRuleDirect = new CimInstance("SMS_CollectionRuleDirect"); //CimClass cimClass = cimSession.GetClass(@"ROOT\sms\site_EDU","SMS_CollectionRuleDirect"); cimCollectionRuleDirect.CimInstanceProperties.Add(CimProperty.Create("ResourceClassName", "SMS_R_System", CimFlags.Key)); cimCollectionRuleDirect.CimInstanceProperties.Add(CimProperty.Create("ResourceID", resourceId, CimFlags.Key)); var addMembershipRuleParameters = new CimMethodParametersCollection { CimMethodParameter.Create("collectionRule", cimCollectionRuleDirect, CimFlags.Parameter) }; var cimCollection = CIM.RunQuery("Select * FROM SMS_Collection WHERE CollectionID='" + collectionId + "'").FirstOrDefault(); cimSession.InvokeMethod(cimCollection, "AddMembershipRule", addMembershipRuleParameters); return true; } catch (Exception) { return false; } finally { cimSession?.Dispose(); } }
public (System.UInt32 retval, CIMConcreteJob outJob) RequestReplicationStateChange(System.UInt16?inRequestedState, System.DateTime?inTimeoutPeriod) { var parameters = new CimMethodParametersCollection(); if (inRequestedState.HasValue) { parameters.Add(CimMethodParameter.Create("RequestedState", inRequestedState.Value, CimFlags.None)); } if (inTimeoutPeriod.HasValue) { parameters.Add(CimMethodParameter.Create("TimeoutPeriod", inTimeoutPeriod.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "RequestReplicationStateChange", parameters); return((System.UInt32)result.ReturnValue.Value, (CIMConcreteJob)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Job"].Value)); }
public (System.UInt32 retval, System.String outGPOSession) Open(System.String inDomainController, System.String inPolicyStore) { var parameters = new CimMethodParametersCollection(); if (inDomainController != null) { parameters.Add(CimMethodParameter.Create("DomainController", inDomainController, CimType.String, inDomainController == null ? CimFlags.NullValue : CimFlags.None)); } if (inPolicyStore != null) { parameters.Add(CimMethodParameter.Create("PolicyStore", inPolicyStore, CimType.String, inPolicyStore == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Open", parameters); return((System.UInt32)result.ReturnValue.Value, (System.String)result.OutParameters["GPOSession"].Value); }
public System.UInt32 ChangeSecurityPermissions(System.UInt32?inOption, Win32SecurityDescriptor inSecurityDescriptor) { var parameters = new CimMethodParametersCollection(); if (inOption.HasValue) { parameters.Add(CimMethodParameter.Create("Option", inOption.Value, CimFlags.None)); } if (inSecurityDescriptor != null) { parameters.Add(CimMethodParameter.Create("SecurityDescriptor", inSecurityDescriptor.AsCimInstance(), CimType.Instance, inSecurityDescriptor == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "ChangeSecurityPermissions", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, CIMConcreteJob outJob) RevokeInteractiveSessionAccess(CIMComputerSystem inComputerSystem, System.String[] inTrustees) { var parameters = new CimMethodParametersCollection(); if (inComputerSystem != null) { parameters.Add(CimMethodParameter.Create("ComputerSystem", inComputerSystem.AsCimInstance(), CimType.Reference, inComputerSystem == null ? CimFlags.NullValue : CimFlags.None)); } if (inTrustees != null) { parameters.Add(CimMethodParameter.Create("Trustees", inTrustees, CimType.StringArray, inTrustees == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "RevokeInteractiveSessionAccess", parameters); return((System.UInt32)result.ReturnValue.Value, (CIMConcreteJob)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Job"].Value)); }
public System.UInt32 SuspendRoot(System.String inPath, System.Boolean?inSuspend) { var parameters = new CimMethodParametersCollection(); if (inPath != null) { parameters.Add(CimMethodParameter.Create("Path", inPath, CimType.String, inPath == null ? CimFlags.NullValue : CimFlags.None)); } if (inSuspend.HasValue) { parameters.Add(CimMethodParameter.Create("Suspend", inSuspend.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SuspendRoot", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, System.String outStopFileName) UncompressEx(System.Boolean?inRecursive, System.String inStartFileName) { var parameters = new CimMethodParametersCollection(); if (inRecursive.HasValue) { parameters.Add(CimMethodParameter.Create("Recursive", inRecursive.Value, CimFlags.None)); } if (inStartFileName != null) { parameters.Add(CimMethodParameter.Create("StartFileName", inStartFileName, CimType.String, inStartFileName == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "UncompressEx", parameters); return((System.UInt32)result.ReturnValue.Value, (System.String)result.OutParameters["StopFileName"].Value); }
public System.UInt32 TransitionOnline(System.UInt32?inFlags, System.String inPath) { var parameters = new CimMethodParametersCollection(); if (inFlags.HasValue) { parameters.Add(CimMethodParameter.Create("Flags", inFlags.Value, CimFlags.None)); } if (inPath != null) { parameters.Add(CimMethodParameter.Create("Path", inPath, CimType.String, inPath == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "TransitionOnline", parameters); return((System.UInt32)result.ReturnValue.Value); }
public System.UInt32 DeleteItems(System.UInt32?inFlags, System.String[] inPaths) { var parameters = new CimMethodParametersCollection(); if (inFlags.HasValue) { parameters.Add(CimMethodParameter.Create("Flags", inFlags.Value, CimFlags.None)); } if (inPaths != null) { parameters.Add(CimMethodParameter.Create("Paths", inPaths, CimType.StringArray, inPaths == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "DeleteItems", parameters); return((System.UInt32)result.ReturnValue.Value); }
public System.UInt32 Encrypt(System.Boolean?inEncrypt, System.UInt32?inFlags) { var parameters = new CimMethodParametersCollection(); if (inEncrypt.HasValue) { parameters.Add(CimMethodParameter.Create("Encrypt", inEncrypt.Value, CimFlags.None)); } if (inFlags.HasValue) { parameters.Add(CimMethodParameter.Create("Flags", inFlags.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Encrypt", parameters); return((System.UInt32)result.ReturnValue.Value); }
public System.UInt32 SetIPXFrameTypeNetworkPairs(System.UInt32[] inIPXFrameType, System.String[] inIPXNetworkNumber) { var parameters = new CimMethodParametersCollection(); if (inIPXFrameType != null) { parameters.Add(CimMethodParameter.Create("IPXFrameType", inIPXFrameType, CimType.UInt32Array, inIPXFrameType == null ? CimFlags.NullValue : CimFlags.None)); } if (inIPXNetworkNumber != null) { parameters.Add(CimMethodParameter.Create("IPXNetworkNumber", inIPXNetworkNumber, CimType.StringArray, inIPXNetworkNumber == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetIPXFrameTypeNetworkPairs", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, CIMConcreteJob outJob, IEnumerable <MsvmFeatureSettingData> outResultingFeatureSettings) AddFeatureSettings(CIMSettingData inAffectedConfiguration, System.String[] inFeatureSettings) { var parameters = new CimMethodParametersCollection(); if (inAffectedConfiguration != null) { parameters.Add(CimMethodParameter.Create("AffectedConfiguration", inAffectedConfiguration.AsCimInstance(), CimType.Reference, inAffectedConfiguration == null ? CimFlags.NullValue : CimFlags.None)); } if (inFeatureSettings != null) { parameters.Add(CimMethodParameter.Create("FeatureSettings", inFeatureSettings, CimType.StringArray, inFeatureSettings == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "AddFeatureSettings", parameters); return((System.UInt32)result.ReturnValue.Value, (CIMConcreteJob)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Job"].Value), (IEnumerable <MsvmFeatureSettingData>)InfrastuctureObjectScope.Mapper.CreateMany <MsvmFeatureSettingData>(InfrastuctureObjectScope, (IEnumerable <CimInstance>)result.OutParameters["ResultingFeatureSettings"].Value)); }
public System.UInt32 SetDynamicDNSRegistration(System.Boolean?inDomainDNSRegistrationEnabled, System.Boolean?inFullDNSRegistrationEnabled) { var parameters = new CimMethodParametersCollection(); if (inDomainDNSRegistrationEnabled.HasValue) { parameters.Add(CimMethodParameter.Create("DomainDNSRegistrationEnabled", inDomainDNSRegistrationEnabled.Value, CimFlags.None)); } if (inFullDNSRegistrationEnabled.HasValue) { parameters.Add(CimMethodParameter.Create("FullDNSRegistrationEnabled", inFullDNSRegistrationEnabled.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetDynamicDNSRegistration", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, CIMConcreteJob outJob) ModifyPoolSettings(CIMResourcePool inChildPool, System.String inPoolSettings) { var parameters = new CimMethodParametersCollection(); if (inChildPool != null) { parameters.Add(CimMethodParameter.Create("ChildPool", inChildPool.AsCimInstance(), CimType.Reference, inChildPool == null ? CimFlags.NullValue : CimFlags.None)); } if (inPoolSettings != null) { parameters.Add(CimMethodParameter.Create("PoolSettings", inPoolSettings, CimType.String, inPoolSettings == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "ModifyPoolSettings", parameters); return((System.UInt32)result.ReturnValue.Value, (CIMConcreteJob)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Job"].Value)); }
public (System.UInt32 retval, System.String outShadowID) Create(System.String inContext, System.String inVolume) { var parameters = new CimMethodParametersCollection(); if (inContext != null) { parameters.Add(CimMethodParameter.Create("Context", inContext, CimType.String, inContext == null ? CimFlags.NullValue : CimFlags.None)); } if (inVolume != null) { parameters.Add(CimMethodParameter.Create("Volume", inVolume, CimType.String, inVolume == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Create", parameters); return((System.UInt32)result.ReturnValue.Value, (System.String)result.OutParameters["ShadowID"].Value); }
public System.UInt32 SetPowerState(System.UInt16?inPowerState, System.DateTime?inTime) { var parameters = new CimMethodParametersCollection(); if (inPowerState.HasValue) { parameters.Add(CimMethodParameter.Create("PowerState", inPowerState.Value, CimFlags.None)); } if (inTime.HasValue) { parameters.Add(CimMethodParameter.Create("Time", inTime.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetPowerState", parameters); return((System.UInt32)result.ReturnValue.Value); }
public System.UInt32 RenameByObject(MSFTPrinter inInputObject, System.String inNewName) { var parameters = new CimMethodParametersCollection(); if (inInputObject != null) { parameters.Add(CimMethodParameter.Create("InputObject", inInputObject.AsCimInstance(), CimType.Instance, inInputObject == null ? CimFlags.NullValue : CimFlags.None)); } if (inNewName != null) { parameters.Add(CimMethodParameter.Create("NewName", inNewName, CimType.String, inNewName == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "RenameByObject", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, MSFTDASiteTableEntry outOutputObject) Rename(System.String inNewName, System.Boolean?inPassThru) { var parameters = new CimMethodParametersCollection(); if (inNewName != null) { parameters.Add(CimMethodParameter.Create("NewName", inNewName, CimType.String, inNewName == null ? CimFlags.NullValue : CimFlags.None)); } if (inPassThru.HasValue) { parameters.Add(CimMethodParameter.Create("PassThru", inPassThru.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Rename", parameters); return((System.UInt32)result.ReturnValue.Value, (MSFTDASiteTableEntry)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["OutputObject"].Value)); }
public System.UInt32 SetWINSServer(System.String inWINSPrimaryServer, System.String inWINSSecondaryServer) { var parameters = new CimMethodParametersCollection(); if (inWINSPrimaryServer != null) { parameters.Add(CimMethodParameter.Create("WINSPrimaryServer", inWINSPrimaryServer, CimType.String, inWINSPrimaryServer == null ? CimFlags.NullValue : CimFlags.None)); } if (inWINSSecondaryServer != null) { parameters.Add(CimMethodParameter.Create("WINSSecondaryServer", inWINSSecondaryServer, CimType.String, inWINSSecondaryServer == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetWINSServer", parameters); return((System.UInt32)result.ReturnValue.Value); }
public System.UInt32 EnableStatic(System.String[] inIPAddress, System.String[] inSubnetMask) { var parameters = new CimMethodParametersCollection(); if (inIPAddress != null) { parameters.Add(CimMethodParameter.Create("IPAddress", inIPAddress, CimType.StringArray, inIPAddress == null ? CimFlags.NullValue : CimFlags.None)); } if (inSubnetMask != null) { parameters.Add(CimMethodParameter.Create("SubnetMask", inSubnetMask, CimType.StringArray, inSubnetMask == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "EnableStatic", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, System.String outInformation, CIMConcreteJob outJob) GetVHDSetInformation(System.UInt32[] inAdditionalInformation, System.String inVHDSetPath) { var parameters = new CimMethodParametersCollection(); if (inAdditionalInformation != null) { parameters.Add(CimMethodParameter.Create("AdditionalInformation", inAdditionalInformation, CimType.UInt32Array, inAdditionalInformation == null ? CimFlags.NullValue : CimFlags.None)); } if (inVHDSetPath != null) { parameters.Add(CimMethodParameter.Create("VHDSetPath", inVHDSetPath, CimType.String, inVHDSetPath == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "GetVHDSetInformation", parameters); return((System.UInt32)result.ReturnValue.Value, (System.String)result.OutParameters["Information"].Value, (CIMConcreteJob)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Job"].Value)); }
public (System.UInt32 retval, MsvmMountedStorageImage outImage) FindMountedStorageImageInstance(System.UInt16?inCriterionType, System.String inSelectionCriterion) { var parameters = new CimMethodParametersCollection(); if (inCriterionType.HasValue) { parameters.Add(CimMethodParameter.Create("CriterionType", inCriterionType.Value, CimFlags.None)); } if (inSelectionCriterion != null) { parameters.Add(CimMethodParameter.Create("SelectionCriterion", inSelectionCriterion, CimType.String, inSelectionCriterion == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "FindMountedStorageImageInstance", parameters); return((System.UInt32)result.ReturnValue.Value, (MsvmMountedStorageImage)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Image"].Value)); }
public System.UInt32 SetAbsolutePosition(System.Int32?inHorizontalPosition, System.Int32?inVerticalPosition) { var parameters = new CimMethodParametersCollection(); if (inHorizontalPosition.HasValue) { parameters.Add(CimMethodParameter.Create("HorizontalPosition", inHorizontalPosition.Value, CimFlags.None)); } if (inVerticalPosition.HasValue) { parameters.Add(CimMethodParameter.Create("VerticalPosition", inVerticalPosition.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetAbsolutePosition", parameters); return((System.UInt32)result.ReturnValue.Value); }
public System.UInt32 SetButtonState(System.UInt32?inButtonIndex, System.Boolean?inIsDown) { var parameters = new CimMethodParametersCollection(); if (inButtonIndex.HasValue) { parameters.Add(CimMethodParameter.Create("ButtonIndex", inButtonIndex.Value, CimFlags.None)); } if (inIsDown.HasValue) { parameters.Add(CimMethodParameter.Create("IsDown", inIsDown.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetButtonState", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, MSFTNetAdapterLsoSettingData outcmdletOutput) Enable(System.Boolean?inIPv4, System.Boolean?inIPv6) { var parameters = new CimMethodParametersCollection(); if (inIPv4.HasValue) { parameters.Add(CimMethodParameter.Create("IPv4", inIPv4.Value, CimFlags.None)); } if (inIPv6.HasValue) { parameters.Add(CimMethodParameter.Create("IPv6", inIPv6.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Enable", parameters); return((System.UInt32)result.ReturnValue.Value, (MSFTNetAdapterLsoSettingData)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["cmdletOutput"].Value)); }
public System.UInt32 SetGateways(System.String[] inDefaultIPGateway, System.UInt16[] inGatewayCostMetric) { var parameters = new CimMethodParametersCollection(); if (inDefaultIPGateway != null) { parameters.Add(CimMethodParameter.Create("DefaultIPGateway", inDefaultIPGateway, CimType.StringArray, inDefaultIPGateway == null ? CimFlags.NullValue : CimFlags.None)); } if (inGatewayCostMetric != null) { parameters.Add(CimMethodParameter.Create("GatewayCostMetric", inGatewayCostMetric, CimType.UInt16Array, inGatewayCostMetric == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetGateways", parameters); return((System.UInt32)result.ReturnValue.Value); }
public System.UInt32 SuspendJobByPrinterObject(System.UInt32?inID, MSFTPrinter inPrinterObject) { var parameters = new CimMethodParametersCollection(); if (inID.HasValue) { parameters.Add(CimMethodParameter.Create("ID", inID.Value, CimFlags.None)); } if (inPrinterObject != null) { parameters.Add(CimMethodParameter.Create("PrinterObject", inPrinterObject.AsCimInstance(), CimType.Instance, inPrinterObject == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SuspendJobByPrinterObject", parameters); return((System.UInt32)result.ReturnValue.Value); }
public (System.UInt32 retval, System.UInt32?outIsolationType) QueryIsolationType(System.UInt32?inInterfaceIndex, System.String inRemoteAddress) { var parameters = new CimMethodParametersCollection(); if (inInterfaceIndex.HasValue) { parameters.Add(CimMethodParameter.Create("InterfaceIndex", inInterfaceIndex.Value, CimFlags.None)); } if (inRemoteAddress != null) { parameters.Add(CimMethodParameter.Create("RemoteAddress", inRemoteAddress, CimType.String, inRemoteAddress == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "QueryIsolationType", parameters); return((System.UInt32)result.ReturnValue.Value, (System.UInt32? )result.OutParameters["IsolationType"].Value); }
public (System.UInt32 retval, System.UInt64?outrequiredVideoMemory) CalculateVideoMemoryRequirements(System.UInt32?inmonitorResolution, System.UInt32?innumberOfMonitors) { var parameters = new CimMethodParametersCollection(); if (inmonitorResolution.HasValue) { parameters.Add(CimMethodParameter.Create("monitorResolution", inmonitorResolution.Value, CimFlags.None)); } if (innumberOfMonitors.HasValue) { parameters.Add(CimMethodParameter.Create("numberOfMonitors", innumberOfMonitors.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "CalculateVideoMemoryRequirements", parameters); return((System.UInt32)result.ReturnValue.Value, (System.UInt64? )result.OutParameters["requiredVideoMemory"].Value); }
public (System.UInt32 retval, CIMConcreteJob outJob) CompactVirtualHardDisk(System.UInt16?inMode, System.String inPath) { var parameters = new CimMethodParametersCollection(); if (inMode.HasValue) { parameters.Add(CimMethodParameter.Create("Mode", inMode.Value, CimFlags.None)); } if (inPath != null) { parameters.Add(CimMethodParameter.Create("Path", inPath, CimType.String, inPath == null ? CimFlags.NullValue : CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "CompactVirtualHardDisk", parameters); return((System.UInt32)result.ReturnValue.Value, (CIMConcreteJob)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Job"].Value)); }
public System.UInt32 Dismount(System.Boolean?inForce, System.Boolean?inPermanent) { var parameters = new CimMethodParametersCollection(); if (inForce.HasValue) { parameters.Add(CimMethodParameter.Create("Force", inForce.Value, CimFlags.None)); } if (inPermanent.HasValue) { parameters.Add(CimMethodParameter.Create("Permanent", inPermanent.Value, CimFlags.None)); } var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Dismount", parameters); return((System.UInt32)result.ReturnValue.Value); }
/// <summary> /// Removes a computer from a collection. /// </summary> /// <param name="computerName">The name of the computer.</param> /// <param name="collectionId">The ID of the collection.</param> /// <returns>returns true if the move succeeded, false otherwise.</returns> public static bool RemoveComputerFromCollection(string computerName, string collectionId) { CimSession cimSession = null; try { var resourceId = uint.Parse(GetComputerByName(computerName).ResourceID); cimSession = CimSession.Create(Properties.Resources.SCCMServerName); var cimCollectionRuleDirect = new CimInstance("SMS_CollectionRuleDirect"); cimCollectionRuleDirect.CimInstanceProperties.Add(CimProperty.Create("ResourceClassName", "SMS_R_System", CimFlags.Key)); cimCollectionRuleDirect.CimInstanceProperties.Add(CimProperty.Create("ResourceID", resourceId, CimFlags.Key)); var addMembershipRuleParameters = new CimMethodParametersCollection { CimMethodParameter.Create("collectionRule", cimCollectionRuleDirect, CimFlags.Parameter) }; var cimCollection = CIM.RunQuery("Select * FROM SMS_Collection WHERE CollectionID='" + collectionId + "'").FirstOrDefault(); cimSession.InvokeMethod(cimCollection, "DeleteMemberShipRule", addMembershipRuleParameters); return true; } catch (Exception ex) { throw new Exception("An error occurred in RemoveComputerFromCollection.\n" + ex.Message); } finally { cimSession?.Dispose(); } }
public void InvokeMethodAsync(string namespaceName, CimInstance instance, string methodName, CimMethodParametersCollection methodParameters) { object[] enableMethodResultStreaming = new object[1]; enableMethodResultStreaming[0] = this.options.EnableMethodResultStreaming; DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, enableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = instance; this.operationName = Strings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add("namespaceName", namespaceName); this.operationParameters.Add("instance", instance); this.operationParameters.Add("methodName", methodName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults<CimMethodResultBase> cimAsyncMultipleResult = this.session.InvokeMethodAsync(namespaceName, instance, methodName, methodParameters, this.options); this.ConsumeCimInvokeMethodResultAsync(cimAsyncMultipleResult, instance.CimSystemProperties.ClassName, methodName, new CimResultContext(instance)); }
/// <summary> /// Invoke static method of a given class asynchronously /// </summary> /// <param name="namespaceName"></param> /// <param name="className"></param> /// <param name="methodName"></param> /// <param name="methodParameters"></param> public void InvokeMethodAsync( string namespaceName, string className, string methodName, CimMethodParametersCollection methodParameters) { DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = null; this.operationName = Strings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); this.operationParameters.Add(@"methodName", methodName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults<CimMethodResultBase> asyncResult = this.session.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, this.options); string errorSource = String.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); ConsumeCimInvokeMethodResultAsync(asyncResult, className, methodName, new CimResultContext(errorSource)); }
public void InvokeMethodAsync(string namespaceName, string className, string methodName, CimMethodParametersCollection methodParameters) { object[] enableMethodResultStreaming = new object[1]; enableMethodResultStreaming[0] = this.options.EnableMethodResultStreaming; DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, enableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = null; this.operationName = Strings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add("namespaceName", namespaceName); this.operationParameters.Add("className", className); this.operationParameters.Add("methodName", methodName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults<CimMethodResultBase> cimAsyncMultipleResult = this.session.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, this.options); object[] objArray = new object[2]; objArray[0] = namespaceName; objArray[1] = className; string str = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", objArray); this.ConsumeCimInvokeMethodResultAsync(cimAsyncMultipleResult, className, methodName, new CimResultContext(str)); }
// 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; }
/// <summary> /// Invoke method of a given cim instance asynchronously /// </summary> /// <param name="namespaceName"></param> /// <param name="instance"></param> /// <param name="methodName"></param> /// <param name="methodParameters"></param> public void InvokeMethodAsync( string namespaceName, CimInstance instance, string methodName, CimMethodParametersCollection methodParameters) { Debug.Assert(instance != null, "Caller should verify that instance != NULL."); DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = instance; this.operationName = Strings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); this.operationParameters.Add(@"methodName", methodName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults<CimMethodResultBase> asyncResult = this.session.InvokeMethodAsync(namespaceName, instance, methodName, methodParameters, this.options); ConsumeCimInvokeMethodResultAsync(asyncResult, instance.CimSystemProperties.ClassName, methodName, new CimResultContext(instance)); }
internal CimMethodResult(CimInstance backingInstance) { this._backingMethodParametersCollection = new CimMethodParametersCollection(backingInstance); }
internal static CimMethodParametersCollection InvokeMethodCore( CimSession cimSession, string cimNamespace, string cimClassName, out string cimMethodName, out CimInstance inputInstance) { CimMethodParametersCollection methodParameters = new CimMethodParametersCollection(); inputInstance = null; cimMethodName = null; bool isStaticMethod = false; try { CimClass cimClass = cimSession.GetClass(cimNamespace, cimClassName); // Print Methods foreach (CimMethodDeclaration methodDecl in cimClass.CimClassMethods) { Console.WriteLine("Method Name = " + methodDecl.Name); } cimMethodName = DotNetSample.GetName("Method Name"); if (cimClass.CimClassMethods[cimMethodName].Qualifiers["static"] != null) { isStaticMethod = true; } foreach (CimMethodParameterDeclaration methodParameter in cimClass.CimClassMethods[cimMethodName].Parameters) { bool bInQualifier = (methodParameter.Qualifiers["In"] != null); if (bInQualifier) { Console.Write("Please type value for Parameter '" + methodParameter.Name + "' of Type:({0}) ", methodParameter.CimType); string parameterValue = Console.ReadLine(); if (!String.IsNullOrEmpty(parameterValue)) { methodParameters.Add(CimMethodParameter.Create(methodParameter.Name, parameterValue, methodParameter.CimType, 0)); } } } // Get the instance if method is not static if (!isStaticMethod) { // Get the instances for this class. List<CimInstance> list = GetAndPrintInstances(cimSession, cimNamespace, cimClassName); if (list == null || list.Count == 0) { Console.WriteLine("InvokeMethodCore operation not performed"); return null; } while (true) { Console.WriteLine("On which instance do you want to invoke the method"); string instanceId = Console.ReadLine(); int result; if (String.IsNullOrEmpty(instanceId) || int.TryParse(instanceId, out result) == false || result >= list.Count) { Console.WriteLine("Please type the instance Id in the range {0} to {1}", 0, list.Count - 1); } else { inputInstance = (CimInstance)list[result]; break; } } } } catch (CimException exception) { Console.WriteLine("Unable to get schema for class '" + cimClassName + "' in namespace " + cimNamespace); PrintCimException(exception); return null; } return methodParameters; }
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; }
public CimMethodResult InvokeMethod(string namespaceName, string className, string methodName, CimMethodParametersCollection methodParameters) { return this.InvokeMethod(namespaceName, className, methodName, methodParameters, null); }
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"); } }
private CimMethodParametersCollection CreateParametersCollection(IDictionary parameters, CimClass cimClass, CimInstance cimInstance, string methodName) { DebugHelper.WriteLogEx(); CimMethodParametersCollection cimMethodParametersCollection = null; if (parameters != null) { if (parameters.Count != 0) { cimMethodParametersCollection = new CimMethodParametersCollection(); IDictionaryEnumerator enumerator = parameters.GetEnumerator(); while (enumerator.MoveNext()) { string str = enumerator.Key.ToString(); CimFlags cimFlag = CimFlags.In; object baseObject = base.GetBaseObject(enumerator.Value); object[] objArray = new object[3]; objArray[0] = str; objArray[1] = baseObject; objArray[2] = cimFlag; DebugHelper.WriteLog("Create parameter name= {0}, value= {1}, flags= {2}.", 4, objArray); CimMethodParameter cimMethodParameter = null; CimMethodDeclaration item = null; string className = null; if (cimClass == null) { if (cimInstance != null) { className = cimInstance.CimClass.CimSystemProperties.ClassName; item = cimInstance.CimClass.CimClassMethods[methodName]; } } else { className = cimClass.CimSystemProperties.ClassName; item = cimClass.CimClassMethods[methodName]; if (item == null) { object[] objArray1 = new object[2]; objArray1[0] = methodName; objArray1[1] = className; throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, Strings.InvalidMethod, objArray1)); } } if (item == null) { if (baseObject != null) { CimType cimType = CimType.Unknown; object referenceOrReferenceArrayObject = base.GetReferenceOrReferenceArrayObject(baseObject, ref cimType); if (referenceOrReferenceArrayObject == null) { cimMethodParameter = CimMethodParameter.Create(str, baseObject, cimFlag); } else { cimMethodParameter = CimMethodParameter.Create(str, referenceOrReferenceArrayObject, cimType, cimFlag); } } else { cimMethodParameter = CimMethodParameter.Create(str, baseObject, CimType.String, cimFlag); } } else { CimMethodParameterDeclaration cimMethodParameterDeclaration = item.Parameters[str]; if (cimMethodParameterDeclaration != null) { cimMethodParameter = CimMethodParameter.Create(str, baseObject, cimMethodParameterDeclaration.CimType, cimFlag); } else { object[] objArray2 = new object[3]; objArray2[0] = str; objArray2[1] = methodName; objArray2[2] = className; throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, Strings.InvalidMethodParameter, objArray2)); } } if (cimMethodParameter == null) { continue; } cimMethodParametersCollection.Add(cimMethodParameter); } return cimMethodParametersCollection; } else { return cimMethodParametersCollection; } } else { return cimMethodParametersCollection; } }
public CimAsyncResult<CimMethodResult> InvokeMethodAsync(CimInstance instance, string methodName, CimMethodParametersCollection methodParameters) { if (instance != null) { if (instance.CimSystemProperties.Namespace != null) { return this.InvokeMethodAsync(instance.CimSystemProperties.Namespace, instance, methodName, methodParameters); } else { throw new ArgumentNullException("instance", System.Management.Automation.Strings.CimInstanceNamespaceIsNull); } } else { throw new ArgumentNullException("instance"); } }
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; }
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"); } }
public CimAsyncResult<CimMethodResult> InvokeMethodAsync(string namespaceName, string className, string methodName, CimMethodParametersCollection methodParameters) { IObservable<CimMethodResultBase> observable = this.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, null); IObservable<CimMethodResult> convertingObservable = new ConvertingObservable<CimMethodResultBase, CimMethodResult>(observable); return new CimAsyncResult<CimMethodResult>(convertingObservable); }
/// <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; }
/// <summary> /// <para> /// Create <see cref="CimMethodParametersCollection"/> with given key properties. /// And/or <see cref="CimClass"/> object. /// </para> /// </summary> /// <param name="parameters"></param> /// <param name="cimClass"></param> /// <param name="cimInstance"></param> /// <param name="methodName"></param> /// <returns></returns> /// <exception cref="ArgumentNullException">See CimProperty.Create</exception> /// <exception cref="ArgumentException">CimProperty.Create</exception> private CimMethodParametersCollection CreateParametersCollection( IDictionary parameters, CimClass cimClass, CimInstance cimInstance, string methodName) { DebugHelper.WriteLogEx(); CimMethodParametersCollection collection = null; if (parameters == null) { return collection; } else if (parameters.Count == 0) { return collection; } collection = new CimMethodParametersCollection(); IDictionaryEnumerator enumerator = parameters.GetEnumerator(); while (enumerator.MoveNext()) { string parameterName = enumerator.Key.ToString(); CimFlags parameterFlags = CimFlags.In; object parameterValue = GetBaseObject(enumerator.Value); DebugHelper.WriteLog(@"Create parameter name= {0}, value= {1}, flags= {2}.", 4, parameterName, parameterValue, parameterFlags); CimMethodParameter parameter = null; CimMethodDeclaration declaration = null; string className = null; if (cimClass != null) { className = cimClass.CimSystemProperties.ClassName; declaration = cimClass.CimClassMethods[methodName]; if (declaration == null) { throw new ArgumentException(String.Format( CultureInfo.CurrentUICulture, Strings.InvalidMethod, methodName, className)); } } else if (cimInstance != null) { className = cimInstance.CimClass.CimSystemProperties.ClassName; declaration = cimInstance.CimClass.CimClassMethods[methodName]; } if (declaration != null) { CimMethodParameterDeclaration paramDeclaration = declaration.Parameters[parameterName]; if (paramDeclaration == null) { throw new ArgumentException(String.Format( CultureInfo.CurrentUICulture, Strings.InvalidMethodParameter, parameterName, methodName, className)); } parameter = CimMethodParameter.Create( parameterName, parameterValue, paramDeclaration.CimType, parameterFlags); // FIXME: check in/out qualifier // parameterFlags = paramDeclaration.Qualifiers; } else { if (parameterValue == null) { // try the best to get the type while value is null parameter = CimMethodParameter.Create( parameterName, parameterValue, CimType.String, parameterFlags); } else { CimType referenceType = CimType.Unknown; object referenceObject = GetReferenceOrReferenceArrayObject(parameterValue, ref referenceType); if (referenceObject != null) { parameter = CimMethodParameter.Create( parameterName, referenceObject, referenceType, parameterFlags); } else { parameter = CimMethodParameter.Create( parameterName, parameterValue, parameterFlags); } } } if (parameter != null) collection.Add(parameter); } return collection; }