Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

PowerShell Custom Object Data into SQL Server Table

$
0
0

Trying to populate a SQL table with contents from a custom object. The custom object will write to an out-file if it is just a text file. However, I want to take the results in the custom object and write them into a SQL table. Here is what I have so far. I get the server name and the time into the table because they are not in the custom object loop. I need to get the DefragRecommended from within the custom object loop and place it into the table along with the server and time.


$datetime = Get-Date
$Time = $datetime

#Defrag Status

$servers = Get-Content "C:\Documents and Settings\user\Desktop\Defrag\servers.txt"
foreach ($server in $servers){
  $defrag = @{
   ServerName = $server
   DefragRecommended = $null
   }
 $vol = Get-WmiObject Win32_Volume -Filter "DriveLetter = 'C:'" -ComputerName $server -ea 0
 if($vol){
  $result = $vol.DefragAnalysis()
  $defrag.DefragRecommended = $result.DefragRecommended
   }

  New-Object PsObject -Property $defrag
  
#Database Update 

"INSERT INTO Defrags" | out-file "C:\Documents and Settings\user\Desktop\Defrag\insert.sql"
"Values ('$Server','$DefragRecommended','$Time')" | out-file "C:\Documents and Settings\user\Desktop\Defrag\insert.sql" -append
                
sqlcmd -S server name -d table name -i "C:\Documents and Settings\user\Desktop\Defrag\insert.sql"
               
cls remove-item "C:\Documents and Settings\user\Desktop\Defrag\insert.sql"

}


Viewing all articles
Browse latest Browse all 10624

Trending Articles