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

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()

Related

PowerShell Exception Calling "Unable to cast COM object" - Error loading type library/DLL

I have the following script in PowerShell which has been executing fine for months. I did not change anything, but I am receiving the error below. I've tried on other machines, but I keep receiving the same error. Any assistance or guidance would be greatly appreciated. I would have to get our IT involved for any registry or permission changes, and I would have to walk them through the process as well.
Script
# start Excel
$excel = New-Object -comobject Excel.Application
$ms_access = New-Object -comobject Access.Application
function Test-IsFileAvailable {
[CmdletBinding()]
param (
[parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string]$Path
)
if (!(Test-Path -Path $Path -PathType Leaf)) {
# the file is not found
Write-Verbose "File '$Path' not found."
return $false
}
try {
$file = New-Object System.IO.FileInfo $Path
$stream = $file.Open([System.IO.FileMode]::Open,
[System.IO.FileAccess]::ReadWrite,
[System.IO.FileShare]::None)
if ($stream) { $stream.Close() }
Write-Verbose "File '$Path' is not locked."
return $true
}
catch {
# file is locked by a process.
Write-Verbose "File '$Path' is locked by another process."
return $false
}
}
#set path files
$FilePath_raw = 'N:\DATA\StatusReport_Raw.xlsx'
$FilePath_report = 'N:DATA\StatusReport.xlsx'
$FilePath_date = 'N:\DATA\ReportDate.xlsx'
$FilePath_access = "N:\DATA\Access\Processing.accdb"
if (!(Test-IsFileAvailable $FilePath_raw -Verbose)) { exit }
if (!(Test-IsFileAvailable $FilePath_report -Verbose)) { exit }
if (!(Test-IsFileAvailable $FilePath_date -Verbose)) { exit }
if (!(Test-IsFileAvailable $FilePath_access -Verbose)) { exit }
#make it visible ($true) or invisible ($false)
$excel.Visible = $false
$wb_eval1 = $excel.Workbooks.Open($FilePath_raw)
$ws_eval1 = $wb_eval1.sheets.Item(1)
$wb_eval2 = $excel.Workbooks.Open($FilePath_report)
$ws_eval2 = $wb_eval2.sheets.Item(1)
$wb_date = $excel.Workbooks.Open($FilePath_date)
$ws_date = $wb_date.sheets.Item(1)
$ws_eval2.Cells.Clear()
$lrow2 = $ws_eval1.usedRange.Rows.Count
$range2=$ws_eval1.Range("A3:AA$lrow2")
$range2.copy()
$cpy_range_eval = $ws_eval2.Range("A1")
$ws_eval2.Paste($cpy_range_eval)
$date_range = $ws_eval1.Range("B1")
$date_range.copy()
$cpy_range_date = $ws_date.Range("A2")
$ws_date.Paste($cpy_range_date)
$wb_date.Save()
$wb_date.Close()
$wb_eval2.Save()
$wb_eval2.Close()
$wb_eval1.Close()
$ms_access.OpenCurrentDatabase($Filepath_access)
$ms_access.Run("ExportExcel")
$excel.Quit()
$ms_access.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb_eval1) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb_eval2) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb_date) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ms_access) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
$excel = $ms_access = $null
$wshell = New-Object -ComObject Wscript.Shell
$output = $wshell.Popup("The task has finished")
Add-Type -AssemblyName System.Windows.Forms
$global:balloon = New-Object System.Windows.Forms.NotifyIcon
$path = (Get-Process -id $pid).Path
$balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Info
$balloon.BalloonTipText = 'The reports have been processed.'
$balloon.BalloonTipTitle = "Attention $Env:USERNAME"
$balloon.Visible = $true
$balloon.ShowBalloonTip(20000)
Error Message
Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your
shell will retain its current effective execution policy of RemoteSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information please see "Get-Help
Set-ExecutionPolicy".
At line:1 char:46
+ ... -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'N ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
+ FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
VERBOSE: File 'N:\DATA\StatusReport_Raw.xlsx' is not locked.
VERBOSE: File 'N:\DATA\StatusReport.xlsx' is not locked.
VERBOSE: File 'N:\DATA\ReportDate.xlsx' is not locked.
VERBOSE: File 'N:\DATA\Access\Processing.accdb' is not locked.
True
True
True
Exception calling "OpenCurrentDatabase" with "1" argument(s): "Unable to cast COM object of type
'Microsoft.Office.Interop.Access.ApplicationClass' to interface type 'Microsoft.Office.Interop.Access._Application'.
This operation failed because the QueryInterface call on the COM component for the interface with IID
'{68CCE6C0-6129-101B-AF4E-00AA003F0F07}' failed due to the following error: Error loading type library/DLL. (Exception
from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))."
At N:\RUN\RUN.ps1:82 char:1
+ $ms_access.OpenCurrentDatabase($Filepath_access)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidCastException
Exception calling "Run" with "1" argument(s): "Unable to cast COM object of type
'Microsoft.Office.Interop.Access.ApplicationClass' to interface type 'Microsoft.Office.Interop.Access._Application'.
This operation failed because the QueryInterface call on the COM component for the interface with IID
'{68CCE6C0-6129-101B-AF4E-00AA003F0F07}' failed due to the following error: Error loading type library/DLL. (Exception
from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))."
At N:\RUN\RUN.ps1:83 char:1
+ $ms_access.Run("ExportExcel")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidCastException
Exception calling "Quit" with "0" argument(s): "Unable to cast COM object of type
'Microsoft.Office.Interop.Access.ApplicationClass' to interface type 'Microsoft.Office.Interop.Access._Application'.
This operation failed because the QueryInterface call on the COM component for the interface with IID
'{68CCE6C0-6129-101B-AF4E-00AA003F0F07}' failed due to the following error: Error loading type library/DLL. (Exception
from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))."
At N:\RUN\RUN.ps1:86 char:1
+ $ms_access.Quit()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidCastException
So if I am understanding the problem the solution should be quite simple. Before you run the Powershell script right click on it and hit run as administrator. The reason the error is occurring is that you need escalated privileges to set the execution policy. As for the other issue it may be that those files are now protected and therefore unable to load so by using the run as administration option it should allow it to access those files.
I have had several issue in the past where just running with escalated permissions has fixed problems. Now I would not do this as a permanent fix but if this works it would at least get it working again.This is why you shouldn't

Re-run SQL on error

I am building a PowerShell script to clean up the hundreds of batch file executions and scheduled tasks that I have running on my machine.
One of the processes that I am cleaning up is a connection to a remote SQL server that downloads .csv files onto a network location.
It works over and over again and then I receive the following message
Exception calling "Fill" with "1" argument(s): "ExecuteReader: CommandText
property has not been initialized"
At L:\Operations Database\BatchScriptExecutions\PS\Scripts\0000 - 0100\ControlsBrokerRec.ps1:2426 char:1
+ $SqlAdapter.Fill($DataSet);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
I am wondering what I can do to re-run the process if this error occurs? Is there a way in PowerShell to loop on error?
The code that is running is multiple iterations of the following:
## - Runs Script from Set Location
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandTimeout=$timeout;
$SqlCMD.CommandText = $CL3CASHPOSITIONSSCRIPTWINS;
$SqlCmd.Connection = $SqlConnection;
## - Extract Data and build sql data object
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
## - Check for Null Return of Data into table
if ($DataSet.Tables["Table"]) {
$isnotnull
$DataSet.Tables["Table"] | Export-Csv $CL3CASHPOSITIONSEXPORTWINS -NoTypeInformation
echo "Cash Wins"
} else {
echo "NULL NULL NULL"
}
The issue happens so sporadically that I am unsure how I can test solutions for this. I am assuming that there should be some kind of catch statement within the code, but I'm at a loss.

Data from Powershell forms with blank fields into SQL Server database

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.

Powershell DoCmd.RunSQL query fails to update MS Access

I'm trying to update an MS Access table by running a query from Powershell. I've simplified my code as follows:
Write-Host "Start Access ..."
$Acc = New-Object –com Access.Application
Write-Host "Open database ..."
$Acc.OpenCurrentDataBase("C:\Users\Administrator\Documents\redacted\imh-test.accdb")
Write-Host "connected ..."
$Acc.DoCmd.RunSQL("update DeepcleanEntryDoor set Title = 'Mrs'")
Write-Host "Data appended, close Access ..."
$Acc.Quit()
Write-Host "... process complete!"
I get a "The RunSQL action was canceled." as follows:
Start Access ...
Open database ...
connected ...
Exception calling "RunSQL" with "1" argument(s): "The RunSQL action was canceled."
At line:8 char:1
+ $Acc.DoCmd.RunSQL("update DeepcleanEntryDoor set Title = 'Mrs'")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Data appended, close Access ...
... process complete!
I've also tried DoCmd.OpenQuery using an existing query, but get the same result.
What am I missing here?
Thanks
DB

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