I need to automate some data extraction from a Microsoft Access DB. The DB is provided to me by a third party, and so I do not have control over what is in the DB when it is received. I need to use Powershell to automate extraction of data from the DB.
Is there any way to use powershell to create a query in the accessDB? This is, essentially, the essence of the code I am looking for:
$l_dbPath = "C:\Path\To\dataBase.accdb"
$l_accessApp = new-object -com access.application
$l_accessApp.OpenCurrentDatabase($l_dbPath)
$l_query = "SELECT SomeTable.SomeField From SomeTable;"
$l_queryName = "Export_Query"
$l_accessApp.CurrentDB().CreateQueryDef($l_queryName, $l_query)
$l_outputFile = "C:\temp\output.csv"
$e_acExportDelim = 2 #$l_accessApp.Enumerations.AcTextTransferType.acExportDelim #arg. this does not seem to exist...
$e_HasFieldNamesYes=-1
$l_exportSpec = ""
$l_accessApp.DoCmd.TransferText($e_acExportDelim,$l_exportSpec,$l_queryName,$l_outputFile,$e_HasFieldNamesYes)
$l_accessApp.CloseCurrentDatabase()
However, the line $l_accessApp.CurrentDB.CreateQueryDef($l_queryName, $l_query)
fails, because $l_accessApp.CurrentDB()
returns null, not the current DB. I can find no way to access CreateQueryDef
from Powershell.
I have looked at Programmatically Build Access Query, Create a query dynamically, Use Powershell to create access 2007 Queries?, and other posts, but found nothing that works.
Thanks for any help.
EDIT:
It turns out that the code as I had it above does, in fact, work! The issue all along was simply that I did not have a machine on which I had both DAO and Access installed. After testing the separate components (using DAO, and using Access) on different machines, and getting IT support to give me a machine with DAO and Access both actually installed, the above code does in fact work. (With MS Access installed and loaded, but DAO not installed, $l_accessApp.CurrentDB()
returns $null
. With DAO installed, it returns a DBEngine object, as expected.)
$l_accessApp.OpenCurrentDatabase($l_dbPath)
– Minos