Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1424712
  • 博文数量: 269
  • 博客积分: 3602
  • 博客等级: 中校
  • 技术积分: 4536
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-17 21:13
文章分类

全部博文(269)

文章存档

2014年(8)

2013年(139)

2012年(122)

分类: 系统运维

2013-12-16 10:20:05

最近,我需要找到远程网络上的多个Windows服务器时间比较这些我写了一个快捷功能使用WMI来这个信息并返回它在一个DateTime对象格式

image

The Code

function Get-Time {
	<#
		.SYNOPSIS
			Gets the time of a windows server

		.DESCRIPTION
			Uses WMI to get the time of a remote server

		.PARAMETER  ServerName
			The Server to get the date and time from

		.EXAMPLE
			PS C:\> Get-Time localhost

		.EXAMPLE
			PS C:\> Get-Time server01.domain.local -Credential (Get-Credential)

	#>
	[CmdletBinding()]
	param(
		[Parameter(Position=0, Mandatory=$true)]
		[ValidateNotNullOrEmpty()]
		[System.String]
		$ServerName,

		$Credential

	)
	try {
			If ($Credential) {
				$DT = Get-WmiObject -Class Win32_LocalTime -ComputerName $servername -Credential $Credential
			} Else {
				$DT = Get-WmiObject -Class Win32_LocalTime -ComputerName $servername
			}
	}
	catch {
		throw
	}

	$Times = New-Object PSObject -Property @{
		ServerName = $DT.__Server
		DateTime = (Get-Date -Day $DT.Day -Month $DT.Month -Year $DT.Year -Minute $DT.Minute -Hour $DT.Hour -Second $DT.Second)
	}
	$Times

}

#Example of using this function
$Servers = "localhost", "dc01.domain.local"

$Servers | Foreach {
	Get-Time $_
}

Checking for time skew

We can also use this function to easily check for time skew between two machines, the below code is an example where I check my time between a remote host and the local server to see if it is within 30 seconds…

$RemoteServerTime = Get-Time -ServerName "dc01.domain.local"
$LocalServerTime = Get-Time -ServerName "localhost"

$Skew = $LocalServerTime.DateTime - $RemoteServerTime.DateTime

# Check if the time is over 30 seconds
If (($Skew.TotalSeconds -gt 30) -or ($Skew.TotalSeconds -lt -30)){
	Write-Host "Time is not within 30 seconds"
} Else {
	Write-Host "Time checked ok"
}
阅读(2083) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~