Need some help PowerShell insert to SQL RRS feed

  • Question

  • I am new to powershell and have been working on my first PowerShell project. My objective is to get data into a SQL database directly. I chose to use getting PowerShell versions to import. Any input would be greatly appreciated. Below is my script i have so far. I have already created the table with corresponding field names.

    $HostName = (Get-WmiObject Win32_ComputerSystem).Name
    $Domain = (Get-WmiObject Win32_ComputerSystem).Domain
    $IPAddress = (Get-WmiObject Win32_NetworkAdapterConfiguration | Where { $_.IPAddress } | Select -Expand IPAddress).split('.')[0..3] -join '.'
    $PSVersionMajor = $PSVersionTable.psversion.Major
    $PSVersionMinor = $PSVersionTable.psversion.Minor
    $PSVersionBuild = $PSVersionTable.psversion.Build
    $PSVersionRevision = $PSVersionTable.psversion.Revision

    $conn = New-Object System.Data.SqlClient.SqlConnection
    $conn.ConnectionString = "Server='sqlserver;Database='database;User Id='username'; Password='password';"
    $cmd = New-Object System.Data.SqlClient.SqlCommand
    $cmd.connection = $conn

    ## Check Connection to DataBase OPEN.

    if ($sqlConnection.State -eq [Data.ConnectionState]::Open){
    "Connection to DataBase is open."

    ### Check Connection to Database CLOSED.

    if ($sqlConnection.State -ne [Data.ConnectionState]::Open){
    "Connection to DataBase is not open."

    $cmd.commandtext = "INSERT INTO 'database table' (HostName,Domain,IPAddress,PSVersionMajor,PSVersionMinor,PSVersionBuild,PSVersionRevision) VALUES('{$HostName}','{$Domain}','{$IPAddress}','{$PSVersionMajor}','{$PSVersionMinor}','{$PSVersionBuild}','{$PSVersionRevision}')"

    Wednesday, September 20, 2017 2:22 AM

All replies