Skip to content

Instantly share code, notes, and snippets.

@jahands
Last active September 28, 2017 19:46
Show Gist options
  • Save jahands/df22b9ffd466ae46f2eef73680877d88 to your computer and use it in GitHub Desktop.
Save jahands/df22b9ffd466ae46f2eef73680877d88 to your computer and use it in GitHub Desktop.
PowerShell database class
[JhaContentDB]::new($dbPath).Load().Add($item).Save().Close()
Class JhaContentDB {
[string]$Path
[JhaContentDBItem[]]$Items
[boolean]$Dirty
[string]$LockPath
JhaContentDB([string]$Path) {
$this.Path = $Path
$this.LockPath = (GetLockPath Play JhaContentDB)
}
[JhaContentDB]Load() {
if ($this.IsLocked()) {
Write-Error "DB Locked: $($this.Path)" -ErrorAction:Stop
}
$this.Lock()
if (Test-Path $this.Path) {
$this.Items = [JhaContentDBItem[]](Import-Csv $this.Path)
}
Return $this
}
[JhaContentDB]Add([JhaContentDBItem]$Item) {
$this.Items += $Item
$this.Dirty = $true
Return $this
}
[JhaContentDB]Save() {
if ($this.Dirty) {
Write-Verbose "Saving DB to disk"
$this | Select-Object -ExpandProperty Items | Export-Csv $this.Path
}
Return $this
}
Close() {
$this.Save()
$this.Unlock()
}
hidden Lock() {
Set-Content -Path $this.LockPath -Value (Get-Date).ToString()
}
hidden Unlock() {
Remove-Item -Path $this.LockPath
}
hidden [boolean]IsLocked() {
Return (Test-Path $this.LockPath)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment