Exemplo n.º 1
0
        static public List <PrintJob> GetPrintJobs()
        {
            List <PrintJob>           printJobs     = new List <PrintJob>();
            string                    Namespace     = @"root\cimv2";
            string                    OSQuery       = "SELECT * FROM Win32_PrintJob";
            CimSession                mySession     = CimSession.Create("mcd-eps-3");
            IEnumerable <CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", OSQuery);

            foreach (var props in queryInstance)
            {
                var jobID     = Int32.Parse(props.CimInstanceProperties["JobID"].Value.ToString());
                var printName = props.CimInstanceProperties["Name"].ToString();
                printJobs.Add(new PrintJob {
                    PrintJobID = jobID, PrintJobName = printName
                });
            }
            return(printJobs);
        }
        /// <summary>
        /// Retrieves the time when the system was last started.
        /// </summary>
        /// <returns>WMI Win32_OperatingSystem LastBootUpTime property</returns>
        private static DateTime?GetLastBootUpTime()
        {
            string             computer       = "MYCOMPUTERNAME";
            string             namespaceName  = @"root\cimv2";
            string             queryDialect   = "WQL";
            string             query          = "SELECT * FROM Win32_OperatingSystem";
            DComSessionOptions SessionOptions = new DComSessionOptions();

            SessionOptions.Impersonation = ImpersonationType.Impersonate;
            CimSession session      = CimSession.Create(computer, SessionOptions);
            var        cimInstances = session.QueryInstances(namespaceName, queryDialect, query);

            if (cimInstances.Any())
            {
                var lastBootUpTime = cimInstances.First().CimInstanceProperties["LastBootUpTime"].Value;
                return(Convert.ToDateTime(lastBootUpTime));
            }
            return(null);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Execute a CIM query and return only the first instance in the result.
        /// </summary>
        /// <param name="session">The CimSession to be queried</param>
        /// <param name="nameSpace">A string containing the namespace to run the query against</param>
        /// <param name="query">A string containing the query to be run</param>
        /// <returns>
        /// A <see cref="Microsoft.Management.Infrastructure.CimInstance"/> object
        /// representing the first instance in a query result if successful, null
        /// otherwise.
        /// </returns>
        internal static CimInstance QueryFirstInstance(this CimSession session, string nameSpace, string query)
        {
            try
            {
                var instances  = session.QueryInstances(nameSpace, query);
                var enumerator = instances.GetEnumerator();

                if (enumerator.MoveNext())
                {
                    return(enumerator.Current);
                }
            }
            catch (Exception /*ex*/)
            {
                // on any error, fall through to the null return below
            }

            return(null);
        }
Exemplo n.º 4
0
        static void FindFile(CimSession session, string file)
        {
            int    i      = file.LastIndexOf(".");
            string filter = "";

            if (i < 0)
            {
                filter = "Filename='" + file + "'";
            }
            else
            {
                filter = "Extension='" + file.Substring(i + 1) + "' AND Filename LIKE '" + file.Substring(0, i) + "'";
            }
            var query = session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Cim_DataFile WHERE " + filter);

            foreach (CimInstance item in query)
            {
                Console.WriteLine("{0}", item.CimInstanceProperties["name"].Value);
            }
        }
Exemplo n.º 5
0
        /*
         * "function Decode {If ($args[0] -is [System.Array]) {[System.Text.Encoding]::ASCII.GetString($args[0])}
         * Else {\"Not Found\"}}
         *
         *
         * $Monitors = Get-CimInstance WmiMonitorID -Namespace root\\wmi;
         * ForEach ($Monitor in $monitors) {$Serial = Decode $Monitor.SerialNumberID -notmatch 0; if($Serial -ne 0){return $Serial}}");
         */
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string Namespace = @"root\wmi";
            string className = "WmiMonitorID";

            CimInstance myDrive = new CimInstance(className, Namespace);

            //myDrive.CimInstanceProperties.Add(CimProperty.Create("SerialNumberID", null, CimFlags.Key)); //CimProperty.Create("SerialNumberID", "C:", CimFlags.Key));

            CimSession mySession = CimSession.Create(null);

            CimInstance searchInstance = mySession.GetInstance(Namespace, myDrive);


            IEnumerable <CimInstance> queryInstances =
                mySession.QueryInstances(@"root\wmi",
                                         "WQL",
                                         @"select * from WmiMonitorID");
        }
 /// <summary>
 /// Retrieves the duration (TickCount) since the system was last started from a remote machine.
 /// </summary>
 /// <param name="computerName">Name of computer on network to retrieve tickcount for</param>
 /// <returns>WMI Win32_OperatingSystem LocalDateTime - LastBootUpTime (ticks)</returns>
 public int? GetRemoteMachineTickCount(string computerName)
 {
     string namespaceName = @"root\cimv2";
     string queryDialect = "WQL";
     DComSessionOptions SessionOptions = new DComSessionOptions();
     SessionOptions.Impersonation = ImpersonationType.Impersonate;
     var baseLineTickCount = Environment.TickCount; // Note: to determine discrepancy
     CimSession session = CimSession.Create(computerName, SessionOptions);
     string query = "SELECT * FROM Win32_OperatingSystem";
     var cimInstances = session.QueryInstances(namespaceName, queryDialect, query);
     if (cimInstances.Any())
     {
         var lastBootUpTime = Convert.ToDateTime(cimInstances.First().CimInstanceProperties["LastBootUpTime"].Value);
         var localDateTime = Convert.ToDateTime(cimInstances.First().CimInstanceProperties["LocalDateTime"].Value);
         var timeSpan = localDateTime - lastBootUpTime;
         var tickCount = Convert.ToInt32(timeSpan.TotalMilliseconds);
         var discrepancy = tickCount - baseLineTickCount; // Note: discrepancy about +/- 100ms
         return tickCount;
     }
     return null;
 }
 public static void QueryInstanceSync(CimSession cimSession, string cimNamespace)
 {
     try
     {
         string query = QueryInstanceCore();
         IEnumerable <CimInstance> queryInstances = cimSession.QueryInstances(cimNamespace, "WQL", query);
         foreach (CimInstance cimInstance in queryInstances)
         {
             // Use the instance
             PrintCimInstance(cimInstance);
         }
     }
     catch (CimException ex)
     {
         PrintCimException(ex);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Exemplo n.º 8
0
        public static bool CheckDgCim(CimSession cimSession)
        {
            // Use this method to check for the existence of Device Guard on a system. This isn't a perfect remedy but should work just fine

            var osQuery = @"SELECT * FROM Win32_DeviceGuard";
            IEnumerable <CimInstance> queryInstance =
                cimSession.QueryInstances(@"root\Microsoft\Windows\DeviceGuard", "WQL", osQuery);

            foreach (CimInstance cimObject in queryInstance)
            {
                if (Convert.ToInt32(cimObject.CimInstanceProperties["CodeIntegrityPolicyEnforcementStatus"].Value) ==
                    2 || Convert.ToInt32(cimObject.CimInstanceProperties["UsermodeCodeIntegrityPolicyEnforcementStatus"]
                                         .Value) == 2)
                {
                    Messenger.ErrorMessage("[-] Device Guard enabled! Using PowerShell with Constrained Language Mode\n");
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 9
0
        private static void PrintMonitorInfos()
        {
            CimSession mySession = CimSession.Create(null);

            IEnumerable<CimInstance> queryInstances =
                mySession.QueryInstances(@"root\wmi",
                    "WQL",
                    @"select * from WmiMonitorID");

            foreach (var queryInstance in queryInstances)
            {
                foreach (var cimInstanceProperty in queryInstance.CimInstanceProperties)
                {
                    var value = cimInstanceProperty.CimType == CimType.UInt16Array
                        ? ConvertUInt16ArrayToString(cimInstanceProperty)
                        : Convert.ToString(cimInstanceProperty.Value);

                    Console.WriteLine(cimInstanceProperty.Name + " " + value);
                }
            }
        }
        /// <summary>
        /// Retrieves the duration (TimeSpan) since the system was last started.
        /// Note: can be used on a local or a remote machine.
        /// </summary>
        /// <param name="computerName">Name of computer on network to retrieve uptime for</param>
        /// <returns>WMI Win32_OperatingSystem LocalDateTime - LastBootUpTime</returns>
        private static TimeSpan?GetSystemUptime(string computerName)
        {
            string             namespaceName  = @"root\cimv2";
            string             queryDialect   = "WQL";
            DComSessionOptions SessionOptions = new DComSessionOptions();

            SessionOptions.Impersonation = ImpersonationType.Impersonate;
            CimSession session      = CimSession.Create(computerName, SessionOptions);
            string     query        = "SELECT * FROM Win32_OperatingSystem";
            var        cimInstances = session.QueryInstances(namespaceName, queryDialect, query);

            if (cimInstances.Any())
            {
                var cimInstance    = cimInstances.First();
                var lastBootUpTime = Convert.ToDateTime(cimInstance.CimInstanceProperties["LastBootUpTime"].Value);
                var localDateTime  = Convert.ToDateTime(cimInstance.CimInstanceProperties["LocalDateTime"].Value);
                var uptime         = localDateTime - lastBootUpTime;
                return(uptime);
            }
            return(null);
        }
Exemplo n.º 11
0
        static public List <PrintJob> GetPrintJobs(List <string> printserver)
        {
            List <PrintJob> printJobs = new List <PrintJob>();
            string          Namespace = @"root\cimv2";
            string          OSQuery   = "SELECT * FROM Win32_PrintJob";

            foreach (string ps in printserver)
            {
                CimSession mySession = CimSession.Create(ps);
                IEnumerable <CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", OSQuery);
                foreach (var props in queryInstance)
                {
                    var Printer = props.CimInstanceProperties["Name"].Value.ToString();
                    Printer = Printer.Substring(0, Printer.LastIndexOf(','));
                    var PrintJobID   = Int32.Parse(props.CimInstanceProperties["JobID"].Value.ToString());
                    var PrintJobName = props.CimInstanceProperties["Document"].Value.ToString();
                    var Server       = props.CimInstanceProperties["HostPrintQueue"].Value.ToString();
                    var Status       = props.CimInstanceProperties["Status"].Value.ToString();
                    var PrintDriver  = props.CimInstanceProperties["DriverName"].Value.ToString();
                    //var TimeSubmitted = ManagementDateTimeConverter.ToDateTime(props.CimInstanceProperties["StartTime"].ToString());
                    var TimeSubmitted = Convert.ToDateTime(props.CimInstanceProperties["TimeSubmitted"].Value);
                    var PagesPrinted  = Int32.Parse(props.CimInstanceProperties["PagesPrinted"].Value.ToString());
                    var TotalPages    = Int32.Parse(props.CimInstanceProperties["TotalPages"].Value.ToString());

                    printJobs.Add(new PrintJob {
                        Printer       = Printer,
                        PrintJobID    = PrintJobID,
                        PrintJobName  = PrintJobName,
                        Server        = Server,
                        Status        = Status,
                        PrintDriver   = PrintDriver,
                        TimeSubmitted = TimeSubmitted,
                        PagesPrinted  = PagesPrinted,
                        TotalPages    = TotalPages
                    });
                }
            }

            return(printJobs);
        }
Exemplo n.º 12
0
        public string UnInstallSoftware(string programName)
        {
            CimSession  session       = CimSession.Create("localHost");
            IEnumerable queryInstance = session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Product ");

            ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");

            foreach (var item in mos.Get())
            {
                if (item["Name"].ToString() == programName)
                {
                    //object hr = item.InvokeMethod("Uninstall", null);
                    // return (bool)hr;
                }
            }

            foreach (CimInstance cimObj in queryInstance)
            {
                //cimObj.Uninstall();
            }
            return("");
        }
Exemplo n.º 13
0
        /// <summary>
        /// Retrieve an array of new objects of type T, whose properties and fields are
        /// populated from an instance of the specified WMI class on the specified CIM
        /// session.
        /// </summary>
        /// <typeparam name="T">
        /// The type of the object to be created. Must be a default-constructable
        /// reference type.
        /// </typeparam>
        /// <param name="session">
        /// The CIM session to be queried.
        /// </param>
        /// <param name="nameSpace">
        /// A string containing the namespace to run the query against
        /// </param>
        /// <param name="wmiClassName">
        /// A string containing the name of the WMI class from which to populate
        /// the resultant array elements.
        /// </param>
        /// <returns>
        /// An array of new objects of type T if successful, null otherwise.
        /// </returns>
        /// <remarks>
        /// This method matches property and field names of type T with identically
        /// named properties in the WMI class instance. The WMI property is converted
        /// to the type of T's property or field.
        /// </remarks>
        internal static T[] GetAll <T>(CimSession session, string nameSpace, string wmiClassName) where T : class, new()
        {
            if (string.IsNullOrEmpty(wmiClassName))
            {
                throw new ArgumentException("String argument may not be null or empty", "wmiClassName");
            }

            var rv = new List <T>();

            try
            {
                var instances = session.QueryInstances(nameSpace, CIMHelper.WqlQueryAll(wmiClassName));

                if (instances != null)
                {
                    var type    = typeof(T);
                    var binding = BindingFlags.Public | BindingFlags.Instance;

                    foreach (var instance in instances)
                    {
                        T objT = new T();

                        using (instance)
                        {
                            SetObjectDataMembers(objT, binding, instance);
                        }

                        rv.Add(objT);
                    }
                }
            }
            catch (Exception /*ex*/)
            {
                // on any error we'll just fall through to the return below
            }

            return(rv.ToArray());
        }
Exemplo n.º 14
0
        public string GetAccounts()
        {
            //CimSession session = CimSession.Create("ROBINDEVIL");
            string             computer    = "ROBINDEVIL";
            DComSessionOptions DComOptions = new DComSessionOptions();

            DComOptions.Impersonation = ImpersonationType.Impersonate;
            CimSession session = CimSession.Create(computer, DComOptions);


            IEnumerable queryInstance = session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_ComputerSystem");

            StringBuilder sb = new StringBuilder();

            foreach (CimInstance cimObj in queryInstance)
            {
                sb.Append("computer name :" + cimObj.CimInstanceProperties["Name"].ToString() + Environment.NewLine);
                sb.Append("computer Domain :" + cimObj.CimInstanceProperties["Domain"].ToString() + Environment.NewLine);
                //Console.WriteLine(cimObj.CimInstanceProperties["Name"].ToString());// to get computer name
                //Console.WriteLine(cimObj.CimInstanceProperties["Domain"].ToString());// to get domain name
            }
            return(sb.ToString());
        }
        private void AppScan(bool PC1, bool PC2, bool PC3)
        {
            Boolean isOn     = false;
            var     password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            if (PC1)
            {
                try
                {
                    CimSession Session1 = CimSession.Create(Data.computer1, SessionOptions);
                    var        allApp1  = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    isOn = false;
                    foreach (CimInstance oneApp1 in allApp1)
                    {
                        if (oneApp1.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"")
                        {
                            labelApp1.Text = "Online";
                            buttonShowStatut1.BackColor = System.Drawing.Color.Lime;
                            isOn = true;
                        }
                    }
                    if (!isOn)
                    {
                        labelApp1.Text = "Offline";
                        buttonShowStatut1.BackColor = System.Drawing.Color.DarkRed;
                    }
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2 = CimSession.Create(Data.computer2, SessionOptions);
                    var        allApp2  = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    isOn = false;
                    foreach (CimInstance oneApp2 in allApp2)
                    {
                        if (oneApp2.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"")
                        {
                            labelApp2.Text = "Online";
                            buttonShowStatut2.BackColor = System.Drawing.Color.Lime;
                            isOn = true;
                        }
                    }
                    if (!isOn)
                    {
                        labelApp2.Text = "Offline";
                        buttonShowStatut2.BackColor = System.Drawing.Color.DarkRed;
                    }
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3 = CimSession.Create(Data.computer3, SessionOptions);
                    var        allApp3  = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    isOn = false;
                    foreach (CimInstance oneApp3 in allApp3)
                    {
                        if (oneApp3.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"")
                        {
                            labelApp3.Text = "Online";
                            buttonShowStatut3.BackColor = System.Drawing.Color.Lime;
                            isOn = true;
                        }
                    }
                    if (!isOn)
                    {
                        labelApp3.Text = "Offline";
                        buttonShowStatut3.BackColor = System.Drawing.Color.DarkRed;
                    }
                }
                catch { Data.LoadPC3 = false; }
            }
        }
Exemplo n.º 16
0
 private CimInstance getRdpTcpGeneralSetting()
 {
     return(cimSession.QueryInstances(TERMINALSERVICES_NAMESPACE, "WQL", $"select {SSL_CERTIFICATE_SHA1_HASH} from Win32_TSGeneralSetting where TerminalName='RDP-tcp'").First());
 }
Exemplo n.º 17
0
        public static void ConnectingToWMI(string Computer_B)
        {
            //string Namespace = @"root\cimv2";
            //string OSQuery = "SELECT * FROM Win32_OperatingSystem";
            //CimSession mySession = CimSession.Create(Computer_B);
            //IEnumerable<CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", OSQuery);


            //foreach (CimInstance cimInstance in queryInstance)
            //{
            //    Console.WriteLine("Process name: {0}", cimInstance.CimInstanceProperties["Name"].Value);
            //}


            //*************************************
            //string domain = "DESKTOP-3KU7CQB";
            //string username = "******";
            //string password = "******";

            string domain   = "devstation";
            string username = "******";
            string password = "******";


            //PerformanceCounter freeSpaceCounter = null;
            //using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
            //{
            //    freeSpaceCounter = new PerformanceCounter("LogicalDisk",
            //                               "Free Megabytes", "D:", "RemoteMachine12");
            //}

            ConnectionOptions con = new ConnectionOptions();

            con.Username = "******";
            con.Password = "******";

            ManagementScope scope = new ManagementScope(@"\\" + Computer_B + @"\root\cimv2", con);

            scope.Connect();



            SecureString securepassword = new SecureString();

            foreach (char c in password)
            {
                securepassword.AppendChar(c);
            }

            // create Credentials
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default,
                                                          Computer_B,
                                                          username,
                                                          securepassword);

            // create SessionOptions using Credentials
            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            // create Session using computer, SessionOptions
            CimSession Session = CimSession.Create(Computer_B, SessionOptions);


            var allVolumes = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
            var allPDisks  = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_DiskDrive");

            // Loop through all volumes
            foreach (CimInstance oneVolume in allVolumes)
            {
                // Show volume information

                if (oneVolume.CimInstanceProperties["DriveLetter"].ToString()[0] > ' ')
                {
                    Console.WriteLine("Volume ‘{0}’ has {1} bytes total, {2} bytes available",
                                      oneVolume.CimInstanceProperties["DriveLetter"],
                                      oneVolume.CimInstanceProperties["Size"],
                                      oneVolume.CimInstanceProperties["SizeRemaining"]);
                }
            }

            // Loop through all physical disks
            foreach (CimInstance onePDisk in allPDisks)
            {
                // Show physical disk information
                Console.WriteLine("Disk {0} is model {1}, serial number {2}",
                                  onePDisk.CimInstanceProperties["DeviceId"],
                                  onePDisk.CimInstanceProperties["Model"].ToString().TrimEnd(),
                                  onePDisk.CimInstanceProperties["SerialNumber"]);
            }
        }
        private void DiskScan(bool PC1, bool PC2, bool PC3)
        {
            var password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);

            if (PC1)
            {
                try
                {
                    CimSession Session1    = CimSession.Create(Data.computer1, SessionOptions);
                    var        allVolumes1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
                    foreach (CimInstance oneVolume1 in allVolumes1)
                    {
                        if (oneVolume1.CimInstanceProperties["DriveLetter"].ToString() == "DriveLetter = \"C:\"")
                        {
                            Data.disk1size   = String.Format("{0}", oneVolume1.CimInstanceProperties["Capacity"].Value);
                            Data.DD1size     = Math.Round(Convert.ToDouble(Data.disk1size) / 1073741824, 2);
                            Data.disk1size   = Data.DD1size.ToString() + " GB";
                            Data.disk1remain = String.Format("{0}", oneVolume1.CimInstanceProperties["FreeSpace"].Value);
                            Data.DD1remain   = Math.Round(Convert.ToDouble(Data.disk1remain) / 1073741824, 2);
                            Data.disk1remain = Data.DD1remain.ToString() + " GB";
                        }
                        BarDD1.Maximum = (int)Data.DD1size;
                        BarDD1.Value   = (int)(Data.DD1size - Data.DD1remain);
                    }
                    labelDisk1Remain.Text = Data.disk1remain;
                    labelDisk1Total.Text  = Data.disk1size;
                    labelDisk1Used.Text   = "Espace occupé (" + (Math.Round(((Data.DD1size - Data.DD1remain) / Data.DD1size), 2) * 100) + "%) :";
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2    = CimSession.Create(Data.computer2, SessionOptions);
                    var        allVolumes2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
                    foreach (CimInstance oneVolume2 in allVolumes2)
                    {
                        if (oneVolume2.CimInstanceProperties["DriveLetter"].ToString() == "DriveLetter = \"C:\"")
                        {
                            Data.disk2size   = String.Format("{0}", oneVolume2.CimInstanceProperties["Capacity"].Value);
                            Data.DD2size     = Math.Round(Convert.ToDouble(Data.disk2size) / 1073741824, 2);
                            Data.disk2size   = Data.DD2size.ToString() + " GB";
                            Data.disk2remain = String.Format("{0}", oneVolume2.CimInstanceProperties["FreeSpace"].Value);
                            Data.DD2remain   = Math.Round(Convert.ToDouble(Data.disk2remain) / 1073741824, 2);
                            Data.disk2remain = Data.DD2remain.ToString() + " GB";
                        }
                        BarDD2.Maximum = (int)Data.DD2size;
                        BarDD2.Value   = (int)(Data.DD2size - Data.DD2remain);
                    }
                    labelDisk2Remain.Text = Data.disk2remain;
                    labelDisk2Total.Text  = Data.disk2size;
                    labelDisk2Used.Text   = "Espace occupé (" + (Math.Round(((Data.DD2size - Data.DD2remain) / Data.DD2size), 2) * 100) + "%) :";
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3    = CimSession.Create(Data.computer3, SessionOptions);
                    var        allVolumes3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
                    foreach (CimInstance oneVolume3 in allVolumes3)
                    {
                        if (oneVolume3.CimInstanceProperties["DriveLetter"].ToString() == "DriveLetter = \"C:\"")
                        {
                            Data.disk3size   = String.Format("{0}", oneVolume3.CimInstanceProperties["Capacity"].Value);
                            Data.DD3size     = Math.Round(Convert.ToDouble(Data.disk3size) / 1073741824, 2);
                            Data.disk3size   = Data.DD3size.ToString() + " GB";
                            Data.disk3remain = String.Format("{0}", oneVolume3.CimInstanceProperties["FreeSpace"].Value);
                            Data.DD3remain   = Math.Round(Convert.ToDouble(Data.disk3remain) / 1073741824, 2);
                            Data.disk3remain = Data.DD3remain.ToString() + " GB";
                        }
                        BarDD3.Maximum = (int)Data.DD3size;
                        BarDD3.Value   = (int)(Data.DD3size - Data.DD3remain);
                    }
                    labelDisk3Remain.Text = Data.disk3remain;
                    labelDisk3Total.Text  = Data.disk3size;
                    labelDisk3Used.Text   = "Espace occupé (" + (Math.Round(((Data.DD3size - Data.DD3remain) / Data.DD3size), 2) * 100) + "%) :";
                }
                catch { Data.LoadPC3 = false; }
            }
        }
Exemplo n.º 19
0
        private static IEnumerable <CimInstance> GetRelatedInstance(CimSession session, string namespaceName, string sourceInstanceObjectPath, string associationClassName, string resultClassName, string resultRoleName, string roleName, CimOperationOptions options)
        {
            var query = string.Format("ASSOCIATORS OF {{{0}}} WHERE AssocClass = {1} ResultClass = {2} ResultRole = {3} Role = {4}", sourceInstanceObjectPath, associationClassName, resultClassName, resultRoleName, roleName);

            return(session.QueryInstances(namespaceName, "WQL", query, options));
        }
        private void RamScan(bool PC1, bool PC2, bool PC3)
        {
            var password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            if (PC1)
            {
                try
                {
                    CimSession Session1   = CimSession.Create(Data.computer1, SessionOptions);
                    var        allMemory1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory");
                    Data.memory1size = 0;
                    foreach (CimInstance oneMemory1 in allMemory1)
                    {
                        Data.ram1size      = String.Format("{0}", oneMemory1.CimInstanceProperties["Capacity"].Value);
                        Data.memory1size  += Math.Round(Convert.ToDouble(Data.ram1size) / 1073741824, 2);
                        Data.ram1size      = Data.memory1size.ToString() + " GB";
                        labelRam1Size.Text = Data.ram1size;
                    }
                    var allUsedMemory1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
                    foreach (CimInstance oneUsedMemory1 in allUsedMemory1)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedMemory1.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram1percent);
                    }
                    labelRam1Used.Text = Data.ram1percent + "%";
                    BarRAM1.Value      = Data.ram1percent;
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2   = CimSession.Create(Data.computer2, SessionOptions);
                    var        allMemory2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory");
                    Data.memory2size = 0;
                    foreach (CimInstance oneMemory2 in allMemory2)
                    {
                        Data.ram2size      = String.Format("{0}", oneMemory2.CimInstanceProperties["Capacity"].Value);
                        Data.memory2size  += Math.Round(Convert.ToDouble(Data.ram2size) / 1073741824, 2);
                        Data.ram2size      = Data.memory2size.ToString() + " GB";
                        labelRam2Size.Text = Data.ram2size;
                    }
                    var allUsedMemory2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
                    foreach (CimInstance oneUsedMemory2 in allUsedMemory2)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedMemory2.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram2percent);
                    }
                    labelRam2Used.Text = Data.ram2percent + "%";
                    BarRAM2.Value      = Data.ram2percent;
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3   = CimSession.Create(Data.computer3, SessionOptions);
                    var        allMemory3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory");
                    Data.memory3size = 0;
                    foreach (CimInstance oneMemory3 in allMemory3)
                    {
                        Data.ram3size      = String.Format("{0}", oneMemory3.CimInstanceProperties["Capacity"].Value);
                        Data.memory3size  += Math.Round(Convert.ToDouble(Data.ram3size) / 1073741824, 2);
                        Data.ram3size      = Data.memory3size.ToString() + " GB";
                        labelRam3Size.Text = Data.ram3size;
                    }
                    var allUsedMemory3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
                    foreach (CimInstance oneUsedMemory3 in allUsedMemory3)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedMemory3.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram3percent);
                    }
                    labelRam3Used.Text = Data.ram3percent + "%";
                    BarRAM3.Value      = Data.ram3percent;
                }
                catch { Data.LoadPC3 = false; }
            }
        }
Exemplo n.º 21
0
        static void wmiConnect(string target, DComSessionOptions SessionOptions, string mode)
        {
            CimSession Session = CimSession.Create(target, SessionOptions);

            try
            {
                if (mode.ToLower() == "all" || mode.ToLower() == "services")
                {
                    var allServices = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Service where NOT startname like '%LocalSystem%' AND NOT startname like '%NT AUTHORITY%'");
                    foreach (CimInstance service in allServices)
                    {
                        if (service.CimInstanceProperties["StartName"].ToString() != "StartName")
                        {
                            Console.WriteLine($"[+]Non-default service account found on {target}: {service.CimInstanceProperties["StartName"].Value.ToString()}");
                        }
                    }
                }

                if (mode.ToLower() == "all" || mode.ToLower() == "sessions")
                {
                    var allSessions  = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_LoggedOnUser");
                    var allProcesses = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_SessionProcess");

                    //gets us the sessionID associated with each running process on the system, done in order to avoid showing false positives tied to stale sessions
                    List <int> processSessions = new List <int>();
                    foreach (CimInstance proc in allProcesses)
                    {
                        processSessions.Add(Int32.Parse(proc.CimInstanceProperties["antecedent"].Value.ToString().Split('"')[1]));
                    }
                    IEnumerable <int> uniqueProcessSessions = processSessions.Distinct();

                    //gets us a list of all sessions on the remote system.  This will include a variety of false positives / unwanted system sessions that we have to filter out.  Results are added to a keyed dictionary for lookups against running processes.
                    List <String> sessions = new List <String>();
                    var           ses2     = new Dictionary <int, string>();
                    foreach (CimInstance session in allSessions)
                    {
                        String   antecedent   = session.CimInstanceProperties["antecedent"].Value.ToString();
                        String   dependent    = session.CimInstanceProperties["dependent"].Value.ToString();
                        String[] userDomain   = antecedent.Split('"');
                        int      dependentKey = Int32.Parse(dependent.Split('"')[1]);
                        if ((!userDomain[1].ToLower().Contains("dwm-")) && (!userDomain[1].ToLower().Contains("umfd-")) && (!userDomain[1].ToLower().Contains("anonymous logon")) && (!userDomain[1].ToLower().Contains("local service")) && (!userDomain[1].ToLower().Contains("network service")) && (!userDomain[1].ToLower().Equals("system")))
                        {
                            sessions.Add($"{userDomain[3]}\\{userDomain[1]}");
                            ses2.Add(dependentKey, $"{userDomain[3]}\\{userDomain[1]}");
                        }
                    }

                    //Now that we have a list of sessions and a list of all logonSessionIDs with currently active processes we can compare the two in order to get an accurate list of active sessions
                    foreach (int procSession in uniqueProcessSessions)
                    {
                        if (ses2.ContainsKey(procSession))
                        {
                            Console.WriteLine($"[+]Session found on {target}: {ses2[procSession]}");
                        }
                    }
                }
            }
            catch (CimException e)
            {
                if (e.MessageId.Contains("40004"))
                {
                    Console.WriteLine($"[-]The following host was unreachable: {target}");
                    return;
                }
                else if (e.MessageId.Contains("70005"))
                {
                    Console.WriteLine($"[-]Insufficient privileges / invalid credentials on the following host: {target}");
                    return;
                }
                else if (e.MessageId.Contains("800706"))
                {
                    Console.WriteLine($"[-]No route to the following host: {target}");
                    return;
                }
                else
                {
                    Console.WriteLine($"[-]Error - undefined error on the following host: {target} errorID: {e.MessageId}");
                    return;
                }
            }
            Session.Close();
        }
        private void CpuScan(bool PC1, bool PC2, bool PC3)
        {
            var password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            if (PC1)
            {
                try
                {
                    CimSession Session1     = CimSession.Create(Data.computer1, SessionOptions);
                    var        allUsedCore1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");
                    foreach (CimInstance oneUsedCore1 in allUsedCore1)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedCore1.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu1percent);
                    }
                    labelCpu1Used.Text = Data.cpu1percent + "%";
                    BarCPU1.Value      = Data.cpu1percent;
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2     = CimSession.Create(Data.computer2, SessionOptions);
                    var        allUsedCore2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");
                    foreach (CimInstance oneUsedCore2 in allUsedCore2)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedCore2.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu2percent);
                    }
                    labelCpu2Used.Text = Data.cpu2percent + "%";
                    BarCPU2.Value      = Data.cpu2percent;
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3     = CimSession.Create(Data.computer3, SessionOptions);
                    var        allUsedCore3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");
                    foreach (CimInstance oneUsedCore3 in allUsedCore3)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedCore3.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu3percent);
                    }
                    labelCpu3Used.Text = Data.cpu3percent + "%";
                    BarCPU3.Value      = Data.cpu3percent;
                }
                catch { Data.LoadPC3 = false; }
            }
        }
Exemplo n.º 23
0
        private CimInstance[] GetServices(string szMachine, string szUsername, CancellationToken _cancel)
        {
            bool _exceptionThrown       = false;
            List <CimInstance> _results = new List <CimInstance>();

            if (!_cancel.IsCancellationRequested)
            {
                try
                {
                    string     Namespace = @"root\cimv2";
                    string     OSQuery   = "SELECT * FROM Win32_Service";
                    CimSession mySession = CimSession.Create(szMachine);
                    IEnumerable <CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", OSQuery);
                    foreach (CimInstance _svc in queryInstance)
                    {
                        if (_cancel.IsCancellationRequested)
                        {
                            break;
                        }

                        string szServiceName = _svc.CimInstanceProperties["StartName"].Value as string;
                        if (!string.IsNullOrWhiteSpace(szServiceName))
                        {
                            if (szServiceName.ToLower().Contains(szUsername.ToLower()))
                            {
                                _results.Add(_svc);
                            }
                        }
                    }
                }
                catch (CimException _cex)
                {
                    switch (_cex.HResult)
                    {
                    case unchecked ((int)0x80338126):
                    case unchecked ((int)0x80131500):
                        Status($"Error Gathering Service Accounts ({szMachine}) - most likely offline / firewall");
                        break;

                    case unchecked ((int)0x80070005):
                        Status($"Error Gathering Service Accounts ({szMachine}) - invalid permissions");
                        break;

                    default:
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            System.Diagnostics.Debugger.Break();
                        }

                        Status($"Error Gathering Service Accounts ({szMachine}) - PROVIDE TO SUPPORT - CIM UNKNKOWN ({_cex.HResult})");
                        break;
                    }
                    _exceptionThrown = true;
                }
                catch (Exception _ex)
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        System.Diagnostics.Debugger.Break();
                    }

                    Status($"Error Gathering Service Accounts ({szMachine}) - PROVIDE TO SUPPORT - UNKNKOWN ({_ex.GetType().Name}:{_ex.HResult})");
                    _exceptionThrown = true;
                }
                if (_exceptionThrown)
                {
                    _results.Clear();                    // clear results so we do not error and can continue.
                    System.Threading.Thread.Sleep(5000); // give them time to see the error
                }
            }
            return(_results.ToArray());
        }
Exemplo n.º 24
0
 /// <summary>
 /// An "overload" of the
 /// <see cref="Microsoft.Management.Infrastructure.CimSession"/>.QueryInstances
 /// method that takes only the namespace and query string as a parameters
 /// </summary>
 /// <param name="session">The CimSession to be queried</param>
 /// <param name="nameSpace">A string containing the namespace to run the query against</param>
 /// <param name="query">A string containing the query to be run</param>
 /// <returns>
 /// An IEnumerable interface that can be used to enumerate the instances
 /// </returns>
 internal static IEnumerable <CimInstance> QueryInstances(this CimSession session, string nameSpace, string query)
 {
     return(session.QueryInstances(nameSpace, CIMHelper.DefaultQueryDialect, query));
 }
Exemplo n.º 25
0
 private protected CimInstance GetCimInstance(CimSession ses) =>
 ses.QueryInstances(ns, dia, query).ToArray().FirstOrDefault();
Exemplo n.º 26
0
        private void OnServiceUpdate(object sender, EventArgs e)
        {
            Console.WriteLine("Atualizando lista de serviços WMI");

            try
            {
                string query;
                if (ServiceFilter != null)
                {
                    query = $"{_serviceQuery} WHERE DisplayName LIKE '%{ServiceFilter}%'";
                }
                else
                {
                    query = _serviceQuery;
                }

                AllServices = Session.QueryInstances(@"root\cimv2", "WQL", query);


                if (ServiceList.Count() > 0)
                {
                    //Loop through all services
                    foreach (CimInstance oneService in AllServices)
                    {
                        Services s       = CimInstanceConvert(oneService);
                        Services service = ServiceList.FirstOrDefault(i => i.Name == s.Name);

                        if (service.State != s.State)
                        {
                            service.Update(s);
                            string       subtitle;
                            PackIconKind icon;

                            switch (s.State)
                            {
                            case "Running":
                                subtitle = "Serviço foi inicializado";
                                icon     = PackIconKind.Notifications;
                                break;

                            case "Start Pending":
                                subtitle = "Serviço esta sendo inicializado";
                                icon     = PackIconKind.InfoCircle;
                                break;

                            case "Stopped":
                                subtitle = "Serviço foi parado";
                                icon     = PackIconKind.Dangerous;
                                break;

                            case "Stop Pending":
                                subtitle = "Serviço esta sendo parado";
                                icon     = PackIconKind.Warning;
                                break;

                            default:
                                subtitle = "Estado não encontrado";
                                icon     = PackIconKind.SackPercent;
                                break;
                            }

                            if (_enableNotification)
                            {
                                _notifier.ShowNotification(s.DisplayName, subtitle, icon, s.State, null, declineAction: n => CloseNotification(n));
                            }
                        }
                    }
                }
                else
                {
                    //Loop through all services
                    foreach (CimInstance oneService in AllServices)
                    {
                        Services s = CimInstanceConvert(oneService);
                        ServiceList.Add(s);
                    }
                }

                IsLoading   = false;
                IsConnected = true;
            }
            catch (Exception ex)
            {
                IsConnected = false;
                IsLoading   = false;
                snackMessageQueue.Enqueue(ex.Message);
                SnackbarNotify.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D20101"));
                _task.Stop();
                //ServiceList.Clear();
                log.Error(ex.Message);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Executes query and returns WMI object instances
        /// </summary>
        /// <param name="expression">LINQ expression</param>
        /// <returns>Query result as object</returns>
        public object Execute(Expression expression)
        {
            var translationResult = _wqlFactory.TranslateQuery(expression);
            var allInstances      = _connection
                                    .QueryInstances(
                _nameSpace,
                QueryDialect,
                translationResult.ToString());

            if (expression is MethodCallExpression methodCallExpression)
            {
                var                 returnInstanceType = methodCallExpression.Type;
                CimInstance         instance;
                IList <CimInstance> instances;
                switch (methodCallExpression.Method.Name)
                {
                case "Count":
                    return(allInstances.Count());

                case "First":
                    instance = allInstances.FirstOrDefault();
                    if (instance == null)
                    {
                        throw new InvalidOperationException("No object found!");
                    }

                    return(CreateObjectInstances(
                               returnInstanceType,
                               translationResult,
                               new[] { instance }).First());

                case "FirstOrDefault":
                    instance = allInstances.FirstOrDefault();
                    if (instance == null)
                    {
                        return(null);
                    }

                    return(CreateObjectInstances(
                               returnInstanceType,
                               translationResult,
                               new[] { instance }).First());

                case "Single":
                    instances = allInstances.ToList();
                    if (instances.Count != 1)
                    {
                        throw new InvalidOperationException("No single object found!");
                    }

                    return(CreateObjectInstances(
                               returnInstanceType,
                               translationResult,
                               new[] { instances.First() }).First());

                case "SingleOrDefault":
                    instances = allInstances.ToList();
                    if (instances.Count != 1)
                    {
                        return(null);
                    }

                    return(CreateObjectInstances(
                               returnInstanceType,
                               translationResult,
                               new[] { instances[0] }).First());

                default:
                    return(CreateObjectInstances(
                               returnInstanceType.GetGenericArguments()[0],
                               translationResult,
                               allInstances));
                }
            }

            return(CreateObjectInstances(
                       expression.Type.GenericTypeArguments[0],
                       translationResult,
                       allInstances));
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //string computer = "ILPT2113";
            //string domain = "ICERTIS.COM";
            //string username = @"*****@*****.**";

            string computer = "myfirstvm";
            string domain   = "";
            string username = "******";


            string plaintextpassword;

            Console.WriteLine("Enter password:"******"root\cimv2", "WQL", "SELECT * FROM Win32_Directory");
            var allPDisks  = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_DiskDrive");

            // Loop through all volumes
            foreach (CimInstance oneVolume in allVolumes)
            {
                // Show volume information

                if (oneVolume.CimInstanceProperties["DriveLetter"].ToString()[0] > ' ')
                {
                    Console.WriteLine("Volume ‘{0}’ has {1} bytes total, {2} bytes available",
                                      oneVolume.CimInstanceProperties["DriveLetter"],
                                      oneVolume.CimInstanceProperties["Size"],
                                      oneVolume.CimInstanceProperties["SizeRemaining"]);
                }
            }

            // Loop through all physical disks
            foreach (CimInstance onePDisk in allPDisks)
            {
                // Show physical disk information
                Console.WriteLine("Disk {0} is model {1}, serial number {2}",
                                  onePDisk.CimInstanceProperties["DeviceId"],
                                  onePDisk.CimInstanceProperties["Model"].ToString().TrimEnd(),
                                  onePDisk.CimInstanceProperties["SerialNumber"]);
            }



            Console.ReadKey();
        }
        private void submitNameButton_Click(object sender, RoutedEventArgs e)
        {
            //clear out the textboxes
            outputTextbox.Text       = "";
            diskInfoTextbox.Text     = "";
            computerInfoTextbox.Text = "";
            logTextbox.Text          = "";

            //computer name, domain, username, and password
            //used to actually connect to a machine and authenticate
            string computerName = computerNameTextbox.Text;
            string domain       = "net.ucf.edu";

/*          string username = usernameTextbox.Text;
 *          string password = passwordTextbox.Password;*/

            if (validateComputerName(computerName) == true && pingHost(computerName) == true)
            {
                logTextbox.AppendText($"Ping Successful for {computerName}\n");

                //computerNameValidLabel.Content = "";

                SecureString securePassword = new SecureString(); //change the password to a secure string
                foreach (char c in password)
                {
                    securePassword.AppendChar(c);
                }

                CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, domain, username, securePassword);

                WSManSessionOptions SessionOptions = new WSManSessionOptions();
                SessionOptions.AddDestinationCredentials(Credentials);

                CimSession Session = CimSession.Create(computerName, SessionOptions);

                //var allVolumes = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");

                //========================================== USERNAME ===================================================

                var allUserNames = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_ComputerSystem");

                foreach (CimInstance o in allUserNames)
                {
                    userLoggedInLablel1.Content = "User Logged In: " + Convert.ToString(o.CimInstanceProperties["Username"].Value);
                    logTextbox.AppendText($"{userLoggedInLablel1.Content}\n");
                }

                //========================================== RAM ===================================================

                var allComputerSystem = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_OperatingSystem");

                double freeRam       = 0;
                double totalRam      = 0;
                double usedRam       = 0;
                double ramPercentage = 0;

                foreach (CimInstance o in allComputerSystem)
                {
                    freeRam  = Convert.ToDouble(o.CimInstanceProperties["FreePhysicalMemory"].Value) / Math.Pow(2, 20);
                    totalRam = Convert.ToDouble(o.CimInstanceProperties["TotalVisibleMemorySize"].Value) / Math.Pow(2, 20);

                    usedRam = (totalRam - freeRam);

                    freeRam  = Math.Round(freeRam, 3);
                    usedRam  = Math.Round(usedRam, 3);
                    totalRam = Math.Round(totalRam, 3);

                    logTextbox.AppendText($"Used RAM: {Convert.ToString(usedRam)} GB\n");
                    logTextbox.AppendText($"Total RAM: {Convert.ToString(totalRam)} GB\n");
                }

                ramPercentage = (usedRam / totalRam) * 100;
                ramPercentage = Math.Round(ramPercentage, 3);

                liveRamProgressBar1.Value = ramPercentage;
                ramComputerLabel1.Content = $"RAM: {usedRam} GB / {totalRam} GB | {ramPercentage}%";

                //========================================== PROGRAMS ===================================================

                int totalPrograms = 0;

                if (programCheckbox.IsChecked == true)
                {
                    logTextbox.AppendText("Importing Programs\n");
                    var allPrograms = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Product");
                    foreach (CimInstance program in allPrograms)
                    {
                        string text = Convert.ToString(program.CimInstanceProperties["Name"].Value);
                        outputTextbox.AppendText(text + "\n");
                        totalPrograms++;
                    }
                }

                totalLabel.Content = $"Total Programs: {totalPrograms}";
                logTextbox.AppendText($"Total Programs: {totalPrograms}\n");
                //========================================== DISK INFO ===================================================
                if (diskInfoCheckbox.IsChecked == true)
                {
                    logTextbox.AppendText("Scanning Disk Drives\n");
                    var allPDisks = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_DiskDrive");
                    foreach (CimInstance pDisk in allPDisks)
                    {
                        string diskName     = Convert.ToString(pDisk.CimInstanceProperties["Name"].Value);
                        string modelName    = Convert.ToString(pDisk.CimInstanceProperties["Model"].Value);
                        string status       = Convert.ToString(pDisk.CimInstanceProperties["Status"].Value);
                        string serialNumber = Convert.ToString(pDisk.CimInstanceProperties["SerialNumber"].Value);

                        double size = Convert.ToDouble(pDisk.CimInstanceProperties["Size"].Value) / Math.Pow(2, 20);

                        diskInfoTextbox.AppendText($"Name: {diskName}\n" +
                                                   $"Model: {modelName}\n" +
                                                   $"Status: {status}\n" +
                                                   $"Serial Number: {serialNumber}\n" +
                                                   $"Size: {Math.Round(size, 3)} GB");
                    }
                }
                //======================================= COMPUTER INFO ===================================================
                if (computerInfoCheckbox.IsChecked == true)
                {
                    var allOS = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_OperatingSystem");
                    //var allComputerSystem = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_OperatingSystem");

                    //============== allOS ==============
                    foreach (CimInstance os in allOS)
                    {
                        //======= Available Memory =======
                        string availableMemory = Convert.ToString(Convert.ToDouble(os.CimInstanceProperties["FreePhysicalMemory"].Value) / Math.Pow(2, 10));
                        availableMemory = Convert.ToString(Math.Round(Convert.ToDouble(availableMemory), 0, MidpointRounding.AwayFromZero));
                        //======= Last Boot Up Time =======
                        DateTime lastBootUpTimeDate = Convert.ToDateTime(os.CimInstanceProperties["LastBootUpTime"].Value);
                        string   lastBootUpTime     = lastBootUpTimeDate.ToString(@"yyyy-MM-dd hh:mm:ss");
                        //======= Operating System =======
                        string osName = Convert.ToString(os.CimInstanceProperties["Caption"].Value);
                        //======= OS Install Date =======
                        DateTime osInstallDate = Convert.ToDateTime(os.CimInstanceProperties["InstallDate"].Value);
                        string   osInstall     = osInstallDate.ToString(@"yyyy-MM-dd hh:mm:ss");
                        //======= OS Version =======
                        string version = Convert.ToString(os.CimInstanceProperties["Version"].Value);

                        computerInfoTextbox.AppendText($"Operating System: {osName}\n");
                        computerInfoTextbox.AppendText($"Windows Version: {version}\n");
                        computerInfoTextbox.AppendText($"Free Memory [MB]: {availableMemory}\n");
                        computerInfoTextbox.AppendText($"Last Boot Up Time: {lastBootUpTime}\n");
                        computerInfoTextbox.AppendText($"OS Install Date: {osInstall}\n");
                    }

                    //============== allComputerSystem ==============
                    foreach (CimInstance comp in allComputerSystem)
                    {
                        //======= User Logged In =======
                        string userLoggedIn = "";
                        try { Convert.ToString(comp.CimInstanceProperties["UserName"].Value); } catch { userLoggedIn = "None"; }


                        computerInfoTextbox.AppendText($"User Logged In: {userLoggedIn}\n");
                    }
                }

                if (processCheckbox.IsChecked == true)
                {
                    var       allProcessList   = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    ArrayList processArrayList = new ArrayList();

                    foreach (CimInstance o in allProcessList)
                    {
                        processArrayList.Add(Convert.ToString(o.CimInstanceProperties["Name"].Value));
                        if (Convert.ToString(o.CimInstanceProperties["Name"].Value).Equals("svchost.exe") == false)
                        {
                            processComputerTextbox1.AppendText(Convert.ToString(o.CimInstanceProperties["Name"].Value) + "\n");
                        }
                    }

                    processCountLabel1.Content = $"Total Processes: {processArrayList.Count}";
                    logTextbox.AppendText($"Process Count: {processArrayList.Count}");
                }
            }
            else
            {
                //computerNameValidLabel.Content = "Computer Name Invalid";
                //computerNameValidLabel.Foreground = Brushes.Red;
            }
        }