使用 Powershell 压缩和修复目录中的所有 Access 数据库

问题描述

我正在寻找一种方法,通过脚本使用 Powershell 压缩和修复某个目录中的所有 Access 数据库

下面的 VBA 代码有效,但需要一个用于 Powershell:

Find all Access databases,and Compact and Repair

我是 Powershell 的新手,因此非常感谢您的帮助。

谢谢

解决方法

你可以试试这个。

Add-Type -AssemblyName Microsoft.Office.Interop.Access

$rootfolder = 'c:\some\folder'

$createlog = $true # change to false if no log desired

$access = New-Object -ComObject access.application
$access.Visible = $false
$access.AutomationSecurity = 1

Get-ChildItem -Path $rootfolder -File -Filter *.accdb -Recurse -PipelineVariable file | ForEach-Object {

    $newname = Join-Path $file.Directory ("{0}_compacted{1}" -f $file.BaseName,$file.Extension)

    $message = @"
    Current file: {0}
    Output file: {1}
"@ -f $file.FullName,$newname

    Write-Host $message -ForegroundColor Cyan

    $access.CompactRepair($file.fullname,$newname,$createlog)
}

$access.Quit()

这会将每个压缩的数据库输出为原始文件的名称,并在名称后附加 _compacted(在扩展名之前)。除了实际压缩数据库之外,我已经以各种方式测试了这一点。

编辑

关于您的评论,一些小的更改应该可以达到预期的结果。请记住,这会将所有新文件放在同一文件夹中。对于您的情况,这可能不是问题,但如果文件名重复,您就会遇到问题。

$rootfolder  = 'c:\some\folder'
$destination = 'c:\some\other\folder'
$todaysdate  = get-date -format '_dd_MM_yyyy'

Add-Type -AssemblyName Microsoft.Office.Interop.Access

$createlog = $true # change to false if no log desired

$access = New-Object -ComObject access.application
$access.Visible = $false
$access.AutomationSecurity = 1

Get-ChildItem -Path $rootfolder -File -Filter *.accdb -Recurse -PipelineVariable file | ForEach-Object {

    $newname = Join-Path $destination ("{0}$todaysdate{1}" -f $file.BaseName,$createlog)
}

$access.Quit()