Get, Set Time with Powershell

Had some challenges with time on some virtual environments that got reverted to snapshot each day and redeployed. Domain Controller was not connected to the Internet and host time synchronization caused some issues here. Basically we created a script which polled a public NTP pool and changed DC time accordingly, using remote powershell from server connected to DC and the Internet.

#--Find the FQDN of the DC.
$DC=([system.net.dns]::GetHostByAddress(([System.Net.Dns]::GetHostAddresses($(gwmi WIN32_ComputerSystem).Domain)[0].IPAddressToString))).hostname
#-- Creates Session to the DC.
$Session= New-PSSession -computername $DC -authentication Kerberos

#-- Collects time from dk ntp pool.
$Time = w32tm /stripchart /dataonly /computer:dk.pool.ntp.org /samples:1
#-- Gets local time of server
$LocalTime = Get-Date

#-- Synchronizes Local time with NTP pool time, using difference in time.
$SetTime= ($LocalTime.AddSeconds($Time[3].split("")[1].trim("+s")))

#-- Creates scriptblock to be run on DC
$SB= {param($SetTime)Set-Date $SetTime}

#-- Sets time according to dk.ntp.pool.org on Domain Controller
Invoke-Command $Session -ArgumentList $SetTime -Scriptblock $SB

#-- Removes Session to DC
Remove-PSSession $Session
Advertisements

One comment

  1. Hey,
    I know this is an old entry, so maybe I won’t get any response, but I’m gonna try anyway šŸ™‚
    I’m a PS newbie pretty much (I know you like me already :)), and I’d like to use PS for checking the time on a local machine, then set it on a remote one. Sounds like a simple scenario, so maybe you’d like to enlighten me on the proper code šŸ™‚
    Thanks so much!
    Maciek

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s