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
Related
Running Macro in Power point. Setting it to run with a PS1 file, but getting error on application.run cmd.
I am setting this up to create a bat file and task scheduler. The file opens but then I get an error upon running the script. Below is my script. Using Office 2016 professional. I have tried both just using the Macroname "mailme" and "Module1.mailme" Any help?
$ppt = New-Object -ComObject PowerPoint.Application
#open file
$FilePath = 'C:\Alerts.pptm'
$workbook = $ppt.Presentations.Open($FilePath)
#access the Application object and run a macro
$app = $presentation.application
$app.Run("Module1.mailme", #())
$ppt.Quit()
You cannot call a method on a null-valued expression.
At line:10 char:1
+ $app.Run("Module1.mailme", #())
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
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
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()
My company sells/supports a product that utilizes a SQL database. I've been trying to create a PowerShell script to prep the entire server for a new install. The script needs to install all the required Windows Server Roles/features, then install SQL, then SQL Server Management Studio, and finally, Enable TCP/IP for SQL. I have gotten all but the last step to work, and trying to figure this one out is kicking my butt...
I feel like I'm on the right path here, but I'm currently stuck...
If I run:
$smo = 'Microsoft.SqlServer.Management.Smo.'
$wmi = new-object ($smo + 'Wmi.ManagedComputer')
$wmi
I actually get results showing:
ConnectionSettings :
Microsoft.SqlServer.Management.Smo.Wmi.WmiConnectionInfo
Services : {MSSQL$WEBACCESS, MSSQLFDLauncher$WEBACCESS,
SQLAgent$WEBACCESS, SQLBrowser}
ClientProtocols : {np, sm, tcp}
ServerInstances : {SQLSERVER}
ServerAliases : {}
Urn : ManagedComputer[#Name='HOSTNAME']
Name : HOSTNAME
Properties : {}
UserData :
State : Existing
I'm then using this information and running:
$uri = "ManagedComputer[#Name='']/ ServerInstance[#Name='']/ServerProtocol[#Name='Tcp']"
$Tcp = $wmi.GetSmoObject($uri)
$Tcp
With this, I get the following error:
Exception calling "GetSmoObject" with "1" argument(s): "Attempt to retrieve data for object failed for ManagedComputer 'HOSTNAME'."
At line:9 char:1
+ $Tcp = $wmi.GetSmoObject($uri)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [],
ParentContainsErrorRecordException
+ FullyQualifiedErrorId : FailedOperationException
Anybody have any idea what I'm doing wrong? I feel like, if I can figure this part out, I can figure out how to alter the settings, but I can't even pull up the settings at this point.
You should consider looking at dbatools, a PowerShell module written by SQL Server and PowerShell MVPs with hundreds of really useful functions for managing SQL Server.
I thought they might have a function that does what you need already. It looks like they don't, but in searching I had a look at Set-DbaTcpPort, and finally at the source code for that function on GitHub, where I saw this code snippet:
$wmi = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $instance
$wmiinstance = $wmi.ServerInstances | Where-Object { $_.Name -eq $wmiinstancename }
$tcp = $wmiinstance.ServerProtocols | Where-Object { $_.DisplayName -eq 'TCP/IP' }
$IpAddress = $tcp.IpAddresses | where-object { $_.IpAddress -eq $IpAddress }
$tcpport = $IpAddress.IpAddressProperties | Where-Object { $_.Name -eq 'TcpPort' }
So that led me to conclude that you could do the same with your object; your $wmi object seems to be the same as their $wmiinstance object even if you arrived at them slightly differently.
From there you can query with Where-Object or the .Where method:
$tcp = $wmi.ClientProtocols.Where({$_.DisplayName -eq 'TCP/IP'})
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.