在Powershell中压缩MS Access数据库的示例代码

时间:2012-12-24 18:30:20

标签: ms-access powershell

我可以找到示例VBA和C#代码来执行此操作,但没有 Powershell片段(谷歌对此非常沉默,就像Stackoverflow一样)。任何人都可以指点我的Powershell(或提供一些)这样做吗?我期待它可以通过COM获得Access的API。

谢谢!

1 个答案:

答案 0 :(得分:1)

我应该知道在圣诞节前一天要问,并希望快速回复,所以我自己做了。事实证明答案在任何情况下都非常简单。下面的顶部函数执行我需要的操作,驱动程序函数将循环遍历目录中的所有访问数据库并压缩它们中的每一个。

function compactDatabaseFile($sourceFilename, $destinationFileName)
{

    $application =  New-Object -ComObject Access.Application

    Write-Host $($(Get-Date).ToString() + ": Starting compacting of $sourceFilename to $destinationFileName")

    $application.CompactRepair($sourceFilename,$destinationFileName, $true)

    Write-Host $($(Get-Date).ToString() + ": Finished compacting of $sourceFilename to $destinationFileName")

    $application.Quit()
}

function driver($sourceDirectory, $newDestinationDirectory, $filePatterns = @("*.mdb","*.accdb"))
{
    if (Test-Path $newDestinationDirectory) {
        Write-Host "Destination Directory $newDestinationDirectory exists.  Exiting without doing anything."
        Exit
    }

    if (!$(Test-Path $sourceDirectory)) {
        Write-Host "SourceDirectory $sourceDirectory not found.  Exiting without doing anything."
        Exit
    }

    mkdir $newDestinationDirectory | Out-Null

    gci -path $($sourceDirectory + "\*") -include $filePatterns | % {
        $sourceFileName = $($sourceDirectory + "\" + $_.Name);
        $destinationFileName = $($newDestinationDirectory + "\" + $_.Name);
        compactDatabaseFile $sourceFileName $destinationFilename
    }
}