Esempio n. 1
0
        /// <summary>
        /// Executes static method of WMI class
        /// </summary>
        /// <typeparam name="T">Return type</typeparam>
        /// <typeparam name="TClass">WMI Class type</typeparam>
        /// <param name="methodName">Name of WMI method to be executed</param>
        /// <param name="methodParameters">WMI Method parameters</param>
        /// <returns>Method execution result of type <c>T</c></returns>
        public T InvokeStaticMethod <T, TClass>(string methodName, IDictionary <string, object> methodParameters)
        {
            var wmiClass   = typeof(TClass);
            var parameters = new CimMethodParametersCollection();

            foreach (var methodParameter in methodParameters)
            {
                var val = methodParameter.Value;
                if (val == null)
                {
                    continue;
                }
                parameters.Add(CimMethodParameter.Create(methodParameter.Key, val, CimFlags.In));
            }

            return((T)_connection.InvokeMethod(
                       _nameSpace,
                       wmiClass.GetCustomAttribute <WmiClassAttribute>()?
                       .Name ?? wmiClass.Name,
                       methodName,
                       parameters).ReturnValue.Value);
        }
Esempio n. 2
0
 public (System.UInt32 retval, MSFTNetAdapterChecksumOffloadSettingData outcmdletOutput) Disable(System.Boolean? inIpIPv4, System.UInt32? inRxTxControl, System.Boolean? inTcpIPv4, System.Boolean? inTcpIPv6, System.Boolean? inUdpIPv4, System.Boolean? inUdpIPv6)
 {
     var parameters = new CimMethodParametersCollection();
     if (inIpIPv4.HasValue)
         parameters.Add(CimMethodParameter.Create("IpIPv4", inIpIPv4.Value, CimFlags.None));
     if (inRxTxControl.HasValue)
         parameters.Add(CimMethodParameter.Create("RxTxControl", inRxTxControl.Value, CimFlags.None));
     if (inTcpIPv4.HasValue)
         parameters.Add(CimMethodParameter.Create("TcpIPv4", inTcpIPv4.Value, CimFlags.None));
     if (inTcpIPv6.HasValue)
         parameters.Add(CimMethodParameter.Create("TcpIPv6", inTcpIPv6.Value, CimFlags.None));
     if (inUdpIPv4.HasValue)
         parameters.Add(CimMethodParameter.Create("UdpIPv4", inUdpIPv4.Value, CimFlags.None));
     if (inUdpIPv6.HasValue)
         parameters.Add(CimMethodParameter.Create("UdpIPv6", inUdpIPv6.Value, CimFlags.None));
     var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Disable", parameters);
     return ((System.UInt32)result.ReturnValue.Value, (MSFTNetAdapterChecksumOffloadSettingData)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["cmdletOutput"].Value));
 }
Esempio n. 3
0
        static void Main(string[] args)
        {
            // Create a CimSession with the remote system
            CimSessionOptions options = new DComSessionOptions();
            //options.AddDestinationCredentials(cimCreds);
            CimSession session = CimSession.Create("localhost", options);

            // Create a CimMethodParametersCollection to pass to method invocation
            CimMethodParametersCollection collection = new CimMethodParametersCollection();

            collection.Add(CimMethodParameter.Create("CommandLine", "calc.exe", CimFlags.None));

            // Invoke the Win32_Process classes Create method to start a calc.exe process on a remote system
            CimMethodResult result = session.InvokeMethod("root/cimv2", "Win32_Process", "Create", collection);

            if (result.ReturnValue.ToString() == "0")
            {
            }
            else
            {
            }

            session.Dispose();
        }
Esempio n. 4
0
        public (System.UInt32 retval, MSFTNetBranchCacheCache outcmdletOutput) Set_BCCacheByPath(System.Boolean?inDefragment, System.Boolean?inForce, System.String inMoveTo, System.Boolean?inPassThru, System.String inPath, System.UInt32?inPercentage, System.UInt64?inSizeBytes)
        {
            var parameters = new CimMethodParametersCollection();

            if (inDefragment.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Defragment", inDefragment.Value, CimFlags.None));
            }
            if (inForce.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Force", inForce.Value, CimFlags.None));
            }
            if (inMoveTo != null)
            {
                parameters.Add(CimMethodParameter.Create("MoveTo", inMoveTo, CimType.String, inMoveTo == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPassThru.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PassThru", inPassThru.Value, CimFlags.None));
            }
            if (inPath != null)
            {
                parameters.Add(CimMethodParameter.Create("Path", inPath, CimType.String, inPath == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPercentage.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Percentage", inPercentage.Value, CimFlags.None));
            }
            if (inSizeBytes.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("SizeBytes", inSizeBytes.Value, CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Set_BCCacheByPath", parameters);

            return((System.UInt32)result.ReturnValue.Value, (MSFTNetBranchCacheCache)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["cmdletOutput"].Value));
        }
Esempio n. 5
0
        public System.UInt32 Create(Win32SecurityDescriptor inAccess, System.String inDescription, System.UInt32?inMaximumAllowed, System.String inName, System.String inPassword, System.String inPath, System.UInt32?inType)
        {
            var parameters = new CimMethodParametersCollection();

            if (inAccess != null)
            {
                parameters.Add(CimMethodParameter.Create("Access", inAccess.AsCimInstance(), CimType.Instance, inAccess == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inDescription != null)
            {
                parameters.Add(CimMethodParameter.Create("Description", inDescription, CimType.String, inDescription == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inMaximumAllowed.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("MaximumAllowed", inMaximumAllowed.Value, CimFlags.None));
            }
            if (inName != null)
            {
                parameters.Add(CimMethodParameter.Create("Name", inName, CimType.String, inName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPassword != null)
            {
                parameters.Add(CimMethodParameter.Create("Password", inPassword, CimType.String, inPassword == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPath != null)
            {
                parameters.Add(CimMethodParameter.Create("Path", inPath, CimType.String, inPath == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inType.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Type", inType.Value, CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Create", parameters);

            return((System.UInt32)result.ReturnValue.Value);
        }
Esempio n. 6
0
        public System.UInt32 SetByPrinterName(System.Boolean?inCollate, System.Boolean?inColor, System.String inComputerName, System.UInt32?inDuplexingMode, System.UInt32?inPaperSize, System.String inPrinterName, System.String inPrintTicketXML)
        {
            var parameters = new CimMethodParametersCollection();

            if (inCollate.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Collate", inCollate.Value, CimFlags.None));
            }
            if (inColor.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Color", inColor.Value, CimFlags.None));
            }
            if (inComputerName != null)
            {
                parameters.Add(CimMethodParameter.Create("ComputerName", inComputerName, CimType.String, inComputerName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inDuplexingMode.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("DuplexingMode", inDuplexingMode.Value, CimFlags.None));
            }
            if (inPaperSize.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PaperSize", inPaperSize.Value, CimFlags.None));
            }
            if (inPrinterName != null)
            {
                parameters.Add(CimMethodParameter.Create("PrinterName", inPrinterName, CimType.String, inPrinterName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPrintTicketXML != null)
            {
                parameters.Add(CimMethodParameter.Create("PrintTicketXML", inPrintTicketXML, CimType.String, inPrintTicketXML == null ? CimFlags.NullValue : CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "SetByPrinterName", parameters);

            return((System.UInt32)result.ReturnValue.Value);
        }
Esempio n. 7
0
        public (System.UInt32 retval, CIMConcreteJob outJob, System.UInt32?outRoundTripTime) TestNetworkConnection(System.UInt32?inIsolationId, System.Boolean?inIsSender, System.String inReceiverIP, System.String inReceiverMac, System.String inSenderIP, System.UInt32?inSequenceNumber, MsvmEthernetPortAllocationSettingData inTargetNetworkAdapter)
        {
            var parameters = new CimMethodParametersCollection();

            if (inIsolationId.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("IsolationId", inIsolationId.Value, CimFlags.None));
            }
            if (inIsSender.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("IsSender", inIsSender.Value, CimFlags.None));
            }
            if (inReceiverIP != null)
            {
                parameters.Add(CimMethodParameter.Create("ReceiverIP", inReceiverIP, CimType.String, inReceiverIP == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inReceiverMac != null)
            {
                parameters.Add(CimMethodParameter.Create("ReceiverMac", inReceiverMac, CimType.String, inReceiverMac == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inSenderIP != null)
            {
                parameters.Add(CimMethodParameter.Create("SenderIP", inSenderIP, CimType.String, inSenderIP == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inSequenceNumber.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("SequenceNumber", inSequenceNumber.Value, CimFlags.None));
            }
            if (inTargetNetworkAdapter != null)
            {
                parameters.Add(CimMethodParameter.Create("TargetNetworkAdapter", inTargetNetworkAdapter.AsCimInstance(), CimType.Reference, inTargetNetworkAdapter == null ? CimFlags.NullValue : CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "TestNetworkConnection", parameters);

            return((System.UInt32)result.ReturnValue.Value, (CIMConcreteJob)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["Job"].Value), (System.UInt32? )result.OutParameters["RoundTripTime"].Value);
        }
Esempio n. 8
0
        public System.UInt32 Publish_BCFileHashes(System.Boolean?inForce, System.String[] inPath, System.Boolean?inRecurse, System.String inReferenceFile, System.Boolean?inStageData, System.String inStagingPath, System.UInt32?inUseVersion)
        {
            var parameters = new CimMethodParametersCollection();

            if (inForce.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Force", inForce.Value, CimFlags.None));
            }
            if (inPath != null)
            {
                parameters.Add(CimMethodParameter.Create("Path", inPath, CimType.StringArray, inPath == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inRecurse.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Recurse", inRecurse.Value, CimFlags.None));
            }
            if (inReferenceFile != null)
            {
                parameters.Add(CimMethodParameter.Create("ReferenceFile", inReferenceFile, CimType.String, inReferenceFile == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inStageData.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("StageData", inStageData.Value, CimFlags.None));
            }
            if (inStagingPath != null)
            {
                parameters.Add(CimMethodParameter.Create("StagingPath", inStagingPath, CimType.String, inStagingPath == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inUseVersion.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("UseVersion", inUseVersion.Value, CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Publish_BCFileHashes", parameters);

            return((System.UInt32)result.ReturnValue.Value);
        }
Esempio n. 9
0
        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);
            }
        }
Esempio n. 10
0
        public (System.UInt32 retval, IEnumerable <MSFTNetRoute> outCmdletOutput) Create(System.UInt16?inAddressFamily, System.UInt32?inCompartmentId, System.String inDestinationPrefix, System.String inInterfaceAlias, System.UInt32?inInterfaceIndex, System.String inNextHop, System.Boolean?inPassThru, System.String inPolicyStore, System.DateTime?inPreferredLifetime, System.UInt16?inProtocol, System.Byte?inPublish, System.UInt16?inRouteMetric, System.DateTime?inValidLifetime)
        {
            var parameters = new CimMethodParametersCollection();

            if (inAddressFamily.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("AddressFamily", inAddressFamily.Value, CimFlags.None));
            }
            if (inCompartmentId.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("CompartmentId", inCompartmentId.Value, CimFlags.None));
            }
            if (inDestinationPrefix != null)
            {
                parameters.Add(CimMethodParameter.Create("DestinationPrefix", inDestinationPrefix, CimType.String, inDestinationPrefix == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inInterfaceAlias != null)
            {
                parameters.Add(CimMethodParameter.Create("InterfaceAlias", inInterfaceAlias, CimType.String, inInterfaceAlias == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inInterfaceIndex.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("InterfaceIndex", inInterfaceIndex.Value, CimFlags.None));
            }
            if (inNextHop != null)
            {
                parameters.Add(CimMethodParameter.Create("NextHop", inNextHop, CimType.String, inNextHop == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPassThru.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PassThru", inPassThru.Value, CimFlags.None));
            }
            if (inPolicyStore != null)
            {
                parameters.Add(CimMethodParameter.Create("PolicyStore", inPolicyStore, CimType.String, inPolicyStore == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPreferredLifetime.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PreferredLifetime", inPreferredLifetime.Value, CimFlags.None));
            }
            if (inProtocol.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Protocol", inProtocol.Value, CimFlags.None));
            }
            if (inPublish.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Publish", inPublish.Value, CimFlags.None));
            }
            if (inRouteMetric.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("RouteMetric", inRouteMetric.Value, CimFlags.None));
            }
            if (inValidLifetime.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("ValidLifetime", inValidLifetime.Value, CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Create", parameters);

            return((System.UInt32)result.ReturnValue.Value, (IEnumerable <MSFTNetRoute>)InfrastuctureObjectScope.Mapper.CreateMany <MSFTNetRoute>(InfrastuctureObjectScope, (IEnumerable <CimInstance>)result.OutParameters["CmdletOutput"].Value));
        }
Esempio n. 11
0
        /// <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;
        }
        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;
        }
Esempio n. 13
0
        public (System.UInt32 retval, IEnumerable <MSFTNetIPAddress> outCmdletOutput) Create(System.UInt16?inAddressFamily, System.UInt16?inAddressState, System.String inDefaultGateway, System.String inInterfaceAlias, System.UInt32?inInterfaceIndex, System.String inIPAddress, System.Boolean?inPassThru, System.String inPolicyStore, System.DateTime?inPreferredLifetime, System.Byte?inPrefixLength, System.UInt16?inPrefixOrigin, System.Boolean?inSkipAsSource, System.UInt16?inSuffixOrigin, System.Byte?inType, System.DateTime?inValidLifetime)
        {
            var parameters = new CimMethodParametersCollection();

            if (inAddressFamily.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("AddressFamily", inAddressFamily.Value, CimFlags.None));
            }
            if (inAddressState.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("AddressState", inAddressState.Value, CimFlags.None));
            }
            if (inDefaultGateway != null)
            {
                parameters.Add(CimMethodParameter.Create("DefaultGateway", inDefaultGateway, CimType.String, inDefaultGateway == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inInterfaceAlias != null)
            {
                parameters.Add(CimMethodParameter.Create("InterfaceAlias", inInterfaceAlias, CimType.String, inInterfaceAlias == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inInterfaceIndex.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("InterfaceIndex", inInterfaceIndex.Value, CimFlags.None));
            }
            if (inIPAddress != null)
            {
                parameters.Add(CimMethodParameter.Create("IPAddress", inIPAddress, CimType.String, inIPAddress == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPassThru.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PassThru", inPassThru.Value, CimFlags.None));
            }
            if (inPolicyStore != null)
            {
                parameters.Add(CimMethodParameter.Create("PolicyStore", inPolicyStore, CimType.String, inPolicyStore == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPreferredLifetime.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PreferredLifetime", inPreferredLifetime.Value, CimFlags.None));
            }
            if (inPrefixLength.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PrefixLength", inPrefixLength.Value, CimFlags.None));
            }
            if (inPrefixOrigin.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PrefixOrigin", inPrefixOrigin.Value, CimFlags.None));
            }
            if (inSkipAsSource.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("SkipAsSource", inSkipAsSource.Value, CimFlags.None));
            }
            if (inSuffixOrigin.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("SuffixOrigin", inSuffixOrigin.Value, CimFlags.None));
            }
            if (inType.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Type", inType.Value, CimFlags.None));
            }
            if (inValidLifetime.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("ValidLifetime", inValidLifetime.Value, CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Create", parameters);

            return((System.UInt32)result.ReturnValue.Value, (IEnumerable <MSFTNetIPAddress>)InfrastuctureObjectScope.Mapper.CreateMany <MSFTNetIPAddress>(InfrastuctureObjectScope, (IEnumerable <CimInstance>)result.OutParameters["CmdletOutput"].Value));
        }
Esempio n. 14
0
        public System.UInt32 Change(System.Boolean?inDesktopInteract, System.String inDisplayName, System.Byte?inErrorControl, System.String inLoadOrderGroup, System.String[] inLoadOrderGroupDependencies, System.String inPathName, System.String[] inServiceDependencies, System.Byte?inServiceType, System.String inStartMode, System.String inStartName, System.String inStartPassword)
        {
            var parameters = new CimMethodParametersCollection();

            if (inDesktopInteract.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("DesktopInteract", inDesktopInteract.Value, CimFlags.None));
            }
            if (inDisplayName != null)
            {
                parameters.Add(CimMethodParameter.Create("DisplayName", inDisplayName, CimType.String, inDisplayName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inErrorControl.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("ErrorControl", inErrorControl.Value, CimFlags.None));
            }
            if (inLoadOrderGroup != null)
            {
                parameters.Add(CimMethodParameter.Create("LoadOrderGroup", inLoadOrderGroup, CimType.String, inLoadOrderGroup == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inLoadOrderGroupDependencies != null)
            {
                parameters.Add(CimMethodParameter.Create("LoadOrderGroupDependencies", inLoadOrderGroupDependencies, CimType.StringArray, inLoadOrderGroupDependencies == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPathName != null)
            {
                parameters.Add(CimMethodParameter.Create("PathName", inPathName, CimType.String, inPathName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inServiceDependencies != null)
            {
                parameters.Add(CimMethodParameter.Create("ServiceDependencies", inServiceDependencies, CimType.StringArray, inServiceDependencies == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inServiceType.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("ServiceType", inServiceType.Value, CimFlags.None));
            }
            if (inStartMode != null)
            {
                parameters.Add(CimMethodParameter.Create("StartMode", inStartMode, CimType.String, inStartMode == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inStartName != null)
            {
                parameters.Add(CimMethodParameter.Create("StartName", inStartName, CimType.String, inStartName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inStartPassword != null)
            {
                parameters.Add(CimMethodParameter.Create("StartPassword", inStartPassword, CimType.String, inStartPassword == null ? CimFlags.NullValue : CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Change", parameters);

            return((System.UInt32)result.ReturnValue.Value);
        }
Esempio n. 15
0
        /// <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;
        }
        // Method: RemoveRoleVhd - Removing a list of server components from a VHD image.
        // Parameters: componentUniqueNames - The list of unique names of the server components to remove.
        //             vhdPath - The path of the VHD image.
        // Returns: The list of server components that are removed.
        public List <CimInstance> RemoveRoleVhd(List <string> componentUniqueNames, string vhdPath)
        {
            CimInstance        guidInstance             = RequestGuidCreator.CreateRequestGuid();
            RequestStateEnum   removeRoleRequestState   = 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 VHD image
            GetRoleSample      getRoleSample    = new GetRoleSample();
            List <CimInstance> serverComponents = getRoleSample.GetRoleVhd(vhdPath);

            // Retrieves the list of MSFT_ServerManagerServerComponentDescriptor CIM classes for the roles to remove
            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 uninstalling components.");

            // Create a CIM session to the local computer and invoke the RemoveServerComponentsVhdAsync 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("DeleteComponents", false, CimType.Boolean, CimFlags.In));
                methodParameters.Add(CimMethodParameter.Create("ServerComponentDescriptors", componentDescriptors.ToArray(), CimType.InstanceArray, CimFlags.In));
                methodParameters.Add(CimMethodParameter.Create("VhdPath", vhdPath, CimType.String, CimFlags.In));

                IObservable <CimMethodResultBase> observable = cimSession.InvokeMethodAsync("root\\Microsoft\\Windows\\ServerManager",
                                                                                            "MSFT_ServerManagerDeploymentTasks",
                                                                                            "RemoveServerComponentVhdAsync",
                                                                                            methodParameters,
                                                                                            operationOptions);
                DeploymentObserver observer = new DeploymentObserver();
                using (IDisposable cancellationDisposable = observable.Subscribe(observer))
                {
                    observer.GetResults(out serverComponentInstances, out removeRoleRequestState);
                }
            }

            int timeout   = 1200000; // timeout in 20 minutes for VHD Remove
            int startTime = Environment.TickCount;

            // Executes the Loop to query the method invocation results until the RequestState is Completed or Failed
            while (removeRoleRequestState == 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 removeRoleRequestState);
                    }
                }
                Console.Write(".");
                Thread.Sleep(1000);
            }

            Console.WriteLine();

            if (removeRoleRequestState == RequestStateEnum.Completed)
            {
                Console.WriteLine("Components successfully uninstalled!");
            }
            else if (removeRoleRequestState == RequestStateEnum.Failed)
            {
                Console.WriteLine("RemoveServerComponentVhdAsync request failed!");
            }

            return(serverComponentInstances);
        }
        // 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;
        }
Esempio n. 18
0
		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;
		}
Esempio n. 19
0
        public System.UInt32 AddByWsdPort(System.UInt32?inBranchOfficeOfflineLogSizeMB, System.String inComment, System.String inComputerName, System.String inDatatype, System.String inDeviceURL, System.String inDeviceUUID, System.Boolean?inDisableBranchOfficeLogging, System.Boolean?inKeepPrintedJobs, System.String inLocation, System.String inName, System.String inPermissionSDDL, System.String inPrintProcessor, System.UInt32?inPriority, System.Boolean?inPublished, System.UInt32?inRenderingMode, System.String inSeparatorPageFile, System.Boolean?inShared, System.String inShareName, System.UInt32?inStartTime, System.UInt32?inUntilTime, System.UInt32?inWorkflowPolicy)
        {
            var parameters = new CimMethodParametersCollection();

            if (inBranchOfficeOfflineLogSizeMB.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("BranchOfficeOfflineLogSizeMB", inBranchOfficeOfflineLogSizeMB.Value, CimFlags.None));
            }
            if (inComment != null)
            {
                parameters.Add(CimMethodParameter.Create("Comment", inComment, CimType.String, inComment == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inComputerName != null)
            {
                parameters.Add(CimMethodParameter.Create("ComputerName", inComputerName, CimType.String, inComputerName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inDatatype != null)
            {
                parameters.Add(CimMethodParameter.Create("Datatype", inDatatype, CimType.String, inDatatype == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inDeviceURL != null)
            {
                parameters.Add(CimMethodParameter.Create("DeviceURL", inDeviceURL, CimType.String, inDeviceURL == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inDeviceUUID != null)
            {
                parameters.Add(CimMethodParameter.Create("DeviceUUID", inDeviceUUID, CimType.String, inDeviceUUID == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inDisableBranchOfficeLogging.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("DisableBranchOfficeLogging", inDisableBranchOfficeLogging.Value, CimFlags.None));
            }
            if (inKeepPrintedJobs.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("KeepPrintedJobs", inKeepPrintedJobs.Value, CimFlags.None));
            }
            if (inLocation != null)
            {
                parameters.Add(CimMethodParameter.Create("Location", inLocation, CimType.String, inLocation == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inName != null)
            {
                parameters.Add(CimMethodParameter.Create("Name", inName, CimType.String, inName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPermissionSDDL != null)
            {
                parameters.Add(CimMethodParameter.Create("PermissionSDDL", inPermissionSDDL, CimType.String, inPermissionSDDL == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPrintProcessor != null)
            {
                parameters.Add(CimMethodParameter.Create("PrintProcessor", inPrintProcessor, CimType.String, inPrintProcessor == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inPriority.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Priority", inPriority.Value, CimFlags.None));
            }
            if (inPublished.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Published", inPublished.Value, CimFlags.None));
            }
            if (inRenderingMode.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("RenderingMode", inRenderingMode.Value, CimFlags.None));
            }
            if (inSeparatorPageFile != null)
            {
                parameters.Add(CimMethodParameter.Create("SeparatorPageFile", inSeparatorPageFile, CimType.String, inSeparatorPageFile == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inShared.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("Shared", inShared.Value, CimFlags.None));
            }
            if (inShareName != null)
            {
                parameters.Add(CimMethodParameter.Create("ShareName", inShareName, CimType.String, inShareName == null ? CimFlags.NullValue : CimFlags.None));
            }
            if (inStartTime.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("StartTime", inStartTime.Value, CimFlags.None));
            }
            if (inUntilTime.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("UntilTime", inUntilTime.Value, CimFlags.None));
            }
            if (inWorkflowPolicy.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("WorkflowPolicy", inWorkflowPolicy.Value, CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "AddByWsdPort", parameters);

            return((System.UInt32)result.ReturnValue.Value);
        }
        // Method: GetRole - Getting the list of server components from a VHD Image.
        // Returns: The list of retrieved server components on the system.
        public List <CimInstance> GetRoleVhd(string vhdPath)
        {
            CimInstance        guidInstance             = RequestGuidCreator.CreateRequestGuid();
            List <CimInstance> serverComponentInstances = new List <CimInstance>();
            RequestStateEnum   getRoleRequestState      = RequestStateEnum.Failed;

            // Create a CIM session to the local computer and invoke the GetServerComponentsVhdAsync 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("VhdPath", vhdPath, CimType.String, CimFlags.In));

                IObservable <CimMethodResultBase> observable = cimSession.InvokeMethodAsync("root\\Microsoft\\Windows\\ServerManager",
                                                                                            "MSFT_ServerManagerDeploymentTasks",
                                                                                            "GetServerComponentsVhdAsync",
                                                                                            methodParameters,
                                                                                            operationOptions);
                DeploymentObserver observer = new DeploymentObserver();
                using (IDisposable cancellationDisposable = observable.Subscribe(observer))
                {
                    observer.GetResults(out serverComponentInstances, out getRoleRequestState);
                }
            }

            int timeout   = 600000; // timeout in 10 minutes for VHD Get
            int startTime = Environment.TickCount;

            // Executes the Loop to query the method invocation results until the RequestState is Completed or Failed
            while (getRoleRequestState == 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));

                    IObservable <CimMethodResultBase> observable = cimSession.InvokeMethodAsync("root\\Microsoft\\Windows\\ServerManager",
                                                                                                "MSFT_ServerManagerDeploymentTasks",
                                                                                                "GetEnumerationRequestState",
                                                                                                methodParameters,
                                                                                                operationOptions);
                    DeploymentObserver observer = new DeploymentObserver();
                    using (IDisposable cancellationDisposable = observable.Subscribe(observer))
                    {
                        observer.GetResults(out serverComponentInstances, out getRoleRequestState);
                    }
                }
                Thread.Sleep(1000);
            }

            if (getRoleRequestState == RequestStateEnum.Failed)
            {
                Console.WriteLine("GetServerComponentsVhdAsync request failed!");
            }

            return(serverComponentInstances);
        }
        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);
        }
Esempio n. 22
0
		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;
			}
		}
        /// <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();

                const 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, CimCmdletStrings.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, CimCmdletStrings.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);
        }
        public (System.UInt32 retval, MSFTDAClientExperienceConfiguration outOutputObject) Reset(System.Boolean?inCorporateResources, System.Boolean?inCustomCommands, System.Boolean?inForceTunneling, System.Boolean?inFriendlyName, System.Boolean?inGslbFqdn, System.Boolean?inIPsecTunnelEndpoints, System.Boolean?inManualEntryPointSelectionAllowed, System.Boolean?inPassiveMode, System.Boolean?inPassThru, System.Boolean?inPreferLocalNamesAllowed, System.Boolean?inSupportEmail, System.Boolean?inUserInterface)
        {
            var parameters = new CimMethodParametersCollection();

            if (inCorporateResources.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("CorporateResources", inCorporateResources.Value, CimFlags.None));
            }
            if (inCustomCommands.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("CustomCommands", inCustomCommands.Value, CimFlags.None));
            }
            if (inForceTunneling.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("ForceTunneling", inForceTunneling.Value, CimFlags.None));
            }
            if (inFriendlyName.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("FriendlyName", inFriendlyName.Value, CimFlags.None));
            }
            if (inGslbFqdn.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("GslbFqdn", inGslbFqdn.Value, CimFlags.None));
            }
            if (inIPsecTunnelEndpoints.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("IPsecTunnelEndpoints", inIPsecTunnelEndpoints.Value, CimFlags.None));
            }
            if (inManualEntryPointSelectionAllowed.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("ManualEntryPointSelectionAllowed", inManualEntryPointSelectionAllowed.Value, CimFlags.None));
            }
            if (inPassiveMode.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PassiveMode", inPassiveMode.Value, CimFlags.None));
            }
            if (inPassThru.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PassThru", inPassThru.Value, CimFlags.None));
            }
            if (inPreferLocalNamesAllowed.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("PreferLocalNamesAllowed", inPreferLocalNamesAllowed.Value, CimFlags.None));
            }
            if (inSupportEmail.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("SupportEmail", inSupportEmail.Value, CimFlags.None));
            }
            if (inUserInterface.HasValue)
            {
                parameters.Add(CimMethodParameter.Create("UserInterface", inUserInterface.Value, CimFlags.None));
            }
            var result = InfrastuctureObjectScope.CimSession.InvokeMethod(InnerCimInstance, "Reset", parameters);

            return((System.UInt32)result.ReturnValue.Value, (MSFTDAClientExperienceConfiguration)InfrastuctureObjectScope.Mapper.Create(InfrastuctureObjectScope, (CimInstance)result.OutParameters["OutputObject"].Value));
        }