1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MS AccessファイルのデータをPowerShellに取り込む

Posted at

OSが64bitの場合は手当が必要だったので出力は必ずCSVになるようにした。

export-accdb.ps1
<#
64bit OS の場合はインストールされている office に合わせたアーキテクチャのpowershellで実行すること

x32 office
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe

x64 office
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
# > 
Param(
    [Parameter(Mandatory=$True)]
    [string]$Path,

    [Parameter(Mandatory=$True)]
    [string]$Table
)
$con = New-Object -ComObject ADODB.Connection

if(-not (Test-Path $Path)) { throw 1 }

if (([System.IO.Path]::GetExtension($path)) -eq ".mdb") {
    $connectionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = $path"
} elseif(([System.IO.Path]::GetExtension($path)) -eq ".accdb") {
    $connectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = $path"
} else {
    throw 1
}

$con.Open($connectionString)

$sql ="SELECT * FROM $Table;"

$rs = New-Object -ComObject ADODB.Recordset


$adOpenStatic = 3
$adLockOptimistic = 3
$rs.Open($sql, $con, $adOpenStatic, $adLockOptimistic)
$rs.MoveFirst()
& {
    while($rs.EOF -eq $False) 
{
        $o = new-object psobject
        $rs.Fields | ForEach-Object {
            $o | Add-Member -NotePropertyName $_.Name -NotePropertyValue $_.value
        }
        Write-Output $o
        $rs.MoveNext()
    }
} | ConvertTo-Csv -NTI

$rs.Close()
$con.Close()
$rs = $null
$con = $null
使い方
$ps = "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe"
$Path = ".\hoge.accdb"
$csv = & $ps -ExecutionPolicy bypass -File .\export-accdb.ps1 -Path $Path -Table table1
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?