{"id":121618,"date":"2020-11-27T17:00:00","date_gmt":"2020-11-27T14:00:00","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/using-litedb-in-powershell-7-cloudsavvy-it\/"},"modified":"2020-11-27T17:00:00","modified_gmt":"2020-11-27T14:00:00","slug":"using-litedb-in-powershell-7-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/","title":{"rendered":"#Using LiteDB in PowerShell 7 \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a44ba76cff3b\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a44ba76cff3b\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/#Installing_LiteDB_in_PowerShell\" >Installing LiteDB in PowerShell<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/#Creating_a_New_LiteDB_Database\" >Creating a New LiteDB Database<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/#Creating_a_Table_and_Adding_a_Record_into_LiteDB\" >Creating a Table and Adding a Record into LiteDB<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/#Adding_a_Record_Into_a_LiteDB_Collection\" >Adding a Record Into a LiteDB Collection<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/#Querying_Records_in_LiteDB\" >Querying Records in LiteDB<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/#Updating_and_Removing_a_Document\" >Updating and Removing a Document<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/buradabiliyorum.com\/en\/using-litedb-in-powershell-7-cloudsavvy-it\/#Cleaning_up_the_Database_and_Next_Steps\" >Cleaning up the Database and Next Steps<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#Using LiteDB in PowerShell 7 \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-4374\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/8fec593cd19e3b20a0773cafaaaaf848\/p\/uploads\/2020\/03\/23e4a5a4.png\" alt=\"Powershell logo\" width=\"1400\" height=\"578\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p><a rel=\"nofollow noopener noreferrer\" target=\"_blank\" href=\"https:\/\/www.litedb.org\/\">LiteDB<\/a> is a .NET native NoSQL embedded database. Built-in .NET, LiteDB is easily accessible to PowerShell and works wonderfully as a local and flexible database. Built-in encryption, SQL-like commands, and ACID-compliant with full transaction support LiteDB is simple and easy to use. In this article, we will talk about you can use LiteDB within PowerShell and <a rel=\"nofollow noopener noreferrer\" target=\"_blank\" href=\"https:\/\/adamtheautomator.com\/writing-an-extension-vault-for-powershell-secretmanagement-preview-4\/\">potential use cases<\/a>!<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Installing_LiteDB_in_PowerShell\"><\/span>Installing LiteDB in PowerShell<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Available as a NuGet package, LiteDB is easily installable as a package using the <code>Install-Package<\/code> cmdlet. <a rel=\"nofollow noopener noreferrer\" target=\"_blank\" href=\"https:\/\/github.com\/mbdavid\/LiteDB\">The latest version<\/a>, at the time of publication, is version <code>5.0.9<\/code>, which we are targeting as the minimum version. Additionally, to avoid the need for administrative rights, we are installing this under the <code>CurrentUser<\/code> scope.<\/p>\n<pre><code class=\"language-powershell\">Install-Package -Name 'LiteDB' -MinimumVersion '5.0.9' -Source 'nuget.org' -Scope 'CurrentUser'&#13;\n<\/code><\/pre>\n<p>Next, we are going to import the library for use. You can simply use <code>Add-Type<\/code> and point to the path of the assembly, but we can automate that.<\/p>\n<pre><code class=\"language-powershell\"># Test if we have already loaded the assembly by looking for the PSType of LiteDB.LiteDatabase&#13;\nIf ( -Not ([System.Management.Automation.PSTypeName]'LiteDB.LiteDatabase').Type ) {&#13;\n    # 1) Get the path of the LiteDB package using the Source &#13;\n  # 2) This returns the *.nupkg file, so we use Split-Path to only return the package root path&#13;\n  # 3) Multiple DLL's will exist, usually for .NET 4.5, .NET Standard 1.3, and .NET Standard 2.0. Locate only the .NET Standard and the latest version, in this case 2.0.&#13;\n  # The path will look something like: C:\\Users\\username\\<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">App<\/a>Data\\Local\\PackageManagement\\NuGet\\Packages\\LiteDB.5.0.9\\lib\\netstandard2.0\\LiteDB.dll&#13;\n  $standardAssemblyFullPath = (Get-ChildItem -Filter '*.dll' -Recurse (Split-Path (Get-Package -Name 'LiteDB').Source)).FullName | Where-Object {$_ -Like \"*standard*\"} | Select-Object -Last 1&#13;\n  &#13;\n  Add-Type -Path $standardAssemblyFullPath -ErrorAction 'SilentlyContinue'&#13;\n}&#13;\n<\/code><\/pre>\n<p>Now that we have loaded the module for use, read on to create a new LiteDB database in the next section!<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Creating_a_New_LiteDB_Database\"><\/span>Creating a New LiteDB Database<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>There are a number of commands available for LiteDB, which you can <a rel=\"nofollow noopener noreferrer\" target=\"_blank\" href=\"https:\/\/www.litedb.org\/docs\/getting-started\/\">learn about here<\/a>, but we first need to create a brand new database. We will need to define the path where to create the database file. Since LiteDB creates single file databases, the database can be located anywhere. In this case, we will locate the DB in our current path and use the name of <code>Test.db<\/code>.<\/p>\n<pre><code class=\"language-powershell\"># Create the Test.db database in the current directory&#13;\n$Database = [LiteDB.LiteDatabase]::New((Join-Path -Path \".\" -ChildPath \"Test.db\"))&#13;\n<\/code><\/pre>\n<blockquote><p><em>Keep in mind that until you call <code>$Database.Dispose()<\/code> on the database file, the <code>Test.db<\/code> file will remain locked.<\/em><\/p>\n<\/blockquote>\n<p>In the next section we will create a table, add an index, and create a new record in our database.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Creating_a_Table_and_Adding_a_Record_into_LiteDB\"><\/span>Creating a Table and Adding a Record into LiteDB<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Similar to tables in SQL, LiteDB uses Collections, similar to MongoDB. For this article, we will create a new collection named <code>TestCollection<\/code>, and by using <code>GetCollection()<\/code> the collection will be created if it doesn\u2019t already exist.<\/p>\n<pre><code class=\"language-powershell\"># Retrieve the collection (i.e. table) to store our data in.&#13;\n$Collection = $Database.GetCollection('TestCollection')&#13;\n&#13;\n# Make sure that an index exists on the Name field so that queries work easier and quicker.&#13;\n# To allow for named queries, such as using the Name field, we ensure an index is created.&#13;\n# The result is sent to Out-Null to avoid the True console output on creation.&#13;\n$Collection.EnsureIndex('Name') | Out-Null&#13;\n<\/code><\/pre>\n<p>Indexes are valuable as they increase performance and allow for easily named queries when searching for a record. Implemented using skip-lists, indexes avoid a full-scan and deserialization of the database every time a search is done.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Adding_a_Record_Into_a_LiteDB_Collection\"><\/span>Adding a Record Into a LiteDB Collection<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>First, we need to set up the <code>LiteDB.BSONMapper<\/code>. This is LiteDB\u2019s implementation of documents, which stores key-value pairs. We first create a mapper that we can parse a PowerShell object into a document that can then be added to our collection using the <code>Insert()<\/code> method.<\/p>\n<pre><code class=\"language-powershell\">$BSONMapper = [LiteDB.BSONMapper]::New()&#13;\n&#13;\n$Object = @{&#13;\n  \"Name\"  = 'TestName'&#13;\n  \"Value\" = 'TestValue'&#13;\n}&#13;\n&#13;\nTry {&#13;\n  # Attempt to insert the object as a new collection entry.&#13;\n  $Collection.Insert($BSONMapper.ToDocument($Object))&#13;\n} Catch {&#13;\n  Throw \"Unable to insert item.\"&#13;\n}&#13;\n<\/code><\/pre>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Querying_Records_in_LiteDB\"><\/span>Querying Records in LiteDB<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>To query an object in LiteDB, we can use several different methods such as:<\/p>\n<ul>\n<li><code>FindAll()<\/code> \u2013 Return all documents in a collection.<\/li>\n<li><code>FindOne()<\/code> \u2013 Returns <code>FirstOrDefault<\/code> of a <code>Find()<\/code> query.<\/li>\n<li><code>FindById()<\/code> \u2013 Returns <code>SingleOrDefault<\/code> result of <code>Find()<\/code> by using the primary key of <code>_id<\/code> index.<\/li>\n<li><code>Find()<\/code> \u2013 Return all documents using the defined expression.<\/li>\n<\/ul>\n<p>In this example, let\u2019s query all the documents and then just the one that we are looking for. We can also test if the document exists, using the <code>Exists()<\/code> method. To demonstrate this, we will first verify that the document exists, then locate the first document with the name <code>TestName<\/code> and finally locate all documents. To demonstrate the last method, we have added an additional document of the same name but a different value.<\/p>\n<pre><code class=\"language-bash\"># Test if the `TestName` document exists&#13;\n$Collection.Exists(\"`$.Name=\"TestName\"\")&#13;\n# Return the first `TestName` document found&#13;\n$Collection.FindOne(\"`$.Name=\"TestName\"\")&#13;\n# Display all documents in a collection&#13;\n$Collection.FindAll()&#13;\n<\/code><\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-8208 aligncenter\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/87ff002a906e73f6d13d7a0f23461e11\/p\/uploads\/2020\/11\/0b76bfae.png\" alt=\"\" width=\"1097\" height=\"504\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Verify that the document exists, located the specific document, and then all documents.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Updating_and_Removing_a_Document\"><\/span>Updating and Removing a Document<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Now that we have created a document, let\u2019s update the value. This is done using the aptly named <code>Update()<\/code> method.<\/p>\n<pre><code class=\"language-powershell\">$Item = $Collection.FindOne(\"`$.Name=\"TestName\"\")&#13;\n&#13;\n$Item['Value'] = 'UpdatedValue'&#13;\n&#13;\nTry {&#13;\n  # Attempt to update the existing document with the updated value&#13;\n  $Collection.Update($Item)&#13;\n} Catch {&#13;\n  Throw \"Unable to update item.\"&#13;\n}&#13;\n<\/code><\/pre>\n<p>Of course, we may not want to keep this document. Therefore, we can remove the document using the <code>Remove()<\/code> method. This requires us to know the ID of the document. Since we already have the information in the <code>$Item<\/code> variable, we can leverage the <code>_id<\/code> property to remove the document.<\/p>\n<pre><code class=\"language-powershell\">Try {&#13;\n    # Remove the entry using the _id attribute, internal to the LiteDB database&#13;\n    $Collection.Delete($Item['_id'].RawValue)&#13;\n} Catch {&#13;\n    Throw \"Unable to delete item.\"&#13;\n}&#13;\n<\/code><\/pre>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Cleaning_up_the_Database_and_Next_Steps\"><\/span>Cleaning up the Database and Next Steps<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Since the database is locked when in use, we need to call the <code>Dispose()<\/code> method to remove the lock. This is an important step, otherwise, we may end up with corruption.<\/p>\n<pre><code class=\"language-bash\">$Database.Dispose()&#13;\n<\/code><\/pre>\n<p>With that, we have demonstrated end-to-end examples of creating a database, creating and updating documents, and removing those documents. There are many possible uses for LiteDB, such as a temporary data collection database on a server, to a fast and portable document storage system that can be easily backed up. Explore LiteDB and see what you can do with it today!\n<\/p><\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong>\n<\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener noreferrer\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/8207\/using-litedb-in-powershell-7\/\" target=\"_blank\" rel=\"noopener noreferrer\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#Using LiteDB in PowerShell 7 \u2013 CloudSavvy IT&#8221; LiteDB is a .NET native NoSQL embedded database. Built-in .NET, LiteDB is easily accessible to PowerShell and works wonderfully as a local and flexible database. Built-in encryption, SQL-like commands, and ACID-compliant with full transaction support LiteDB is simple and easy to use. In this article, we will&#8230;<\/p>\n","protected":false},"author":1,"featured_media":121619,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2020\/03\/23e4a5a4.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-121618","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/121618","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=121618"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/121618\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/121619"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=121618"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=121618"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=121618"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}