1

I've been searching to find out how to get a remote PC's System.Environment.TickCount. Using this simple code gets the info I want from my local PC but I can't work out how to get the same info for each PC in our domain network. I want to run this from our server.

TimeSpan t = TimeSpan.FromMilliseconds(System.Environment.TickCount);
MessageBox.Show(t.Days.ToString() + "days, " + t.Hours.ToString() + "hrs & " + t.Minutes.ToString() + "mins.");

I've got this code to get all computer names in the network:

public List<String> ListNetworkComputers()
{
    List<String> _ComputerNames = new List<String>();
    String _ComputerSchema = "Computer";
    System.DirectoryServices.DirectoryEntry _WinNTDirectoryEntries = new System.DirectoryServices.DirectoryEntry("WinNT:");
    foreach (System.DirectoryServices.DirectoryEntry _AvailDomains in _WinNTDirectoryEntries.Children)
    {
        foreach (System.DirectoryServices.DirectoryEntry _PCNameEntry in _AvailDomains.Children)
        {
            if (_PCNameEntry.SchemaClassName.ToLower().Contains(_ComputerSchema.ToLower()))
            {
                _ComputerNames.Add(_PCNameEntry.Name);
            }
        }
    }
    return _ComputerNames;
}

How can I use this info to get the System.Environment.TickCount from each PC? I've tried PsExec.exe but I've really got no clue how to get it to work for me. I tried this but it doesn't work:

var list = ListNetworkComputers();
foreach (var pc in list)
{
    string output = "";
    using (var process = new System.Diagnostics.Process())
    {
        process.StartInfo.FileName = @"C:\PsExec.exe";
        process.StartInfo.Arguments = @"\\" + pc + " cmd /c echo " + "System.Environment.TickCount";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();
        output = process.StandardOutput.ReadToEnd();
    }
    int count = 0;
    Int32.TryParse(output, out count);
    TimeSpan ts = TimeSpan.FromMilliseconds(count);
    MessageBox.Show(pc + ": " + ts.Days.ToString() + "days, " + ts.Hours.ToString() + "hrs & " + ts.Minutes.ToString() + "mins.");
}
Mutley
  • 77
  • 2
  • 13

2 Answers2

0

Instead of using "cmd.exe", maybe you can use PowerShell? If so, it's a simple command to print that property: [System.Environment]::TickCount

RobSiklos
  • 8,348
  • 5
  • 47
  • 77
0

I needed to do the same thing: get a remote PC's System.Environment.TickCount.

I came up with this solution (using Windows Management Instrumentation or WMI LocalDateTime - LastBootUpTime), but it's not 100% accurate compared to Environment.TickCount (see code comment below).

So I checked for other solutions online. Turns out @HansPassant suggested the same thing. For my use case, the +/-100 ticks discrepancy shouldn't matter.

using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using System;
using System.Linq;
using System.Security;

namespace TickCountTest
{
    class Program
    {
        /// <summary>
        /// Print the system TickCount (converted from Win32_OperatingSystem LocalDateTime - LastBootUpTime properties).
        /// Why? Because this technique can be used to get TickCount from a Remote machine.
        /// </summary>
        public static void Main(string[] args)
        {
            var tickCount = GetRemoteMachineTickCount("REMOTEMACHINENAME");

            if (!tickCount.HasValue)
            {
                throw new NullReferenceException("GetRemoteMachineTickCount() response was null.");
            }

            Console.WriteLine($"TickCount: {tickCount}");
            Console.ReadKey();
        }

        /// <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>
        private static 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 cimInstance = cimInstances.First();
                var lastBootUpTime = Convert.ToDateTime(cimInstance.CimInstanceProperties["LastBootUpTime"].Value);
                var localDateTime = Convert.ToDateTime(cimInstance.CimInstanceProperties["LocalDateTime"].Value);

                var timeSpan = localDateTime - lastBootUpTime;
                var tickCount = Convert.ToInt32(timeSpan.TotalMilliseconds);

                var discrepancy = tickCount - baseLineTickCount; // Note: discrepancy about +/- 100 ticks

                return tickCount;
            }

            return null;
        }
    }
}
JohnB
  • 18,046
  • 16
  • 98
  • 110