Data from Powershell forms with blank fields into SQL Server database - sql

So far I have created a form in Powershell studio and from that form I want to take the user's input and place it into a SQL Server database.
For the most part this works fine, unless a textfield in the form is left blank, then an error occurs. I need to be able to insert the data even if some of the fields are not complete as people are able to go back and edit and add to that data and then update it in the database.
This is the error I get if I leave a textbox blank:
ERROR: Exception calling "Fill" with "1" argument(s): "Incorrect syntax near ','." testTabForm.psf (59): ERROR: At Line: 59 char: 3
ERROR: + $SqlAdapter.Fill($DataSet)
ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~
ERROR: + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
ERROR: + FullyQualifiedErrorId : SqlException
And the code which does this aspect of it is the following:
$server = "server"
$database = "database"
$A = $record.Text
$B = $textB.Text
$C = $textC.Text
$insert = "INSERT INTO dbo.AMY (ColumnA, ColumnB, ColumnC) VALUES ($A,$B,$C)"
$connectionTemplate = "Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database;"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $insert
$command.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()
Any ideas on how to fix this would be appreciated.

Test for the existance of B and C building your insert command along the way.$insert = "INSERT INTO dbo.AMY (ColumnA, ColumnB, ColumnC) VALUES ($A, "
if ($B.Length) { $insert += "'$B', " }
else { $insert += "NULL, " }
if ($C.Length) { $insert += "'$C')" }
else { $insert += "NULL)" }

The problem ended up being a simple syntax error, the variables needed to be in quotes for a string specifically single quotes, once I did this it worked perfectly. Thanks.

Related

Powershell SQL Query - Problem with a property "Site"

I'm a beginner in powershell and SQL Query. I figured out how to make a Query and i'm getting some results but i ran into a problem and don't know how to manage it.
My Code:
$dataSource = "MyBdServer"
$database = "DabaseName"
$connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$sqlCommand = "select Site, Pavillon, Floor, Localisation, Description from [DabaseName].dbo.Local_C where Location_ID In ( '6096B3F168C546BE84A7A98C8210E947')"
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
Output
Site : NCH
Pavillon : D
Floor : Level S3
Localisation : D.S3.5113
Description : CONSULT./ENTREVUE
The problem: when i'm trying to get the value by properties for site ($DataSet.Tables.Site) value is always empty, it works well with Pavillon, Floor, Localisation and Description. I think it's because the Object System.Data.Dataset has a property with that name by default. I'm trying to find a way to use this value.
DataColumn has a Site property which is why you're unable to reference the values of the Site column. There are two easy alternatives, the easiest one is to reference the .Table property of your DataTable and then the .Site property and the other alternative is to use the .ToTable(..) method from DataView.
$columns = #(
'Site'
'Pavillon'
'Floor'
'Localisation'
'Description'
)
$dtt = [System.Data.DataTable]::new()
$columns | ForEach-Object{
$dtt.Columns.Add([System.Data.DataColumn]::new($_))
}
$row = $dtt.NewRow()
$row.Site = 'NCH'
$row.Pavillon = 'D'
$row.Floor = 'Level S3'
$row.Localisation = 'D.S3.5113'
$row.Description = 'CONSULT./ENTREVUE'
$dtt.Rows.Add($row)
$dtt.Site # => Doesn't work
$dtt.Table.Site # => Works
$dv = [System.Data.DataView]::new($dtt)
$dv.ToTable($true, 'Site') # => Works

How check for errors with powershell sql

I need to check for general errors with my sql, like make sure it connects ok, make sure it returns with the query results ok, etc. I tried try/catch, but even though I know my login is wrong, it's not finding an error with the catch. I had found the try/catch idea at try catch.
How do I identify or catch when it doesn't logon to the db, or returns 0 results?
This is what I have so far:
function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile, [string]$facility)
{
#create sql connection to connect to the sql DB
try{
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=blah;Database=blah;User ID=blah;Password=blah" #sql connection
$sqlConnection.Open()
#Create a SqlCommand object to define the query
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.CommandText = $SQLquery
$sqlCmd.Parameters.Add('#facility',$facility)
$sqlCmd.Connection = $sqlConnection
#create a SqlAdapter that actually does the work and manages everything
$sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$sqlAdapter.SelectCommand = $sqlCmd
$sqlAdapter.SelectCommand.CommandTimeout=300 #set timeout for query execution to 5 minutes (60x5=300)
#create an empty dataSet for the query to fill with its results
$dataSet = New-Object System.Data.DataSet
#execute the query and fill the dataSet (then disconnect)
$sqlAdapter.Fill($dataSet)
$sqlConnection.Close()
#dump the data to csv
$DataSet.Tables[0] | Export-Csv $extractFile #this may not be comma delimited...need to check
} #try
catch{
if($LASTEXITCODE -ne 0) #if there was an error, record it
{
Write-host $PSItem.ToString()
$global:ErrorStrings.Add("Exception: $LASTEXITCODE ; $PSItem.ToString() ")
}
else
{
$global:ErrorStrings.Add("Exception: $LASTEXITCODE ; $PSItem.ToString() ")
}
} #catch
}

SQL DB Power Shell Connection Code error I don't understand

So I have a peice of code that I'm using to try to write to the database but I keep getting an error at the bottom that makes no sense. everything seems to work interdependantly but executing the code is just... no.
I pulled this db query ps code from
https://blogs.msdn.microsoft.com/buckwoody/2009/04/13/run-a-sql-server-command-from-powershell-without-the-sql-server-provider/
here is the code, the error is below the Close().
I'm totally lose. Help?
$strserver = "1sl-den-db03"
$strdatabase = "reporting"
$strusername = "belamiinc\PSscripts"
#you can get convert pass by "p#ssw0rdt3xt" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Users\daniel.williams\Documents\Scriptcred.txt"
$strpassword = Get-Content "C:\Users\daniel.williams\Documents\Scriptcred.txt" | ConvertTo-SecureString
#$strQuery = "
#INSERT INTO EventLog (SourceID, Started, Completed, Result, Context, Machine)
#SELECT (50, null, null, 'error undefined query','query run outside of manufacturer','1sl-den-db03')
#"
$strQuery = "
insert into [reporting].[dbo].[password] (Username, Password)
select (test, testpw)
"
# Create and open a database connection
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=$strserver;database=$strdatabase;Integrated Security=SSPI; User ID=$strusername; password=$strpassword"
#Create a command object
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = $strQuery
$sqlConnection.Open()
#Execute the Command
$sqlCommand.ExecuteNonQuery()
$sqlConnection.Close()
The error is:
PS C:\Windows> Y:\DEPT - IT\Scripting\PSConnecttoSQL.ps1
Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near ','."
At Y:\DEPT - IT\Scripting\PSConnecttoSQL.ps1:27 char:1
+ $sqlCommand.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
You don't need a reader for an INSERT command. Change this line:
$sqlReader = $sqlCommand.ExecuteReader()
Into:
$sqlCommand.ExecuteNonQuery()
More about SqlCommand.ExecuteNonQuery()

Powershell Function SQL Stored Procedure with Parameters

The error received is "The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlCommand objects." & "Procedure or function 'usp__SingleUpdateServerBackupPath' expects parameter '#decServerName', which
was not supplied."
PowerShell code:
Set-StrictMode -Version 1.0
function update-serverbackuppath {
param(
[Parameter(Mandatory=$True,ValueFromPipeLine=$True)][object[]]$inputobject
)
BEGIN {
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$connection.ConnectionString = "server=servername;database=database;trusted_connection=yes"
$connection.Open()
}
PROCESS {
$UpdateBackupPath = New-Object -TypeName System.Data.SqlClient.SqlCommand
$UpdateBackupPath.Connection = $connection
$UpdateBackupPath.CommandText = "usp__SingleUpdateServerBackupPath"
$UpdateBackupPath.Commandtype = [System.Data.Commandtype]::StoredProcedure
$ParamUpdateBackupPath = New-Object -TypeName System.Data.SqlClient.SqlParameter
$ParamUpdateBackupPath.ParameterName = "#decBackupPath"
$ParamUpdateBackupPath.SqlDbType = [System.Data.SqlDbType]::VarChar
$ParamUpdateBackupPath.Direction = [System.Data.ParameterDirection]::Input
$ParamUpdateBackupPath.Value = $inputobject.paths
$ParamUpdateBackupPathServerName = New-Object -TypeName System.Data.SqlClient.SqlCommand
$ParamUpdateBackupPathServerName.ParameterName = "#decServerName"
$ParamUpdateBackupPathServerName.SqlDbType = [System.Data.SqlDbType]::VarChar
$ParamUpdateBackupPathServerName.Direction = [System.Data.ParameterDirection]::Input
$ParamUpdateBackupPathServerName.Value = $inputobject.names
$UpdateBackupPath.Parameters.Add($ParamUpdateBackupPath)
$UpdateBackupPath.Parameters.Add($ParamUpdateBackupPathServerName)
$reader = New-Object -TypeName System.Data.SqlClient.SqlDataReader = $UpdateBackupPath.ExecuteReader()
}
END {
$connection.Close()
}
}
SQL Procedure:
Create Procedure usp__SingleUpdateServerBackupPath
(
#decBackupPath AS varchar(50),
#decServerName AS varchar(50)
)
AS
UPDATE BCKP
SET PTH = #decBackupPath
FROM BCKP
INNER JOIN SRVR
ON SRVR.ID = BCKP.FK_SRVR
WHERE SRVR.NM = #decServerName
CSV File Format
Import-Csv -Path C:\Bin\Repos\Backup.csv | C:\Bin\Scripts\update-serverbackuppath.ps1
Names Paths
Server1 \\fileshare\server_name
The Powershell code has several syntax errors, like referring to enums in erroneus a way:
# Incorrect form
[System.Data.Commandtype.StoredProcedure]
# Correct form for referring to enumeration
[System.Data.Commandtype]::StoredProcedure
Later on, there is an undeclared object which's member method is called:
# $command is not set, so ExecuteReader method is available
$reader = $command.ExecuteReader()
It is highly recommended to use strict mode in Powershell. It helps catching typos by preventing access to non-existing properties an uninitialized variables.
Edit
After the updated code, there are still two errors:
# This doesn't make sense. The variable should be SqlParameter, not SqlCommand
$ParamUpdateBackupPathServerName = New-Object -TypeName System.Data.SqlClient.SqlCommand
# Like so:
$ParamUpdateBackupPathServerName = New-Object -TypeName System.Data.SqlClient.SqlParameter
# This is nonsense syntax
$reader = New-Object -TypeName System.Data.SqlClient.SqlDataReader = $UpdateBackupPath.ExecuteReader()
# Like so:
$reader = $UpdateBackupPath.ExecuteReader()

SQL Query through powershell w/variables

I am attempting to run a query against SQL using powershell and was successful until I attempted to throw parameters in the mix. My code is as follows:
$parameter="TEST"
$connectionString = "CONNECTION STRING";
$Connection = New-Object System.Data.OleDb.OleDbConnection $connectionString;
$Values = New-Object System.Data.DataSet;
$SelectCommand = "Select Value FROM dbo.Values WHERE Value=#param";
$Command = New-Object System.Data.OleDb.OleDbCommand $SelectCommand,$Connection;
$Command.Parameters.Add("#param", [System.Data.OleDb.OleDbType]::VarChar, 50)
$Command.Parameters["#param"].Value = $parameter;
$adapter = New-Object System.Data.OleDb.OleDbDataAdapter $Command;
[void] $adapter.Fill($Values);
foreach($a in $Values.tables[0].Rows )
{
#handle returned values
}
I have messed around with different ways of passing a parameter that i have found online and always get the same result:
Exception calling "Fill" with "1" argument(s): "Must declare the scalar variable "#try"."
At line:28 char:31
+ [void] $adapter.Fill <<<< ($Values);
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Any help would be appreciated, finding good examples of powershell SQL queries has been rough. Using OLeDB is not necessary, if someone has an example using another provider that is fine as well, I have also been messing with System.Data.SqlClient.SqlConnection without success.
Since you are using OleDbCommand your parameter markers should be ? instead of #paramname.
Or you can use System.Data.SqlClient.SqlCommand instead of OleDbCommand so you can use #paramname.
Check this out:
http://blogs.msdn.com/b/spike/archive/2010/03/03/must-declare-the-scalar-variable.aspx