Last active
September 28, 2017 19:46
-
-
Save jahands/df22b9ffd466ae46f2eef73680877d88 to your computer and use it in GitHub Desktop.
PowerShell database class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[JhaContentDB]::new($dbPath).Load().Add($item).Save().Close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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