使用 powershell 在 MS-Access 中创建查询

2024-05-05

我需要自动从 Microsoft Access DB 中提取一些数据。数据库是由第三方提供给我的,因此我无法控制收到数据库时的内容。我需要使用 Powershell 自动从数据库中提取数据。

有没有办法使用powershell在accessDB中创建查询?这本质上是我正在寻找的代码的本质:

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

然而,该行$l_accessApp.CurrentDB.CreateQueryDef($l_queryName, $l_query)失败,因为$l_accessApp.CurrentDB()返回 null,而不是当前数据库。我找不到访问的方法CreateQueryDef来自 Powershell。

我看过以编程方式构建访问查询 https://stackoverflow.com/questions/23092523/programmatically-build-access-query, 通过 MS Access 2003 中的代码动态创建查询 [VBA] https://stackoverflow.com/questions/390420/create-a-query-dynamically-through-code-in-msaccess-2003-vba, 使用 Powershell 创建 access 2007 查询? https://stackoverflow.com/questions/3559158/use-powershell-to-create-access-2007-queries和其他帖子,但发现没有任何效果。

谢谢你的帮助。

编辑: 事实证明,我上面的代码确实有效!问题一直很简单,就是我没有一台机器上同时安装了 DAO 和 Access。在不同的机器上测试了单独的组件(使用 DAO 和使用 Access),并获得 IT 支持给我一台实际安装了 DAO 和 Access 的机器后,上面的代码实际上可以工作。 (安装并加载了 MS Access,但未安装 DAO,$l_accessApp.CurrentDB()回报$null。安装 DAO 后,它会按预期返回一个 DBEngine 对象。)


创建一个查询定义:

$dbe =new-Object -comobject DAO.DBEngine.120
$path="c:\path\to\db.mdb"
$db = $dbe.opendatabase($path)

$l_query = "select table1.* from table1"
$l_queryName="testquery"
$l_outputFile="z:\test.csv"

$db.CreateQueryDef($l_queryName, $l_query)
$db.closedatabase


$l_outputFile = "z:\test.csv"
$e_acExportDelim = 2 
$e_HasFieldNamesYes=-1
$l_exportSpec = ""

$l_accessApp = new-object -com access.application
$l_accessApp.OpenCurrentDatabase($path)
$l_accessApp.DoCmd.TransferText($e_acExportDelim,$l_exportSpec,$l_queryName,$l_outputFile,$e_HasFieldNamesYes)
            $l_accessApp.CloseCurrentDatabase()

$l_accessApp.CloseCurrentDatabase()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 powershell 在 MS-Access 中创建查询 的相关文章

随机推荐