Home Forums Programming Powershell Write PowerShell Output to SQL Server Table RE: Write PowerShell Output to SQL Server Table

  • Hi,

    Not knowing Powershell very well and indeed sql it's taken me some time to tinker with and adapt your script . I need help expanding on it. It works for retrieving more than 1 value from the same class and inserts the values. What I need to do is to be able to retrieve values from other classes and insert the result in to the appropriate column. Any help / advice would be so appreciated.

    $servernames = Get-WmiObject -computername Anycompname -class win32_ComputerSystem | Select Name, Manufacturer

    # Open Connection

    $conn = New-Object System.Data.SqlClient.SqlConnection

    $connectionString = "Server=;Database=;user=;pwd=;"

    $conn.ConnectionString = $connectionString

    $conn.Open()

    # Create the Command object to execute the queries

    $cmd = New-Object System.Data.SqlClient.SqlCommand

    $cmd.Connection = $conn

    $cmd.CommandType = [System.Data.CommandType]::Text

    # Write Data

    foreach ($servername in $servernames)

    {

    # Compose Query for this $servername - watch the single quotes for string values!!

    $query = "INSERT INTO dbo.U_Server (ServerName, OSVersion) VALUES ('" + $servername.Name + "', '" + $servername.Manufacturer + "')"

    # Uncomment next line to display query for checking

    $query

    # Setup Command

    $cmd.CommandText = $query

    # Execute Command to insert data for this $drive

    $result = $cmd.ExecuteNonQuery()

    }

    # Tidy Up

    $conn.Close()