Как посмотреть время работы windows server 2012

Как посмотреть uptime в Windows Server

Как посмотреть uptime(время работы) в Windows Server 2008/R2/2012/R2 ?

1. В Windows 7/8/Server 2008 , открыть диспетчер задач и на вкладке «Быстродействие/Производительность» посмотреть время работы Windows:
taskmanager taskmanagerwin8

2. Нужно запустить в командной строке утилиту systeminfo. В ней можно узнать время загрузки системы. Открываем командную строку и вводим:
systeminfo | find «System Boot» или systeminfo | find «Время загрузки» :
cmd-uptime-windows

Как удалённо узнать время последней загрузки Windows? Uptime

С помощью PSExec.
Computername — имя удалённого компьютера:

C:scriptsPsExec.exe \Computername net statistics workstation

Для англоязычной версии операционной системы:

C:scriptsPsExec.exe \Computername systeminfo | find "System Boot Time:"

Для русскоязычной версии операционной системы:

C:scriptsPsExec.exe \Computername systeminfo | find "Время загрузки системы:"

С помощью Powershell и службы событий:

Get-WinEvent -ComputerName Computername -LogName system  | where {$_.id -eq "6005"}
Get-EventLog -ComputerName Computername -LogName System | Where-Object {$_.EventID -eq "6005"}


Как узнать аптайм сервера

Аптайм (uptime) — это время непрерывной работы сервера, т.е. время, прошедшее с момента загрузки операционной системы. С помощью аптайма можно оценить, как долго сервер работает без сбоев и перезагрузок. В операционных системах Windows есть много способов посмотреть аптайм, вот некоторые из них.

Самый простой способ — это запустить Task Manager и перейти на вкладку «Performance».

аптайм в Task Manager

Атайм можно посмотреть и в свойствах сетевого подключения.

аптайм в свойствах сетевого подключения

Также аптайм можно определить по системным логам. При выключении и перезагрузке сервера происходит остановка и запуск службы Event Log, поэтому мы можем открыть Event Viewer и отфильтровать события с кодом 6006 (остановка) или 6005 (старт службы).

аптайм в Event Viewer

Узнать время последнего старта операционной системы можно из командной строки, введя команду systeminfo и найдя строку System Boot Time.

аптайм из командной строке

Можно ввести команду net statistics workstation и посмотреть, с какого момента времени собирается статистика. Как правило, это момент загрузки системы.

аптайм в статистике сети

Ну и конечно для выяснения аптайма можно воспользоваться WMI и PowerShell. Выяснить время старта ОС можно вот так:

$wmi = Get-WmiObject Win32_OperatingSystem
$wmi.LastBootUpTime

Время выводится в несколько неудобном формате, поэтому сконвертируем его:

$wmi.ConvertToDateTime($wmi.LastBootUpTime)

И выведем время работы с точностью до миллисекунды, вычтя из текущей даты дату последней загрузки:

$wmi.ConvertToDateTime($wmi.LocalDateTime) — $wmi.ConvertToDateTime($wmi.LastBootUpTime)

аптайм в PowerShell

Бывают ситуации когда необходимо выяснить сколько времени работает сервер/ клиентская машина без перезагрузки. Для этого вовсе не обязательно пользоваться сторонними утилитами, достаточно использовать стандартные средства Windows. В этой статье я опишу все известные мне способы определения времени последней перезагрузки/ выключения Windows.

1 Способ определить длительность работы Windows без перезагрузки.

Один из способ определить время работы ОС Windwos запустить Диспетчер задач, перейти во вкладку «Быстродействие», в строке «Время работы» вы увидите, как долго включен сервер:

Фото Определяем время загрузки Windows server

 компьютер:

Фото Определяем время загрузки Windows workstation

2 Способ определить время работы Windows без выключения.

Еще один весьма простой способ получить информацию о времени работы операционной системой- запустить командную строку «Пуск» — «Программы» — «Стандартные» — «Командная строка» или воспользоваться сочетанием горячишь клавиш «Win» + «R» в строке поиска ввести «CMD» и нажать клавишу Enter.

В командной строке введите команду: net statistics workstation. В результате вы увидите время начала работы ОС Windows.

Скрин Определение времени загрузки компьютера/ сервера с помощью командной строки

3 Способ определить время последней перезагрузки/ выключения компьютера/ сервера Windows.

Запустите командную строку и выполните команду:

для англоязычной версии операционной системы systeminfo | find «System Boot Time:»

Скриншот Как определить время загрузки компьютера/ сервера в английской версии Windows в командной строке

для русскоязычной версии операционной системы systeminfo | find «Время загрузки системы:».

Скриншот Как определить время загрузки компьютера/ сервера в русской версии Windows в командной строке

4 Способ определения времени работы ОС Windows.

 Время загрузки можно посмотреть в сетевых подключениях (если сеть не отключалась). Нажмите правой кнопкой мыши на сетевых подключениях в панели управления и выберите «Центр управления сетями и общим доступом» (англ. Open Network and Sharing Center).

Фотография Определение времени перезагрузки Windows

Далее выберите «Изменения параметров адаптера» (англ. Change adapter settings).

Фото как поределить время загрузки Windows

Далее нажмите на подключении двойным кликом мыши в открывшемся окне в строке Длительность (англ. Duration) вы увидите время работы ОС Windows.

Скрин способ определить когда загрузилась Windows

5 Способ определить время с которого работает компьютер/ сервер.

Так же информацию можно найти в Журналах Windows (Event Viewer). Для этого:

На компьютере нажмите правой кнопкой мыши на ярлыке «Компьютер», выберите «Управление», в окне Управления компьютером выберите «Журнал Windows» — «Система». Теперь найдите событие 6005 — оно говорит о том, что компьютер загрузился соответственно в столбце Дата и время будет указано, когда это произошло.

Фото Определяем время загрузки Windwos с помощью журнала Windows

На сервере откройте «Server  Manager», выберите «Diagnostics» — «Event Viewer» — «Windows Log» — «System». Найдите Event ID 6005 он отвечает за время загрузки сервера.

Фото Определяем время загрузки Windwos с помощью Windows Logs

Я очень надеюсь, моя статья помогла Вам! Просьба поделиться ссылкой с друзьями:

Всем доброго времени суток, дорогие друзья, знакомые, читатели, почитатели и прочие личности.

Для многих не секрет, что в linux легко получить значение uptime, которое условно означает время работы системы с момента запуска без перезагрузок, выключений и тп. Как правило это делается той же командой, выполненной в терминале, либо, как аналог, это может быть top -c или w.

Как получить uptime в Windows с помощью консоли (cmd) - иконка статьи

В Windows чаще всего люди получают это значение с помощью стороннего софта, как пример, — это AIDA64 и аналогичные анализаторы системы. Но вообще говоря, всё довольно просто.

Сегодня краткая статья на эту тему.

Получение uptime из консоли или диспетчера задач

В младших версиях серверов, а так же в пользовательских системах, аля Windows Vista и тп, чаще всего достаточно перейти на вкладку «Производительность» (или «Быстродействие«) используя «Диспетчер задач» (CTRL+ SHIFT+ ESC на клавиатуре), где найти соответствующую строку:

Как получить uptime в Windows с помощью диспетчера задач - скриншот 1

Чтобы запустить командную строку, нажмите  сочетание клавиш Win+R и в появившемся окне «Выполнить» введите cmd. Сама утилита командной строки лежит обычно в папке C:WindowsSystem32cmd.exe.

Как получить uptime в Windows с помощью консоли (cmd) - скриншот 1

Вот так по умолчанию выглядит командная строка Windows. Как видите, все достаточно аскетично. Если захочется более симпатичного вида, щелкните правой кнопкой мыши по заголовку окна  и выберите пункт «Свойства», вкладка «Цвета», на которой вы можете выбрать цвет шрифта и фона.

Как получить uptime в Windows с помощью консоли (cmd) - скриншот 2
В открывшемся окне сверху вы видите традиционный знак копирайта мелкомягких, а чуть ниже строка с текущим каталогом и мигающий курсор, приглашающий начать работу. Введите команду:

systeminfo

Чтобы получить вывод информации о системе. Там найдите строку «Время загрузки системы«:

Как получить uptime в Windows с помощью консоли (cmd) - скриншот 3

Это будет время последнего запуска с момента выключения, перезагрузки, синего экрана смерти и пр. Можно так же сделать это с помощью команды:

net statistics workstation

Вывод ответа будет аналогичный:

Как получить uptime в Windows с помощью консоли (cmd) - скриншот 4

В частности, это время можно посмотреть в журнале событий (статья вот, событие искать по коду 6005, означающее фактический старт системы), либо используя uptime.exe, требующий загрузки отдельных обновлений, пакетов и тп, поэтому говорить мы о нём сейчас не будем.

Послесловие

Вот такая простая команда, позволяющая быстро узнать, когда была последняя перезагрузка. Таким нехитрым образом можно узнать были ли проблемы с сервером и когда, а так же отловить их в журнале событий, поймать домочадцев на хитростях с перезагрузками и прочее прочее.

На этом, пожалуй всё. Сегодня кратенько.
Оставайтесь с нами.

Like many things in the Microsoft Windows universe, there are several ways to check Up Time of your systems.

Fortunately, they are all easy and quick!

How to Check Windows Uptime via Command Line

There are several really simple ways to check uptime in Windows Server 2016, 2019, and Windows 10 using Command Prompt or PowerShell.

Rather than bore you with the details lets jump into each of them starting with the easiest.

Check Windows Uptime with Net Statistics

This one is super simple. You just need to open command prompt or PowerShell and type either:

net statistics server

or

net statistics workstation

If you’re on a server OS such as Server 2016 or Server 2019 then use the command ending in Server. If you’re using a workstation OS such as Windows 8.1 or Windows 10 use the command ending in workstation.

The output will look like this:

C:WINDOWSsystem32>net statistics workstation
Workstation Statistics for \DOMCON1


Statistics since 9/17/2018 4:40:11 PM


  Bytes received                               6094
  Server Message Blocks (SMBs) received        12
  Bytes transmitted                            5164
  Server Message Blocks (SMBs) transmitted     0
  Read operations                              0
  Write operations                             0
  Raw reads denied                             0
  Raw writes denied                            0

  Network errors                               0
  Connections made                             0
  Reconnections made                           0
  Server disconnects                           0

  Sessions started                             0
  Hung sessions                                0
  Failed sessions                              0
  Failed operations                            0
  Use count                                    8
  Failed use count                             0

The line starting with “Statistics since …” displays the last time your computer was booted up.

How to Check Uptime in Windows with SystemInfo

Another way to see the the last boot time of your machine using a simple command prompt command is to use:

systeminfo

You can cut down the output to just the system boot time line by using a pipe and the find operator like so:

systeminfo | find “System Boot Time”

Which outputs:

C:WINDOWSsystem32>systeminfo | find "System Boot Time"
System Boot Time:          9/17/2018, 4:40:10 PM

If you want to check the boot time on a remote server you can either use the this command:

systeminfo /s remoteservername | find “System Boot Time”

or use a utility like PSExec from Microsoft PSTools to enter a remote command line.

Use the Windows Uptime Command (Uptime.exe)

The original Windows Server Uptime command was part of a program released by Microsoft called Uptime.exe. You used to be able to download it via KB232243. Now you have resort to downloading it from the Internet Archive URL or our website here.

Simply download the .exe and place inside your C:WindowsSystem32 folder.

You can then run the following command to find the system uptime:

uptime

Or you can use this command to see the uptime on a remote server or workstation:

uptime remoteservername

Which results in:

C:WINDOWSsystem32>uptime
\DOMCON1 has been up for: 1 day(s), 12 hour(s), 6 minutes(s), 58 seconds(s)

Now I did say original Uptime command earlier. That is because a new uptime.exe was developed under the open source project uptimeEXE which you can download here at Codeplex.

The command syntax is nearly identical to the original Uptime.exe as you can see here:

C:WINDOWSsystem32>uptime
 08:20:14 uptime 08:48:27

The only drawback to this updated version is that it doesn’t contain the extra options such as checking windows uptime on a remote computer.

Use Task Manager to Check Server Uptime

If you’re more of a GUI type person then you’ll be happy to know that you can use Task Manager to view system uptime.

All you have to do is open Task Manager (can search start menu for Task Manager, right click the task bar and click on Task Manager, or search for taskmgr.exe) and open the Performance tab.

Inside the CPU window, in the bottom left hand corner, you’ll find the Up time.

Recommended for You: Solarwinds Hybrid Systems Monitoring Bundle

Know which applications are having issues in your environment before users complain? Know which systems are causing those problems or were recently changed by someone? How about which servers are about to have problems like running out of space or memory?

Automate collection of data and alerting on your local or cloud applications and servers with Solarwinds Hybrid Systems Bundle so you have these answers.

Get insight into Active Directory, DNS, DHCP, and your Virtual and Applications environments, both locally and cloud hosted, without needing to mess with complex templates or knowing a single line of code.

What is the simplest way to find out how long a computer is turned on Windows?

asked Jul 23, 2009 at 9:06

Juozas Kontvainis's user avatar

  • Run command line
  • Type Systeminfo
  • Find «System Boot Time»

    Days: 10 Hours: 10 Minutes: 10 Seconds: 10

For shorter result you can use:

systeminfo | find "Boot Time" 

Community's user avatar

answered Jul 23, 2009 at 9:13

MicTech's user avatar

11

there is great command line tool from Microsoft uptime.exe:

http://www.microsoft.com/downloads/details.aspx?FamilyID=BC18FFDB-D6FE-400B-B892-94783AE44C91&displaylang=en

good thing with this tool is it works really fast.

Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
server Name or IP address of remote server to process.
/s Display key system events and statistics.
/a Display application failure events (assumes
/s).
/d: Only calculate for events after mm/dd/yyyy.
/p: Only calculate for events in the previous n days.
/heartbeat Turn on/off the system’s heartbeat
/? Basic usage.
/help Additional usage information.

answered Jul 23, 2009 at 9:31

Andrija's user avatar

AndrijaAndrija

2,4063 gold badges25 silver badges28 bronze badges

2

Open the command prompt and type:

net stats srv | find "Statistics"

Example output:

>net stats srv | find "Statistics"
Server Statistics for \4IFS-SANDER
Statistics since 22/07/2009 10:14:14

Source (MS KB).

Edit: Actually this will tell you the date and time when the pc was up from, not the duration.

Charlie Joynt's user avatar

answered Jul 23, 2009 at 9:10

svandragt's user avatar

svandragtsvandragt

3,2034 gold badges23 silver badges28 bronze badges

5

On Windows 7 / Windows Server 2008 and above, this information is displayed in task manager under the «Performance tab».

This can be quicker then using the command line and works in cases where you might have WMI issues preventing you from running systeminfo.

where to find uptiem

If you need to find this remotely, you could also run

systeminfo /s SERVERNAME | find «Time:»

from the command line.

answered Dec 3, 2015 at 4:45

Brett Larson's user avatar

7

Following command gives last reboot time for a remote system:

systeminfo /s server_name | find "System Boot Time"

Charlie Joynt's user avatar

answered May 22, 2013 at 5:46

Dhananjay's user avatar

DhananjayDhananjay

611 silver badge1 bronze badge

In windows 10, this is located in Task manager > Expand More Details Chevron > Performance > CPU > At the bottom, Up time.

enter image description here

answered Sep 15, 2020 at 17:03

Wasif's user avatar

WasifWasif

7,5932 gold badges15 silver badges32 bronze badges

If you have the Windows Server 2000 or 2003 resource kits try

srvinfo -ns [\server] | Findstr "Time"

Note: Srvinfo.exe will not run on a 64-bit versions of Windows, due to it being 16-bit.

Ƭᴇcʜιᴇ007's user avatar

Ƭᴇcʜιᴇ007

111k19 gold badges198 silver badges262 bronze badges

answered Dec 28, 2011 at 22:03

Don's user avatar

Using SYSTEMINFO with PowerShell

For those who like using PowerShell, you can use the answer(s) above and wrap systeminfo in a PowerShell function to get a DateTime result for when the server last booted:

function Get-ComputerBootTime {
  param($ComputerName = (hostname))

  $SystemInfo = & systeminfo /s $ComputerName | Select-String "System Boot Time")
  if($SystemInfo -match "[d/]+,s+S+"){
    return (Get-Date $matches[0])
  }
}

And then call the function, for example:

[PS]> $BootTime = Get-ComputerUptime -ComputerName MYSERVER

To get the Uptime for the server, you compare with the current time:

[PS]> $UpTime = (Get-Date) - $BootTime

This is a TimeSpan, which includes properties such as TotalDays:

[PS]> $UpTime.TotalDays
14.1827364

answered Mar 1, 2017 at 11:19

Charlie Joynt's user avatar

1

Yet another way:

C:>wmic path Win32_OperatingSystem get LastBootUpTime
LastBootUpTime
20200908203723.500000+120

answered Sep 9, 2020 at 6:45

hlovdal's user avatar

hlovdalhlovdal

3,0204 gold badges31 silver badges38 bronze badges

Anyone wanting the unix time (seconds since the epoch) that are using cygwin can try this:

date +%s -d "$(wmic path Win32_OperatingSystem get LastBootUpTime | grep -E '^[0-9]' | awk '{print substr($1,1,4) "-" substr($1,5,2) "-" substr($1,7,2) " " substr($1,9,2) ":" substr($1,11,2) ":" substr($1,13,2);}')"

answered Dec 4, 2020 at 13:54

MattBianco's user avatar

MattBiancoMattBianco

2,0932 gold badges19 silver badges26 bronze badges

Sometimes the uptime is dificult and user is not logged out and the two prety much coincide so I use this command to display the LOGON TIME

query USER

or shorter even:

quser

which prints something like:

C:Userseflorinescu>query  USER
 USERNAME                 SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>eflorinescu              console             2  Active    2+23:44  5/7/2018 8:25 AM

also even better using PowerShell

Get-ComputerInfo | select-object oslastbootuptime

answered May 7, 2018 at 13:23

Eduard Florinescu's user avatar

2

In PowerShell either of the following commands will work

Get-WmiObject win32_operatingsystem |% {$_.ConverttoDateTime($_.lastbootuptime)}
(Get-CimInstance -ClassName win32_operatingsystem).lastbootuptime

Get-CimInstance is both shorter and more future proof, because Get-WmiObject and wmic have been both deprecated

You can also run (Get-WmiObject win32_operatingsystem).lastbootuptime but the output is less readable because it’s a raw time string

See PowerTip: Get the Last Boot Time with PowerShell

answered Jun 10, 2021 at 4:32

phuclv's user avatar

phuclvphuclv

24.7k13 gold badges105 silver badges219 bronze badges

Windows uptime is a measurement that many server administrators use to troubleshoot day-to-day issues that may arise in the environment. In this article, you’re going to learn how to check boot time in Windows 10 and Windows Server. You’re free to use whichever way is easiest for you. Use this article as a future reference.

The article will be broken up into two main parts; checking server uptime and finding historical Windows uptime. The first part will focus on finding how much time the computer has been up since its last reboot. This is called “current” uptime in this article.

The second part of the article will focus on finding “historical” uptime meaning a reboot on how long a Windows system was up between multiple reboots. Using PowerShell, you’ll learn how to parse the Windows event log to pull historical uptime numbers.

How to Check Boot Time in Windows 10 and Windows Server

To get started, let’s now jump into a few different ways to find the current Windows uptime.

You’ll be seeing a demonstration of how to check boot time in Windows 10 by running commands locally on a Windows system through this section. But know that by using PowerShell Remoting, you can also perform these checks remotely (excluding task manager).

Task Manager

One of the most simple and straightforward ways to find uptime is to simply open Task Manager.

To check Windows uptime with Task Manager, right-click the Windows taskbar and select Task Manager or press CtrlShiftEsc. Once Task Manager is open, click on the Performance tab. Under the Performance tab, you will see a label of Up Time.

Finding Windows uptime with task manager
Finding Windows uptime with task manager

Event Viewer

Event Viewer is very commonly used by most sysadmins on a regular basis, which makes it a great option for a non-command line-related method of retrieving uptime. Event ID 6005 and 6006 can be used to identify when the event log service starts or stops, which occurs during boot/shut downtimes. Follow these steps to identify uptime via Event Viewer:

  • Bring up the Start Menu and simply search for Event Viewer, you can also get to it via Computer Management.
  • On the left, expand the Windows Logs section and select System
  • Now that we are querying only System related events, click “Filter Current Log…” on the right hand side of your window
  • In the Event ID field (by default this will be prefilled with text stating “All Event IDs”) we need to search for our applicable Event IDs, type “6005, 6006” then click OK

You can then compare the two times to create a total uptime. Also, since many instances of these events are stored, we can query the history of uptimes!

You now have filtered Event Logs that will show you not only the last time but all known times in which there has been a bootup/shut down.

PowerShell

PowerShell has a few different ways you can retrieve uptime. You can either query WMI or use the Windows event log.

When querying WMI, you can query the Win32_OperatingSystem class and select the LastBootUpTime property as shown below.

PS51> Get-CimInstance Win32_OperatingSystem | Select-Object LastBootUpTime

LastBootUpTime      
--------------      
9/25/2019 9:37:37 PM

To query the Event Log via PowerShell, use the Get-WinEvent cmdlet. You’ll need to search for event IDs 6005 or 6006 that indicate the last time the machine was started.

PS51> Get-WinEvent -ProviderName EventLog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006} | Select-Object -First 1 TimeCreated

TimeCreated         
-----------         
9/25/2019 9:37:52 PM

WMIC

WMIC provides a command-line interface for WMI and is a tried and true method that has been used for many years. To query via uptime via WMIC you query the Win32_OperatingSystem WMI class again although a bit under the covers. You can see below you can use the WMIC syntax os get lastbootuptime to return the last time the server was started.

> wmic os get lastbootuptime

LastBootUpTime             

20190925213737.500000-240

You do not have to download anything to leverage WMIC, as it comes pre-installed with Windows.

System Information Utility

The systeminfo command displays detailed configuration info about a computer and can be used to query system uptime. By using the built-in find command line tool you can parse the text to retrieve the data you need.

Simply open up either Command Prompt or PowerShell and type systeminfo | find.

> systeminfo | find "System Boot Time:"

System Boot Time:          9/25/2019, 9:37:37 PM

You do not have to download anything to leverage systeminfo, as it comes pre-installed with Windows.

Net Statistics Command

You can also quickly query uptime via Net Statistics or more commonly known as net stats. The net stats command returns general information about your session. You can see below the Statistics since… line. This date indicates when the machine was started.

> net stats srv

Workstation Statistics for \NATES-PC


Statistics since 9/25/2019 9:37:52 PM

--SNIP--

The command completed successfully.

Uptime Command

If you need a small, portable utility to find Windows uptime, look no further than NeoSmart Technologies’ Uptime command for Windows. This utility is perfect for quickly querying uptime on any Windows version. The major benefit of this tool is the convenience factor. If you find yourself using this many times per day you may want to consider this method.

After downloading the tool, extract uptime.exe to %WinDir%System32. Then open up a command prompt and simply type uptime.

Uptime tool
Uptime tool

To run this tool remotely, you’d first need to copy the tool to the Windows systems you’re checking uptime on.

Introducing the Get-ServerUptimeReport script

So you don’t have to write the PowerShell yourself, download a community script called Get-ServerUptimeReport.ps1.

PS51> Install-Script -Name Get-ServerUptimeReport

This script allows you to provide a computer name as a parameter. It will then parse the System event log of the computer and find both a start and stop event to compare the two. It will then return the total time the server was online until the event log has rolled.

Below is an example of using this script on a server. It will return the total uptime for all of the events the server has in the event log, including the current uptime.

PS51> ./Get-ServerUptimeReport.ps1 -ComputerName sqlsrv1

Startup Shutdown Uptime (Days) Uptime (Min)
------- -------- ------------- ------------
9/16/2017 12:40:00 PM 9/22/2017 4:20:11 PM 6.15 8860.18
9/16/2017 10:22:49 AM 9/16/2017 12:22:36 PM 0.08 119.79
9/16/2017 3:22:12 PM 9/22/2017 4:20:11 PM 6.04 8697.98

Finding Windows Uptime Across Many Servers

This script is a quick way to find the uptime of a single server across many days. But what if you need this information for lots of servers at once? To do this, you can gather up a list of servers and then pass each computer name, one at a time, to this script.

As an example, define all your servers in an array in the PowerShell console. In this example, the variable array will be called $servers.

In reality, though, you might be pulling server names from Active Directory, Hyper-V, or a text file. As long as you can build an array of server names, you’re fine.

Define all the server names and then iterate over each one with a loop, as shown below.

$servers = 'WEBSRV1','SQLSRV1'
foreach ($server in $servers) {
	Get-ServerUptimeReport.ps1 -ComputerName $server
}

Startup Shutdown Uptime (Days) Uptime (Min)
------- -------- ------------- ------------
9/16/2017 12:45:48 PM 9/22/2017 4:25:39 PM 6.15 8859.86
9/16/2017 10:42:52 AM 9/16/2017 12:42:34 PM 0.08 119.7
9/16/2017 2:42:17 PM 9/22/2017 4:25:39 PM 6.07 8743.38
9/16/2017 12:40:00 PM 9/22/2017 4:25:39 PM 6.16 8865.65
9/16/2017 10:22:49 AM 9/16/2017 12:22:36 PM 0.08 119.79
9/16/2017 3:22:12 PM 9/22/2017 4:25:39 PM 6.04 8703.46

This code works, but you can’t determine which server each row references. Add a server name to the output like below using a calculated property.

$servers = 'WEBSRV1','SQLSRV1'
foreach ($server in $servers) {
	Get-ServerUptimeReport.ps1 -ComputerName $server | Select-Object -Property *,@{n='ServerName';e={$server}}
}

Startup Shutdown Uptime (Days) Uptime (Min) ServerName
------- -------- ------------- ------------ ----------
9/16/2017 12:45:48 PM 9/22/2017 4:34:59 PM 6.16 8869.19 WEBSRV1
9/16/2017 10:42:52 AM 9/16/2017 12:42:34 PM 0.08 119.7 WEBSRV1
9/16/2017 2:42:17 PM 9/22/2017 4:34:59 PM 6.08 8752.71 WEBSRV1

Startup Shutdown Uptime (Days) Uptime (Min) ServerName
------- -------- ------------- ------------ ----------
9/16/2017 12:40:00 PM 9/22/2017 4:35:01 PM 6.16 8875.01 SQLSRV1
9/16/2017 10:22:49 AM 9/16/2017 12:22:36 PM 0.08 119.79 SQLSRV1
9/16/2017 3:22:12 PM 9/22/2017 4:35:01 PM 6.05 8712.81 SQLSRV1

We now have an excellent little tool that can provide us a quick report on uptime for our servers over time!

Summary

You’ve now seen many different ways to find Windows uptime. Regardless of which option you choose, you’ll receive the same information. Choose the best one for your own context.

And remember if you need a historical report of uptime history, don’t forget about the Get-ServerUptimeReport PowerShell script!

Как увидеть время простоя пользователей на RDP-сервере

есть ли быстрый и простой способ увидеть время простоя сеанса пользователей на сервере RDP?

Диспетчер служб терминалов может предоставить вам эту информацию.

в разделе Администрирование — > Службы терминалов — > Диспетчер служб терминалов

затем выберите хост в левой панели и в средней панели выберите вкладку» сеансы». Там будет список всех активных сессий и есть столбец «IdleTime».

выход intererpeted как «дни+часы: минуты». Так, например, если выходные данные «4+11: 23» пользователь бездействовал в течение 4 дней, 11 часов, 23 минут.

также стоит отметить, что вы можете выйти из этих сессий, щелкнув правой кнопкой мыши и отключив их. Хотя было бы неплохо сначала позвонить им :p

Edit: Ну, это хороший ответ для версий сервера до 2012 года: (но поскольку они исключили Диспетчер служб терминалов из более новых версий сервера, похоже, что этот сценарий powershell может быть лучшим вариантом: https://gallery.technet.microsoft.com/scriptcenter/Get-LoggedOnUser-Gathers-7cbe93ea

Я предполагаю, что IdleTime сообщается в минутах, так как мои начальные тесты отображают только отдельные целые числа.

начиная с Windows 2008 команда quser строительство.

отображает сведения о сеансах пользователей на сервере узел сеансов удаленных рабочих столов.

фактически сценарий PowerShell, связанный с in answer, просто выполняет эту команду. OP попросил быстрый и простой способ, это определенно быстрее, чем загружать и выполнять PS-скрипт.

пример из Windows Server 2012 R2:

количество в перед + дней, так что 15+15:12-15 дней, 15 часов и 12 минут.

внимание! В документации сказано, что это то же самое, что и running query user . Команда query не существует на моих серверах. Не уверен, что это отдельная установка или часть установки компонента.

вы можете использовать powershell для поиска различных пользователей или простоя нескольких серверов Скрипт создан пользователем » Cookie.Монстр » на technet Get-UserSession-Parse запрос user result

Windows

Открываем командную строку.

Для этого нажимаем комбинацию клавиш Win + R и в появившемся окне вводим cmd:

Ввод команды cmd для запуска командной строки

И нажимаем OK. Откроется командная строка.

1. Команда net stats

Введем команду net stats srv

Среди результатов увидим Статистика после .

Время работы Windows при выводе статистики

Это и будет, так называемый, uptime windows или время работы с момента последнего запуска.

2. Команда systeminfo

Для более детальной информации также можно ввести следующую команду:

Она покажет детальную информацию, в том числе общее (суммарное) время работы компьютера:

Время загрузки системы после ввода systeminfo

* где дата установки — дата и время, когда система была запущена в первые; время загрузки системы — дата и время, когда система была перезагружена последний раз.

Время выключения Windows

Открываем журнал Windows (команда eventvwr) и находим последнее событие с кодом 6006:

Фильтр системного журнала

Ищем событие 6006

Windows uptime (аптайм) как узнать?

К сожалению, в Операционной системе Windows uptime штатной команды нет как в Unix — системах. Но посмотреть сколько проработал компьютер, или когда он был включен, возможность есть. Опишу несколько способов как узнать в Windows uptime:

1. Через команду systeminfo (самый удобный на мой взгляд способ):
Чтобы ее выполнить, нужно запустить командную строку (для Windows XP: Пуск -> Выполнить -> cmd , для Windows 7: Пуск -> в строке поиска пишем cmd и кликаем на найденный вариант , через горячие клавиши для всех Windows: Win + R cmd ).

windows uptime

windows uptime

windows uptime

Запуск командной строки через горячие клавиши

В командной строке запускаем команду systeminfo и где-то среди первых строк результата ищем что-то типа «Время загрузки системы:» («System Boot Time:» ) в Windows 7 , или «Время работы системы:» в Windows XP . В Windows 7 эта команда показывает дату и время когда система загрузилась, а в Windows XP промежуток времени прошедший с момента загрузки.

windows uptime

Пример ответа команды systeminfo

2. Команда net statistics workstation , или net statistics server , или net stats srv , в первой строке показывает с каких пор снимается статистика;

3. В Windows 7 , в диспетчере задач ( Ctrl + Shift + Esc ), на вкладке «Быстродействие» («Performance» ) ближе к низу есть строка «Время работы» («Up Time») :

windows uptime

windows uptime через «диспетчер задач» в Windows 7

Как на все эти данные влияют режимы (спящий и ждущий режим компьютера) не проверено.

Такими простыми действиями мы можем проверить узнать uptime в Windows Xp и Windows 7.

Определить дату запуска ОС Windows, используя утилиту SystemInfo

Для определения времени запуска ОС (без необходимости высчитывать от текущего времени времени работы), можно использовать утилиту SystemInfo для этого необходимо запустить командную строку Windows (cmd.exe) и в открывшейстя консоли запустить выполнить команду SystemInfo.

В 11 строке сверху будет отображает время старта ОС.

  • Event ID: 12 Source: Kernel-General The operating system started at system time ‎
  • Event ID: 13 Source: Kernel-General The operating system is shutting down at system time

Проверка времени работы компьютера с помощью Powershell

Проверка времени работы компьютера с помощью Powershell

Статистика длительности работы компьютера может пригодиться для проверки работы серверов или в случае мониторинга пользователей на предмет нарушения техники безопасности (пожарной и информационной) и для многих других случаев. Такую статистику можно увидеть несколькими путями:

  1. С помощью диспетчера задач (Task Manager).
  2. С помощью Systeminfo.
  3. В логах. Например по событию 6005, которое показывает время включения хоста.
  4. С помощью класса WMI Win32_OperatingSystem, по свойству LastBootUpTime.

Lastboottime windows

Каждый из этих способов по своему удобен, но три из них теряют актуальность, если нужно проверить эти данные на множестве компьютеров. В случае с WMI такие данные можно получить с любого хоста. Я не исключаю, что такие данные можно получить с команд типа Get-NetAdapter или Get-ComputerInfo.

Следующим образом мы получим дату включения хоста используя команду CMD WMIC:

Аналогичный результат, но используя команду получения WMI в Powershell:

Get-WMIObject Powershell

Мы можем различить дату, но желательно иметь сразу более человеческое представление. Можно преобразовать результат и с WMI, но в случае с CIM он сразу корректный:

В зависимости от региональной версии ОС формат может быть разный:

Powershell LastBootTime

Наша задача посмотреть сколько времени работает компьютер, а не когда он был запущен. Для этого получим разницу во времени:

Powershell Get-DAte lastboottime

Попробуем выполнить команду на удаленном компьютере с Powershell, такой способ требует дополнительной настройки. Я обернул наш скрипт в функцию Get-UpTime, что бы было удобнее ее вызывать:

Powershell удаленная функция

Я выполняю две удаленные команды на одном и том же компьютере, так как он у меня один, но для наглядности продемонстрировано что можно иметь множество хостов. Я так же отсортировал результат с помощью Sort-Object сначала по дням, затем по часам. Нам не обязательно использовать метод Invoke-Command, так как сам командлет CIM имеет такую возможность, но первый способ мне нравится больше:

В каждом варианте я использовал параметр со значением -ErrorAction SilentlyContinue , который пропускает некоторые ошибки в Powershell. Это делается на случай, если какой-то хост окажется выключенным.

Теперь попробуем использовать нашу функцию Get-Uptime для получения данных со всех компьютеров в ActiveDirectory и экспортируем результат в CSV:

Powershell время работы компьютера

Далее этот файл можно открыть в Excel и просмотреть результат. Я так же убрал сортировку, так как это можно сделать через Excel. Выполнение подобной процедуры будет долгим, если в ActiveDirectory много компьютеров и его можно сузить с помощью ключей Filter и SearchBase в команде Powershell Get-ADUser.

Шестой способ узнавать uptime windows

Ну собственно можно воспользоваться WMI и PowerShell. Выяснить время старта ОС можно вот так:

$wmi = Get-WmiObject Win32_OperatingSystem
$wmi.LastBootUpTime

Время выводится в несколько неудобном формате, поэтому сконвертируем его:

И выведем время работы с точностью до миллисекунды, вычтя из текущей даты дату последней загрузки:

Как определить UP time (время работы системы) без выключения на примере windows server 2008 R2

Как определить UP time (время работы системы) без выключения на примере windows server 2008 R2

Надеюсь вы как и я что то для себя повторили, а кто то и просто узнал. Все спасибо, что были тут, будут вопросы жду в комментариях. Материал сайта Pyatilistnik.org

Посмотреть время работы компьютера после перезагрузки

Обновлено Обновлено: 08.02.2018
Опубликовано Опубликовано: 17.08.2016

Иногда хочется (или необходимо) увидеть, сколько компьютер работал времени без перезагрузки. В данной инструкции приведены примеры команд для Windows и Linux.

Для определения возраста компьютера или ноутбука, не стоит полагаться на 100% на данную информацию — система может быть переустановлена, а вместе с этим, сбивается общее время работы системы.

Открываем командную строку.

Для этого нажимаем комбинацию клавиш Win + R и в появившемся окне вводим cmd:

Ввод команды cmd для запуска командной строки

И нажимаем OK. Откроется командная строка.

1. Команда net stats

Введем команду net stats srv

> net stats srv

Среди результатов увидим Статистика после …

Время работы Windows при выводе статистики

Это и будет, так называемый, uptime windows или время работы с момента последнего запуска.

2. Команда systeminfo

Для более детальной информации также можно ввести следующую команду:

> systeminfo

Она покажет детальную информацию, в том числе общее (суммарное) время работы компьютера:

Время загрузки системы после ввода systeminfo

* где дата установки — дата и время, когда система была запущена в первые; время загрузки системы — дата и время, когда система была перезагружена последний раз.

Время выключения Windows

Открываем журнал Windows (команда eventvwr) и находим последнее событие с кодом 6006:

Фильтр системного журнала

Ищем событие 6006

Linux

Любая из приведенных ниже команд позволит посмотреть общее время работы Linux:

1. Uptime

uptime

Пример ответа:

13:28:16 up 27 days,  2:46,  1 user,  load average: 0.00, 0.02, 0.05

* где 13:28:16 — текущее время; up 27 days — дней с последней перезагрузки.

2. w

w

* по сути, ответ тот же, что и после ввода команды uptime, с подробными сведениями подключения пользователей.

3. Top

Команда top предназначена для отображения состояния загруженности Linux, но она также показывает, сколько компьютер работал после перезагрузки:

top

Ответ:

top — 13:35:15 up 27 days,  2:53,  1 user,  load average: 0.03, 0.03, 0.05
Tasks: 116 total,   1 running, 115 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni, 99.8 id,  0.0 wa,  0.0 hi,  0.0 si,  0.2 st
KiB Mem :  1016040 total,    77052 free,   591528 used,   347460 buff/cache
KiB Swap:   524284 total,   231264 free,   293020 used.   237288 avail Mem

* в данном случае, нас интересует верхняя строчка, которая нам напоминает вывод, все той же, uptime.

Дмитрий Моск — частный мастер

Была ли полезна вам эта инструкция?

Да            Нет

Понравилась статья? Поделить с друзьями:
  • Как посмотреть время проведенное в приложениях на пк windows 10
  • Как посмотреть время отключения компьютера windows 10
  • Как посмотреть время использования приложений на пк windows 10
  • Как посмотреть время использования компьютера windows 10
  • Как посмотреть время запуска windows 10