Hello friends,
I am a very new bee to Power Shell. I would like to put output of powershell output to a SQL table. Here is the code. I know some scripting guy put two functions Out-DataTable and Write-DataTable. But I don't want to use them ... Can any one point me where am I doing mistake? I am getting data in the table emptry for charcters and 0 (zero) for Integers.
Thanks in advance.
#=============================================================================
# get server names from SQL table to loop through
$DataSet = Invoke-Sqlcmd -Database DBA -Query "SELECT ServerName FROM [DBA].[dbo].[ServerList]" -ServerInstance"DBA_Test"
# get disk stats
foreach ($element in $DataSet)
{
$element
$Server = $element.ServerName
#the exclude property (-ExcludeProperty "_*") in conjunction with Property is not needed IMHO.
$Output = Get-WmiObject -Class Win32_Volume -Computer $Server | Select-Object SystemName, Capacity, DriveType, DriveLetter, FreeSpace
<# The output may or may not be an array (there may be zero, one or more volumes),
so the $output | foreach {} is the best choice.
If there are no items it won't run the foreach body -> zero inserts.
#>
# Output to SQL Server table
##Connect to the SQL server and the Database
#replace one or more white space (including NewLine) with one space
#purely formatting thing.
# Output to SQL Server table
##Connect to the SQL server and the Database
$connectionString = "Data Source=DBA_Test; Initial Catalog=DBA; Integrated Security=SSPI" -replace "\s+"," "
$conn = New-Object System.Data.SqlClient.SqlConnection($connectionString)
Try
{
#using the try finally you do as much as you can to make sure
#you won't leak connections.
## Open DB Connection
$conn.Open()
## Create your command
$cmd = $conn.CreateCommand()
#Create SQL Insert Statement with your values
$insert_stmt = "INSERT INTO Disk(ComputerName,Size,DiskType,DriveLetter,FreeSpace)
VALUES ('$($_.systemName)','$($_.Capacity)','$($_.DriveType)','$($_.DriveLetter)','$($_.FreeSpace)')" -replace "\s+"," "
$cmd.CommandText = $insert_stmt
## Invoke the Insert statement
$cmd.ExecuteNonQuery()
}
finally
{
## Close DB Connection
#http://msdn.microsoft.com/cs-cz/library/system.data.connectionstate.aspx
#if $conn is $null then this fails (can't call method on null object), so check the object first.
if ($conn -and ($conn.state -eq 'Open'))
{
$conn.Close()
}
}
}
# end disk stats
#=============================================================================