Is there a way to find LastBootUpTime with Powershell and insert results to a SQL table with data type of smalldatetime? I have attempted the following but receive error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Conversion failed when converting character string to smalldatetime data type."At C:\ServerUptime\ServerUptimePowershellScript.ps1:46 char:22
+ $cmd.ExecuteNonQuery <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Here is the code I have been trying. I am new to Powershell and don't really know if I am doing FOREACH correctly. The SELECT ServerName is returning a number of servernames.
# First, clear existing table $ClearTbl = Invoke-Sqlcmd -Database DatabaseName -Query 'DELETE FROM [DatabaseName].[dbo].[ServerUptime]' -ServerInstance ServerName # Output to SQL Server table ##Connect to the SQL server and the Database $conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=ServerName; Initial Catalog=TableName; Integrated Security=SSPI") ## Open DB Connection $conn.Open() # Get server names for net stats srv to loop through $DataSet = Invoke-Sqlcmd -Database DatabaseName -Query "SELECT ServerName FROM [DatabaseName].[dbo].[TableName]" -ServerInstance ServerName foreach ($element in $DataSet) { $element $Server = $element.ServerName # Get server uptime and convert to SQL datetime format (2013-04-08 00:00:00.000). $wmidate=(Get-WmiObject -Class Win32_OperatingSystem).LastbootUpTime
$shortdt=[System.Management.ManagementDateTimeConverter]::ToDateTime($wmidate).ToShortDateString()foreach ($lastbootuptime in $wmidate) { $lastbootuptime $uptime = $lastbootuptime #Create SQL Insert Statement with your values $insert_stmt = "INSERT INTO ServerUptime(ServerName,Uptime) VALUES('$Server','$uptime')" } } ## Create your command $cmd = $conn.CreateCommand() $cmd.CommandText = $insert_stmt ## Invoke the Insert statement $cmd.ExecuteNonQuery() ## Close DB Connection $conn.Close()
Appreciate any help. Thanks!