首页 > 解决方案 > 如何仅在 Powershell 上获取服务器的正常运行时间?

问题描述

我有以下代码,当我直接在 powershell 中使用时它可以工作:

Get-WmiObject win32_operatingsystem | select @{LABEL=’LastBootUpTime’;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)

它返回:

LastBootUpTime
--------------
14/09/2019 10:41:50

.ps1但是,当我在带有 invoke-command 的Powershell 脚本中使用该命令时,输出会返回更多信息:

LastBootUpTime        PSComputerName RunspaceId                          
--------------        -------------- ----------                          
9/14/2019 10:41:50 AM 192.168.0.20   af08d2d8-c4f1-4f85-9d6c-e3f4ffe475c6

为什么会这样?

如果可能的话,我也希望没有标题 LastBootUpTime 。

标签: windowspowershell

解决方案


Invoke-Command 将始终返回附加信息,在这种情况下,命令运行的位置和运行空间 id。您始终可以将结果放入变量中,然后简单地打印出您想要的属性。例如

$result = invoke-command {your-command}
$result.LastBootUpTime

或简称

(invoke-command {your-command}).LastBootupTime

注意,当你使用 wmi 时,你不一定需要使用 invoke-command,你也可以直接将 -computer 参数传递给它以对远程计算机运行命令:

Get-WmiObject win32_operatingsystem -computer "remote_computer_name"

推荐阅读