Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Powershell Connection to Database: Issues Writing Data back to Database

$
0
0

Afternoon;


I'm updating a script file we have that we use in a remote assistance application and I am able to get into a database to read the information that I need but now I need to write back to the data base in two portions of this script.


Portion 1: User Update of Database Record

Pull all data for a selected Item from the dropdown  and display to user in an edit form so the user can modify the current record and write back up to the database on 'Accept'.


Portion 2: User Creation of Database Record

Display a form for the user to fill out and upon 'Accept' check PrimaryKey Variable 'SID' to ensure if it is not already taken. If not taken, continue to write new record to database with information provided by the user.



This scrip file has been in use for a while, and they don't want to move from it, they just want to add to it.  I already have added one of the three functions requested, and was working on this next one but hit a dead end since I cannot figure out how to get this to write back to the database. Also, this is currently connecting to a test database so I don't muck up the current one.


Here is what I'm using to connect and read from the database...

#Two script segments

#SEG1
$DBcon = "Server=DASHIPMAN\SQLEXPRESS;Database=MISINVENTORY;Trusted_Connection=True"
$DBqry = "select * from PCDATA order by USERNAME"


#SEG2
function Get-DatabaseData # Used to collect data from linked database
    {
    param
        (
        [string]$connectionString,
        [string]$query,
        [switch]$isSQLServer
        )
    $connection = New-Object System.Data.SqlClient.SqlConnection
    $connection.ConnectionString = $connectionString
    $command = $connection.CreateCommand()
    $command.CommandText = $query
    $adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset)
    $dataset.Tables[0]
    }

And I know there is a good bit more I can do to neaten this up, but here is the full script if there are questions about what is calling what to do what...

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  

############################################## Start form constructions

# Main Form
$FormMain = New-Object System.Windows.Forms.Form
$FormMain.Text = "MIS Inventory Manager"
$FormMain.Font = New-Object System.Drawing.Font("Times New Roman",10,[System.Drawing.FontStyle]::Regular)
$FormMain.Size = New-Object System.Drawing.Size(600,420)
$FormMain.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;

# Sub Form Data Record Add
$FormDBA = New-Object System.Windows.Forms.Form
$FormDBA.Text = "MIS Inventory Manager"
$FormDBA.Font = New-Object System.Drawing.Font("Times New Roman",10,[System.Drawing.FontStyle]::Regular)
$FormDBA.Size = New-Object System.Drawing.Size(300,500)
$FormDBA.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;

# Sub Form Data Record Modify


############################################## End form constructions

############################################## Start process variables

$INDX=" - "
$DBcon = "Server=DASHIPMAN\SQLEXPRESS;Database=MISINVENTORY;Trusted_Connection=True"
$DBqry = "select * from PCDATA order by USERNAME"

############################################## End process variables

############################################## Start functions

function VNCcom # Used to VNC control a selected PC (ignores null option)
    {
    $computer = $DropDownBox.SelectedItem.ToString()
    If ($computer -ne $null)
        {
        $ILOC = $INDX.Length
        $DLOC = $computer.IndexOf($INDX)
        $PCNAME = $computer.Substring($DLOC+$ILOC)
        $outputBox.text = "Attempting VNC Connection with " + $PCNAME + "..."
        $cmd = '"C:\Program Files\RealVNC\VNC4\VNCViewer.exe" ' + $PCNAME
        cmd /c $cmd
        $outputBox.text = "VNC Connection with " + $PCNAME + " terminiated..."
        }
        Else
        {
        $outputBox.text = "No PC Value Chosen ::: Please select a PC value above..."
        }
    }

function RecordPull # Used to pull a selected PC's record (ignores null option)
    {
    $computer = $DropDownBox.SelectedItem.ToString()
    If ($computer -ne $null)
        {
        $ILOC = $INDX.Length
        $DLOC = $computer.IndexOf($INDX)
        $PCNAME = $computer.Substring($DLOC+$ILOC)
        $DBqryRP = "select * from PCDATA Where PCNAME = '" + $PCNAME + "' order by USERNAME"
        $RecordSet = $DBextract = Get-DatabaseData –query $DBqryRP –isSQLServer –connectionString $DBcon
        foreach ($ROW in $RecordSet)
            {
            $Record = "Sticker ID : " + $ROW.STICKERID + "`r`n" + "User Name : " + $ROW.USERNAME + "`r`n" + "PC Name : " + $ROW.PCNAME + "`r`n" + "Department : " + $ROW.DEPARTMENT + "`r`n" + "PC Type : " + $ROW.PCTYPE + "`r`n" + "Make : " + $ROW.MAKE + "`r`n" + "Model : " + $ROW.MODEL + "`r`n" + "Operating System : " + $ROW.OS + "`r`n" + "Disposed of : " + $ROW.DISPOSED
            }
        $outputBox.text = $Record
        }
        Else
        {
        $outputBox.text = "No PC Value Chosen ::: Please select a PC value above..."
        }
    }

function RecordEdit # Used to pull a selected PC's record (ignores null option)
    {
    $computer = $DropDownBox.SelectedItem.ToString()
    If ($computer -ne $null)
        {
        $ILOC = $INDX.Length
        $DLOC = $computer.IndexOf($INDX)
        $PCNAME = $computer.Substring($DLOC+$ILOC)
        $DBqryRP = "select * from PCDATA Where PCNAME = '" + $PCNAME + "' order by USERNAME"
        $RecordSet = $DBextract = Get-DatabaseData –query $DBqryRP –isSQLServer –connectionString $DBcon
        foreach ($ROW in $RecordSet)
            {
            $Record = "This button is meant for editing database records and as of yet is not active..."
            }
        $outputBox.text = $Record
        }
        Else
        {
        $outputBox.text = "No PC Value Chosen ::: Please select a PC value above..."
        }
    }

function RecordAdd # Used to pull a selected PC's record (ignores null option)
    {
    $outputBox.text = "Please fill out provided form..."
    $NULLFND = $False
    $FormDBA.Add_Shown({$FormDBA.Activate()})### DO NOT MODIFY
    If ('Ok' -eq $FormDBA.ShowDialog())
        {$FormDBA.Controls|%{$_.Text}}
    If ($InBoxSID.Text -ne "")
        {$VALSID = $InBoxSID.Text}
        Else
        {
        $VALSID = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxUSR.Text -ne "")
        {$VALUSR = $InBoxUSR.Text}
        Else
        {
        $VALUSR = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxPCN.Text -ne "")
        {$VALPCN = $InBoxPCN.Text}
        Else
        {
        $VALPCN = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxDPT.Text -ne "")
        {$VALDPT = $InBoxDPT.Text}
        Else
        {
        $VALDPT = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxPCT.Text -ne "") 
        {$VALPCT = $InBoxPCT.Text}
        Else
        {
        $VALPCT = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxMAK.Text -ne "")  
        {$VALMAK = $InBoxMAK.Text}
        Else
        {
        $VALMAK = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxMOD.Text -ne "")
        {$VALMOD = $InBoxMOD.Text}
        Else
        {
        $VALMOD = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxOPS.Text -ne "")
        {$VALOPS = $InBoxOPS.Text}
        Else
        {
        $VALOPS = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($InBoxDIS.Text -ne "")
        {$VALDIS = $InBoxDIS.Text}
        Else
        {
        $VALDIS = "VALUE IS NULL"
        $NULLFND = $True
        }
    If ($NULLFND -eq $False) # Checks for null submissions from user
        {
        $RECSTAT = "PASSED"
        $DBqryRP = "select * from PCDATA Where STICKERID = '" + $VALSID + "' order by STICKERID"
        $RecordSet = $DBextract = Get-DatabaseData –query $DBqryRP –isSQLServer –connectionString $DBcon
        foreach ($ROW in $RecordSet)
            {$DBPULL = $ROW.STICKERID}
        If ($VALSID -eq $DBPULL)
            {
            $DBCHK = "Sticker ID: " + $DBPULL + " is already in use..."
            $RECSTAT = "FAILED"
            }
            Else
            {
            $DBCHK = "Sticker ID: " + $VALSID + " was not in use..."
            $DBqryRA = "insert into PCDATA values  " + "(" + $VALSID + "','" + $VALPCN + "','" + $VALUSR + "','" + $VALDPT + "','" + $VALPCT + "','" + $VALMAK + "','" + $VALMOD + "','" + $VALOPS + "','" + $VALDIS + ")"
            $RecordSet = $DBextract = Add-DatabaseData –query $DBqryRA –isSQLServer –connectionString $DBcon
            }

        $RECSTAT = $RECSTAT + " " + $DBCHK
        }
        Else
        {
        $RECSTAT = "FAILED"
        }
    $outputBox.text = ":::Values Submitted:::" + "    Record add status : " + $RECSTAT + "`r`n" + "`r`n" + "Sitcker ID : " + $VALSID + "`r`n" + "User Name : " + $VALUSR + "`r`n" + "PC Name : " + $VALPCN + "`r`n" + "Department : " + $VALDPT + "`r`n" + "PC Type : " + $VALPCT + "`r`n" + "Make : " + $VALMAK + "`r`n" + "Model : " + $VALMOD + "`r`n" + "O.S. : " + $VALOPS + "`r`n" + "Disposed : " + $VALDIS
    }

function procInfo # Used to ping a selected PC (ignores null option)
    {
    $computer = $DropDownBox.SelectedItem.ToString()
    If ($computer -ne $null)
        {
        $ILOC =$INDX.Length
        $DLOC = $computer.IndexOf($INDX)
        $PCNAME = $computer.Substring($DLOC+$ILOC)
        $outputBox.text = "Please wait ::: Attempting ping on... " + $PCNAME
        $pingResult = ping $PCNAME | fl | out-string;
        $outputBox.text = $pingResult
        }
        Else
        {
        $outputBox.text = "No PC Value Chosen ::: Please select a PC value above..."
        }
    }

function Add-DatabaseData # Used to collect data from linked database
    {
    param
        (
        [string]$connectionString,
        [string]$query,
        [switch]$isSQLServer
        )
    $connection = New-Object System.Data.SqlClient.SqlConnection
    $connection.ConnectionString = $connectionString
    $command = $connection.CreateCommand()
    $command.CommandText = $query
    $adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    #$adapter.Fill($dataset)
    #$dataset.Tables[0]
    }

function Get-DatabaseData # Used to collect data from linked database
    {
    param
        (
        [string]$connectionString,
        [string]$query,
        [switch]$isSQLServer
        )
    $connection = New-Object System.Data.SqlClient.SqlConnection
    $connection.ConnectionString = $connectionString
    $command = $connection.CreateCommand()
    $command.CommandText = $query
    $adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset)
    $dataset.Tables[0]
    }

function DataCollection # Used to fill dropdown box for FormMain
    {
    $DropDownBox.Items.Clear()
    $DBextract = Get-DatabaseData –query $DBqry –isSQLServer –connectionString $DBcon
    $outputBox.text = "Please wait ::: Populating DropDown List..."
    foreach ($ROW in $DBextract)
        {
        $Record = $ROW.USERNAME + $INDX + $ROW.PCNAME
        If ($Record -ne ' - '){$DropDownBox.Items.Add($Record)}
        }
    $outputBox.text = "Dropdown List populated"
    }

############################################## End functions

############################################## Start drop down boxes

$DropDownBoxLabel = New-Object System.Windows.Forms.Label
$DropDownBoxLabel.Text = "Please choose a PC below..."
$DropDownBoxLabel.Location = New-Object System.Drawing.Size(20,50)
$DropDownBoxLabel.AutoSize = $True
$DropDownBox = New-Object System.Windows.Forms.ComboBox
$DropDownBox.Location = New-Object System.Drawing.Size(20,80) 
$DropDownBox.Size = New-Object System.Drawing.Size(180,20) 
$DropDownBox.DropDownHeight = 200 

############################################## End drop down boxes

############################################## Start input boxes

#Sub Form Data Record Add Input Boxes
$InBoxTxtSID = New-Object System.Windows.Forms.Label
$InBoxTxtSID.Location = New-Object System.Drawing.Size(25,15)
$InBoxTxtSID.Text = "Sticker ID : "
$InBoxSID = New-Object System.Windows.Forms.TextBox 
$InBoxSID.Location = New-Object System.Drawing.Size(130,10)
$InBoxSID.Size = New-Object System.Drawing.Size(120,20)
$InBoxSID.Text = ""
$InBoxTxtUSR = New-Object System.Windows.Forms.Label
$InBoxTxtUSR.Location = New-Object System.Drawing.Size(25,55)
$InBoxTxtUSR.Text = "User Name ; "
$InBoxUSR = New-Object System.Windows.Forms.TextBox 
$InBoxUSR.Location = New-Object System.Drawing.Size(130,50)
$InBoxUSR.Size = New-Object System.Drawing.Size(120,20)
$InBoxUSR.Text = ""
$InBoxTxtPCN = New-Object System.Windows.Forms.Label
$InBoxTxtPCN.Location = New-Object System.Drawing.Size(25,95)
$InBoxTxtPCN.Text = "PC Name : "
$InBoxPCN = New-Object System.Windows.Forms.TextBox 
$InBoxPCN.Location = New-Object System.Drawing.Size(130,90)
$InBoxPCN.Size = New-Object System.Drawing.Size(120,20)
$InBoxPCN.Text = ""
$InBoxTxtDPT = New-Object System.Windows.Forms.Label
$InBoxTxtDPT.Location = New-Object System.Drawing.Size(25,135)
$InBoxTxtDPT.Text = "Department : "
$InBoxDPT = New-Object System.Windows.Forms.TextBox 
$InBoxDPT.Location = New-Object System.Drawing.Size(130,130)
$InBoxDPT.Size = New-Object System.Drawing.Size(120,20)
$InBoxDPT.Text = ""
$InBoxTxtPCT = New-Object System.Windows.Forms.Label
$InBoxTxtPCT.Location = New-Object System.Drawing.Size(25,175)
$InBoxTxtPCT.Text = "PC Type : "
$InBoxPCT = New-Object System.Windows.Forms.TextBox 
$InBoxPCT.Location = New-Object System.Drawing.Size(130,170)
$InBoxPCT.Size = New-Object System.Drawing.Size(120,20)
$InBoxPCT.Text = ""
$InBoxTxtMAK = New-Object System.Windows.Forms.Label
$InBoxTxtMAK.Location = New-Object System.Drawing.Size(25,215)
$InBoxTxtMAK.Text = "Make : "
$InBoxMAK = New-Object System.Windows.Forms.TextBox 
$InBoxMAK.Location = New-Object System.Drawing.Size(130,210)
$InBoxMAK.Size = New-Object System.Drawing.Size(120,20)
$InBoxMAK.Text = ""
$InBoxTxtMOD = New-Object System.Windows.Forms.Label
$InBoxTxtMOD.Location = New-Object System.Drawing.Size(25,255)
$InBoxTxtMOD.Text = "Model : "
$InBoxMOD = New-Object System.Windows.Forms.TextBox 
$InBoxMOD.Location = New-Object System.Drawing.Size(130,250)
$InBoxMOD.Size = New-Object System.Drawing.Size(120,20)
$InBoxMOD.Text = ""
$InBoxTxtOPS = New-Object System.Windows.Forms.Label
$InBoxTxtOPS.Location = New-Object System.Drawing.Size(25,295)
$InBoxTxtOPS.Text = "O.S. : "
$InBoxOPS = New-Object System.Windows.Forms.TextBox 
$InBoxOPS.Location = New-Object System.Drawing.Size(130,290)
$InBoxOPS.Size = New-Object System.Drawing.Size(120,20)
$InBoxOPS.Text = ""
$InBoxTxtDIS = New-Object System.Windows.Forms.Label
$InBoxTxtDIS.Location = New-Object System.Drawing.Size(25,335)
$InBoxTxtDIS.Text = "Disposed : "
$InBoxDIS = New-Object System.Windows.Forms.TextBox 
$InBoxDIS.Location = New-Object System.Drawing.Size(130,330)
$InBoxDIS.Size = New-Object System.Drawing.Size(120,20)
$InBoxDIS.Text = ""

############################################## End input boxes

############################################## Start output boxes

#Main form
$outputBox = New-Object System.Windows.Forms.TextBox 
$outputBox.Location = New-Object System.Drawing.Size(10,170) 
$outputBox.Size = New-Object System.Drawing.Size(560,200) 
$outputBox.MultiLine = $True 
$outputBox.ScrollBars = "Vertical" 

############################################## End output boxes

############################################## Start buttons

#Main Form Buttons
#VNC Connect Button
$ButtonVNC = New-Object System.Windows.Forms.Button 
$ButtonVNC.Location = New-Object System.Drawing.Size(270,110) 
$ButtonVNC.Size = New-Object System.Drawing.Size(120,40) 
$ButtonVNC.Text = "VNC Connect" 
$ButtonVNC.Add_Click({VNCcom}) 
#Ping Button
$ButtonPNG = New-Object System.Windows.Forms.Button 
$ButtonPNG.Location = New-Object System.Drawing.Size(270,60) 
$ButtonPNG.Size = New-Object System.Drawing.Size(120,40) 
$ButtonPNG.Text = "Ping Test" 
$ButtonPNG.Add_Click({procInfo}) 
#Display Record Button
$ButtonDBP = New-Object System.Windows.Forms.Button 
$ButtonDBP.Location = New-Object System.Drawing.Size(400,10) 
$ButtonDBP.Size = New-Object System.Drawing.Size(120,40) 
$ButtonDBP.Text = "View Record" 
$ButtonDBP.Add_Click({RecordPull})
#Edit Record Button
$ButtonDBE = New-Object System.Windows.Forms.Button 
$ButtonDBE.Location = New-Object System.Drawing.Size(400,60) 
$ButtonDBE.Size = New-Object System.Drawing.Size(120,40) 
$ButtonDBE.Text = "Edit Record" 
$ButtonDBE.Add_Click({RecordEdit}) 
#Add Record Button
$ButtonDBA = New-Object System.Windows.Forms.Button 
$ButtonDBA.Location = New-Object System.Drawing.Size(400,110) 
$ButtonDBA.Size = New-Object System.Drawing.Size(120,40) 
$ButtonDBA.Text = "Add Record" 
$ButtonDBA.Add_Click({RecordAdd}) 
#Update Dropdown Button
$ButtonDPD = New-Object System.Windows.Forms.Button 
$ButtonDPD.Location = New-Object System.Drawing.Size(270,10) 
$ButtonDPD.Size = New-Object System.Drawing.Size(120,40) 
$ButtonDPD.Text = "Update Dropdown" 
$ButtonDPD.Add_Click({DataCollection}) 

#Sub Form Data Record Add Buttons
#Data Add Submit Button
$ButtonDASUB = New-Object System.Windows.Forms.Button
$ButtonDASUB.Location = New-Object System.Drawing.Size(150,400)
$ButtonDASUB.Width = 100
$ButtonDASUB.Text = “Submit Record”
$ButtonDASUB.DialogResult='Ok'
$ButtonDASUB.Add_Click({$FormDBA.Close()})

############################################## End buttons

############################################## Start initial message

$outputBox.text = "Please populate Dropdown List before continuing..."
DataCollection

############################################## End initial message

############################################## Start form controls

# Main Form controls
$FormMain.Controls.Add($DropDownBoxLabel) 
$FormMain.Controls.Add($DropDownBox)
$FormMain.Controls.Add($outputBox)
$FormMain.Controls.Add($ButtonVNC) 
$FormMain.Controls.Add($ButtonPNG) 
$FormMain.Controls.Add($ButtonDBP)
$FormMain.Controls.Add($ButtonDBE)
$FormMain.Controls.Add($ButtonDBA)
$FormMain.Controls.Add($ButtonDPD)

# Sub Form Data Record Add controls
$FormDBA.Controls.Add($ButtonDASUB)
$FormDBA.Controls.Add($InBoxTxtSID)
$FormDBA.Controls.Add($InBoxTxtUSR)
$FormDBA.Controls.Add($InBoxTxtPCN)
$FormDBA.Controls.Add($InBoxTxtDPT)
$FormDBA.Controls.Add($InBoxTxtPCT)
$FormDBA.Controls.Add($InBoxTxtMAK)
$FormDBA.Controls.Add($InBoxTxtMOD)
$FormDBA.Controls.Add($InBoxTxtOPS)
$FormDBA.Controls.Add($InBoxTxtDIS)
$FormDBA.Controls.Add($InBoxSID)
$FormDBA.Controls.Add($InBoxUSR)
$FormDBA.Controls.Add($InBoxPCN)
$FormDBA.Controls.Add($InBoxDPT)
$FormDBA.Controls.Add($InBoxPCT)
$FormDBA.Controls.Add($InBoxMAK)
$FormDBA.Controls.Add($InBoxMOD)
$FormDBA.Controls.Add($InBoxOPS)
$FormDBA.Controls.Add($InBoxDIS)

# Sub Form Data Record Modify controls


############################################## End form controls

##############################################
##############################################
$FormMain.Add_Shown({$FormMain.Activate()})### DO NOT MODIFY
$FormMain.ShowDialog()########################
##############################################
############################################## 




Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>