Advertisement
Old-Lost

Classes for Access databases

Jun 9th, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class AccessDB {
  2.     hidden [System.__ComObject]$Connection
  3.     [string]$DBPath
  4.     AccessDB([string]$Path) {
  5.         if (-not (Test-Path $Path)) {
  6.             throw "Invalid Access database path specified ($Path). Please supply full absolute path to database file!"
  7.         }
  8.         $FullPath = (Resolve-Path $Path).ProviderPath
  9.         $this.DBPath = $FullPath
  10.         $this.Connection = New-Object -ComObject ADODB.Connection
  11.         try {
  12.             $this.Connection.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$FullPath`";Persist Security Info=False;")
  13.         } catch {
  14.             $this.Connection = $null
  15.         }
  16.     }
  17. }
  18. class AccessRS {
  19.     hidden [System.__ComObject]$RecordSet
  20.     [System.Collections.Generic.List`1[PSCustomObject]]$Values = @()
  21.     [string]$Query
  22.     [AccessDB]$DB
  23.     AccessRS([AccessDB]$Conn, [string]$Query ) {
  24.         [int]$CursorType = 3
  25.         [int]$LockType = 3
  26.         $this.DB = $Conn
  27.         $this.Query = $Query
  28.         $this.RecordSet = New-Object -ComObject ADODB.Recordset
  29.         Write-Verbose "$Query, $($this.DB.Connection.Provider), $CursorType, $LockType"
  30.         $this.RecordSet.Open($Query, $this.DB.Connection, $CursorType, $LockType)
  31.         $fields = $this.GetAccessRecordSetStructure()
  32.         try { $this.RecordSet.MoveFirst() } catch { return }
  33.         do {
  34.             $record = @{ }
  35.             foreach ($field in $fields) {
  36.                 $record[$field.Name] = $this.RecordSet.Fields.Item($field.Name).Value
  37.             }
  38.             $this.Values.Add( ([PSCustomObject]$record))
  39.             $this.RecordSet.MoveNext()
  40.         } until ($this.RecordSet.EOF -eq $True)
  41.     }
  42.     [boolean]Test() {
  43.         if (-not $this.RecordSet) { return $false }
  44.         return ( $this.RecordSet.RecordCount -gt 0 )
  45.     }
  46.     [System.Collections.Generic.List`1[PSCustomObject]]GetAccessRecordSetStructure() {
  47.         [System.Collections.Generic.List`1[PSCustomObject]]$Fields = @()
  48.         $this.Recordset.Fields | % {
  49.             $Fields.Add( ([PSCustomObject]@{
  50.                         Name        = $_.Name
  51.                         Attributes  = $_.Attributes
  52.                         DefinedSize = $_.DefinedSize
  53.                         Type        = $_.Type
  54.                     }))
  55.         }
  56.         return $Fields
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement