{"id":63283,"date":"2008-01-15T21:51:00","date_gmt":"2008-01-15T21:51:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2008\/01\/15\/hey-scripting-guy-how-can-i-add-a-record-to-a-database-using-windows-powershell\/"},"modified":"2008-01-15T21:51:00","modified_gmt":"2008-01-15T21:51:00","slug":"hey-scripting-guy-how-can-i-add-a-record-to-a-database-using-windows-powershell","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-add-a-record-to-a-database-using-windows-powershell\/","title":{"rendered":"Hey, Scripting Guy! How Can I Add a Record to a Database Using Windows PowerShell?"},"content":{"rendered":"<p><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" height=\"34\" alt=\"Hey, Scripting Guy! Question\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\" \/> <\/p>\n<p>Hey, Scripting Guy! <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/oct06\/hey1002.mspx\"><b>Awhile back<\/b><\/a> you showed us how we could use Windows PowerShell to retrieve data from a Microsoft Access database. I\u2019m now trying to <i>add<\/i> data to a database using PowerShell, but I can\u2019t get the script to work. Any chance you could show me how to add a record to a database using Windows PowerShell?<\/p>\n<p>&#8212; AB<\/p>\n<p><img decoding=\"async\" height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\" \/><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" height=\"34\" alt=\"Hey, Scripting Guy! Answer\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\" \/><a href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><img decoding=\"async\" class=\"farGraphic\" title=\"Script Center\" height=\"288\" alt=\"Script Center\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" align=\"right\" border=\"0\" \/><\/a> <\/p>\n<p>Hey, AB. Before we start we\u2019d like to show everyone the nice little note we received last Friday (January 11<sup>th<\/sup>) from Joel Thoreson:<\/p>\n<p>\u201cJust wanted to wish you all a Happy Scripting Guy\u2019s day this fine 11<sup>th<\/sup> of January!\u201d<\/p>\n<p>Thanks, Joel. Needless to say, we truly appreciate the fact that <i>someone<\/i> remembered that January 11<sup>th<\/sup> was Scripting Guys Day; even the Scripting <i>Mothers<\/i> failed to call and wish us a happy Scripting Guys Day. Did that hurt our feelings? You bet it did. And still does.<\/p>\n<p>Now, we realize that some of you are thinking, \u201cWhat are they talking about? Scripting Guys Day? No way. Scripting Guys Day is <i>not<\/i> January 11<sup>th<\/sup>.\u201d As it turns out, though, Scripting Guys Day <i>is<\/i> January 11<sup>th<\/sup>; after all, take a look at this note from our <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/dec05\/hey1220.mspx\"><b>December 20, 2005<\/b><\/a> column:<\/p>\n<table class=\"dataTable\" id=\"EME\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td class=\"\">\n<p><b>Interesting historical fact<\/b>. National Grandparents Day falls each year on the first Sunday after Labor Day. This holiday was started by a married couple that had 40 grandchildren. The Scripting Guys fully support the idea of a Grandparents Day; after all, who could be more deserving? Still, we find it interesting that Grandparents Day was started by a couple who would then be eligible to receive 40 additional gifts each and every year.<\/p>\n<p>Say, did we mention that January 11th is Scripting Guys Day\u2026?<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Hey, if it\u2019s in <i>Hey, Scripting Guy!<\/i> then it <i>must<\/i> be true. Case closed.<\/p>\n<p>Anyway, thanks again, Joel; a Happy Scripting Guys Day to you, too. As for the rest of you, well, don\u2019t feel guilty; after all, there\u2019s still plenty of time to send your favorite Scripting Guy a present. Just send the package to:<\/p>\n<p>The Scripting Guy Who Writes That Column<br \/>Microsoft Corporation<br \/>One Microsoft Way<br \/>Building 42\/4039<br \/>Redmond, WA 99352<\/p>\n<p>Remember what they say: better late than never.<\/p>\n<table class=\"dataTable\" id=\"EMF\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td class=\"\">\n<p class=\"lastInCell\"><b>Note<\/b>. What\u2019s that? Aren\u2019t there other Scripting Guys besides the Scripting Guy who writes this column? Sure. But we said that there was still plenty of time to send your <i>favorite<\/i> Scripting Guy a present. That pretty much rules out all the other Scripting Guys.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>In the spirit of the holidays, we thought we\u2019d take time out from our Scripting Guys Day party to show you how to add a new record to an Access database using Windows PowerShell. (Or, for that matter, how you can add a record to any other database that uses ADO [ActiveX Data Objects].) We know that many of you have grabbed a VBScript script that uses ADO and tried to convert it to a Windows PowerShell script that performs the same task. That can be done; in fact, we\u2019re just about to do it. It\u2019s just that there are a couple of \u201cgotchas\u201d that you need to watch out for.<\/p>\n<p>And yes, as a matter of fact we <i>are<\/i> going to explain what those gotchas are.<\/p>\n<p>Even to those of you who forgot that it was Scripting Guys Day.<\/p>\n<p>Here\u2019s the script:<\/p>\n<pre class=\"codeSample\">$adOpenStatic = 3\n$adLockOptimistic = 3\n\n$objConnection = New-Object -com \"ADODB.Connection\"\n$objRecordSet = New-Object -com \"ADODB.Recordset\"\n\n$objConnection.Open(\"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\\Scripts\\Test.mdb\")\n\n$objRecordset.Open(\"Select * From Computers\", $objConnection,$adOpenStatic,$adLockOptimistic)\n\n$objRecordSet.AddNew()\n$objRecordSet.Fields.Item(\"ComputerName\").Value = \"atl-ws-001\"\n$objRecordSet.Fields.Item(\"SerialNumber\").Value = \"192ATG43R\"\n$objRecordSet.Update()\n\n$objRecordSet.Close()\n$objConnection.Close()\n<\/pre>\n<p>So how does this script work? Well, let\u2019s see what we have here. To begin with, we assign values to a pair of variables $adOpenStatic and $adLockOptimistic:<\/p>\n<pre class=\"codeSample\">$adOpenStatic = 3\n$adLockOptimistic = 3\n<\/pre>\n<p>We won\u2019t talk about these variables in any detail today; suffice to say that they help determine the type of cursor and the type of record locking employed when we open our database table. (If you\u2019d like a little more information than that, take a peek at the Scripting Guys webcast <a href=\"http:\/\/go.microsoft.com\/fwlink\/?LinkId=22089\" target=\"_blank\"><b>Database Scripting For System Administrators<\/b><\/a>.) After initializing our two variables, we then create instances of the <b>ADODB.Connection<\/b> and <b>ADODB.Recordset<\/b> objects:<\/p>\n<pre class=\"codeSample\">$objConnection = New-Object -com \"ADODB.Connection\"\n$objRecordSet = New-Object -com \"ADODB.Recordset\"\n<\/pre>\n<p>In case you\u2019re wondering, the Connection object is used to manage the connection to the actual database file (in this case, C:\\Scripts\\Test.mdb). After we\u2019ve made the connection the Recordset object is then used to help us work with a specified set of records in that database; for today\u2019s script, that\u2019s going to be all the records found in a table named Computers.<\/p>\n<p>Once we have these two objects in hand we can then use this line of code to connect to Test.mdb:<\/p>\n<pre class=\"codeSample\">$objConnection.Open(\"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\\Scripts\\Test.mdb\")\n<\/pre>\n<p>Actually, we need to clarify that a little. The preceding command connects us to Test.mdb provided that Test.mdb is an Access 2003 (or Access XP) database. If Test.mdb happens to be an Access 2007 database, well, that command isn\u2019t going to help us much; that\u2019s because Access 2007 uses a different Provider string and a different file extension. Working with an Access 2007 database? Then use this line of code instead:<\/p>\n<pre class=\"codeSample\">$objConnection.Open(\"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\Scripts\\Test.accdb\")\n<\/pre>\n<p>And no, we don\u2019t know why they changed the Provider string and the file extension. For some reason the Office team simply makes major changes like these without ever asking the Scripting Guys for their opinion. <\/p>\n<p>Go figure.<\/p>\n<table class=\"dataTable\" id=\"E2G\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td class=\"\">\n<p><b>Note<\/b>. You might have noticed that all the information passed to the <b>Open<\/b> method was enclosed in parentheses. This is one spot where people get fouled up when trying to convert a VBScript script to Windows PowerShell. In Windows PowerShell, all methods \u2013 including the Open method \u2013 must be followed by a set of parentheses, and all the method parameters must be enclosed in those parentheses. If you put the Provider information in parentheses in VBScript your script will fail; however, if you <i>don\u2019t<\/i> put the Provider information in parentheses in Windows PowerShell your script will fail.<\/p>\n<p>Go figure.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>After we make the connection to the database we then use the following line of code to return a recordset consisting of all the data found in the Computers table:<\/p>\n<pre class=\"codeSample\">$objRecordset.Open(\"Select * From Computers\", $objConnection,$adOpenStatic,$adLockOptimistic)\n<\/pre>\n<p>Believe it or not, we\u2019re now ready to add a record to our database; in fact, that\u2019s what this block of code is for:<\/p>\n<pre class=\"codeSample\">$objRecordSet.AddNew()\n$objRecordSet.Fields.Item(\"ComputerName\").Value = \"atl-ws-001\"\n$objRecordSet.Fields.Item(\"SerialNumber\").Value = \"192ATG43R\"\n$objRecordSet.Update()\n<\/pre>\n<p>What\u2019s going on here? Well, for starters, we use the <b>AddNew<\/b> method to create a new, blank record. (Again, note the parentheses that follow the method name.) That brings us to this line of code:<\/p>\n<pre class=\"codeSample\">$objRecordSet.Fields.Item(\"ComputerName\").Value = \"atl-ws-001\"\n<\/pre>\n<p>We\u2019re willing to bet, AB, that this is the line that\u2019s been causing you the most trouble. In this line of code we\u2019re assigning a value (<i>atl-ws-001<\/i>) to the ComputerName field. This isn\u2019t a particularly troublesome line of code unless you\u2019re trying to port a VBScript script. That\u2019s because, in VBScript, this same line of code looks like this:<\/p>\n<pre class=\"codeSample\">objRecordSet(\"ComputerName\") = \"atl-ws-001\"\n<\/pre>\n<p>In VBScript all we have to do is specify the object reference (objRecordset) followed by a pair of parentheses containing the name of the field (ComputerName). But remember, that\u2019s in VBScript. In Windows PowerShell that simplified command won\u2019t work; if we try something similar we merely get an error message like this one:<\/p>\n<pre class=\"codeSample\">Unexpected token '(' in expression or statement.\nAt C:\\scripts\\test.ps1:11 char:15\n+ $objRecordSet(\" &lt;&lt;&lt;&lt; ComputerName\") = \"atl-ws-001\"\n<\/pre>\n<p>To tell you the truth, we don\u2019t know exactly why this problem occurs. We do know that, unless you specify otherwise, VBScript automatically gives you the default property for any object; most other languages (including Windows PowerShell) make you explicitly spell out that property, default property or not. We\u2019re guessing that <b>Fields.Item.(<\/b><b><i>Field name<\/i><\/b><b>).Value<\/b> is the default property for our recordset; that would explain why VBScript only needs the field name while PowerShell requires the complete property name.<\/p>\n<p>Of course, like we said, that\u2019s just a guess, and there\u2019s a good chance we\u2019re completely wrong. But that\u2019s OK. After all, it doesn\u2019t matter <i>why<\/i> you have to \u201cspell out\u201d the complete property name; the only thing that matters is that you follow this same approach. With that in mind, how would we assign a value to the SerialNumber field? You got it:<\/p>\n<pre class=\"codeSample\">$objRecordSet.Fields.Item(\"SerialNumber\").Value = \"192ATG43R\"\n<\/pre>\n<p>From there, of course, we could continue to assign properties to as many fields as there are in the Computers table. Once we\u2019re done assigning properties we then call the <b>Update<\/b> method to actually write the new record to the database:<\/p>\n<pre class=\"codeSample\">$objRecordSet.Update()\n<\/pre>\n<p>After that all we have to do is close the Connection and Recordset objects, and then return to our Scripting Guys Day festivities.<\/p>\n<p>That should do the trick, AB. We hope you find this script useful, and we hope you enjoy what\u2019s left of the Scripting Guys Day holiday season. Speaking of which, we should also note that we aren\u2019t upset or disappointed that everyone except Joel forgot about Scripting Guys Day this year. That\u2019s no big deal, and there are no hard feelings on our end.<\/p>\n<table class=\"dataTable\" id=\"EXAAC\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td class=\"\">\n<p class=\"lastInCell\"><b>Note<\/b>. OK, that\u2019s not true; as it turns out, there are <i>plenty<\/i> of hard feelings on our end. But if we told the truth about that the Scripting Editor would just edit that part out. Therefore we figured that we might as well pretend that everything\u2019s peaches and cream. Even if it\u2019s not.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>In all fairness, though, we must admit that Scripting Guys Day <i>does<\/i> come at a bad time of year; after all, having a major holiday like Scripting Guys Day follow so closely on the heels of a major holiday like Christmas can be difficult. Then when you throw in the fact that January 11<sup>th<\/sup> is also the birthday of singer\/songwriter Mary J. Blige; one-time Major League shortstop Rey Ordonez; <i>and<\/i> former Canadian Prime Minister Jean Chretien, well, it\u2019s no wonder people get confused. Tell you what: go ahead and send your presents in now (even though you\u2019re a little late), and we\u2019ll see what we can do about moving Scripting Guys Day to a new date for 2009.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! Awhile back you showed us how we could use Windows PowerShell to retrieve data from a Microsoft Access database. I\u2019m now trying to add data to a database using PowerShell, but I can\u2019t get the script to work. Any chance you could show me how to add a record to a database [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[19,146,54,49,3,45],"class_list":["post-63283","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-activex-data-objects-ado","tag-databases","tag-microsoft-access","tag-office","tag-scripting-guy","tag-windows-powershell"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! Awhile back you showed us how we could use Windows PowerShell to retrieve data from a Microsoft Access database. I\u2019m now trying to add data to a database using PowerShell, but I can\u2019t get the script to work. Any chance you could show me how to add a record to a database [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/63283","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=63283"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/63283\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=63283"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=63283"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=63283"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}