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

  • Gary Varga (6/17/2013)


    The simplest way is to build up a string to execute:

    $commandText = "INSERT DiskSpace VALUES ('" + $wmiObject.GetValue(0)["SystemName"] + "')"

    $command = $conn.CreateCommand()

    $command.CommandText = $commandText

    $command.ExecuteNonQuery()

    This way is not necessarily ideal as it is a little bit verbose, however, I would recommend building up the text as a separate string because you can always output it to the console before using it in anger:

    Write-Output $commandText

    Just say if you need more or if this is not what you were looking for.

    Thanks, Gary.

    So would I build the insert for the first two columns like this?

    $commandText = "INSERT DiskSpace (SystemName,DeviceID) VALUES ('" + $wmiObject.GetValue(0)["SystemName"] + "," + $wmiObject.GetValue(0)["DeviceID"]+ "')"

    Also, there seems to be a bit of hidden magic there. Will 1 insert do it or am I going to have to iterate over each row from the $wmiObject with incrementing values for the operand of .GetValue?

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)