需求:本地时间为域时间。想要获取其他windows计算机的时间与网域时间相比较并存入数据库。
编辑文件C:\IPList.txt
172.22.22.21:CNServer01
172.22.22.22:CNServer02
PowerShell脚本
$IPList = Get-Content "C:\IPList.txt"
$sqlServer = "DBSERVER"
$database = "TEST"
$UserName= 'test'
$Password= 'test'
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$cnnString = "Server=$sqlServer;Database=$database;User ID=$UserName;Password=$Password;Trusted_Connection=False"
$sqlConnection.ConnectionString = $cnnString
$sqlCmd =New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.Connection = $sqlConnection
$sqlCmd.Connection.Open()
foreach ($Server in $IPList)
{
try{
$IP=($Server -Split ":")[0]
$Name=($Server -Split ":")[1]
$info=GWmi win32_localtime -computername $IP
$DateTime=Get-Date
$dt= New-Object DateTime $info.year,$info.month,$info.day,$info.hour,$info.minute,$info.second
$diff=(New-TimeSpan $DateTime -end $dt).TotalSeconds
$time1=$DateTime.ToString("yyyy-MM-dd HH:mm:ss")
$time2= $dt.ToString("yyyy-MM-dd HH:mm:ss")
$sqlCmd.CommandText = "INSERT INTO [dbo].[Time] (ServerName ,ServerTime ,DomainTime ,Diff) VALUES ('$Name','$time1','$time2','$diff')"
$sqlCmd.ExecuteNonQuery()
}
catch [exception]
{
$ErrMsg=$_.Exception.Message
print $ErrMsg
continue
}
}