{"id":13982,"date":"2018-03-22T06:00:45","date_gmt":"2018-03-22T13:00:45","guid":{"rendered":"https:\/\/www.sapien.com\/blog\/?p=13982"},"modified":"2018-05-23T14:31:10","modified_gmt":"2018-05-23T21:31:10","slug":"storing-powershell-variables-in-external-files","status":"publish","type":"post","link":"https:\/\/dev.sapien.com\/blog\/2018\/03\/22\/storing-powershell-variables-in-external-files\/","title":{"rendered":"Storing PowerShell Variables in External files"},"content":{"rendered":"<p>On our PowerShell community forums, we have recently received questions asking if it is possible to store PowerShell variables in external files, and if so, how is it done. It is indeed possible to store variables in external files for PowerShell to use. These external variables can be stored in a variety of file types. Storing them in a PowerShell file is one of the easiest because you can just dot source these files.<\/p>\n<p>We will cover the following methods to store variables:<\/p>\n<blockquote>\n<ul style=\"list-style-type: disc;\">\n<li><strong>Script Files<\/strong><\/li>\n<li><strong>Text Files<\/strong><\/li>\n<li><strong>JSON Files<\/strong><\/li>\n<li><strong>XML Files<\/strong><\/li>\n<\/ul>\n<\/blockquote>\n<p>The examples shown in this post are pretty simple, but that doesn\u2019t mean that it isn&#8217;t possible to store fairly complex variables in external files. If you want to\u00a0experiment with storing external variables you can download the sample files for this post\u00a0<a href=\"https:\/\/sapien.s3.amazonaws.com\/Blog_Post_Files\/ExternalVariablesExamples.zip\" target=\"_blank\" rel=\"noopener\">here<\/a>.<\/p>\n<p><span style=\"font-size: x-large;\"><strong>Script Files<\/strong><\/span><\/p>\n<p>Dot sourcing may be the easiest way to store external variables\u2014but it isn&#8217;t always the safest. When a file is dot sourced we are telling PowerShell to execute that script. If there is any malicious code in the file, then that code will also run.<\/p>\n<p>In addtion to dot sourcing, you will also need to ensure that the external variables PowerShell script is signed and that\u00a0<a href=\"https:\/\/www.sapien.com\/blog\/2013\/05\/16\/but-it-works-on-my-machine\/\" target=\"_blank\" rel=\"noopener\">Remote Execution<\/a> is enabled on your machine.<\/p>\n<p>Dot sourcing can be helpful if we need to get information about something dynamically. For the other options discussed in this post, the data stored in the file types will have to be manually changed.<\/p>\n<div class=\"wp_syntax\" style=\"width: auto; position: relative;\">\n<table>\n<tbody>\n<tr>\n<td class=\"line_numbers\">\n<pre>1\r\n2\r\n3\r\n4<\/pre>\n<\/td>\n<td class=\"code\">\n<pre lang=\"powershell\"># Here we dot source the External variables PowerShell File\r\n. \"C:\\Test\\BlogPosts\\ExternalVariables.ps1\"\r\n\r\nWrite-Host $External_Variable1 $External_Variable2<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"theCode\" style=\"display: none;\">\n<\/div>\n<p>Here is what is in the ExternalVariables.ps1 file:<\/p>\n<blockquote><p>#Declaration of External variables<br \/>\n$External_Variable1 = &#8216;Sapien&#8217;<br \/>\n$External_Variable2 = &#8216;Technologies&#8217;<\/p><\/blockquote>\n<p><span style=\"font-size: x-large;\"><strong>Text Files<\/strong><\/span><\/p>\n<p>External variables can also be stored in a number of text files and formats, such as plain text in a general .txt file using the <em><b>Get-Content <\/b><\/em>cmdlet. When we import variables this way, we aren\u2019t running any code, so it\u2019s not a problem if you don\u2019t constantly monitor the files to get information.<\/p>\n<p>The following three pictures are examples of different ways of storing information in a simple text file:<\/p>\n<div class=\"wp_syntax\" style=\"width: auto; position: relative;\">\n<table>\n<tbody>\n<tr>\n<td class=\"line_numbers\">\n<pre>1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13<\/pre>\n<\/td>\n<td class=\"code\">\n<pre lang=\"powershell\">$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path\r\n$ScriptDir += \"\\ExternalVariables.txt\"\r\n\r\n# Use get content to get all of the lines that are in the txt files\r\n\r\n$External_Variables = Get-Content -Path $ScriptDir\r\n\r\n#The Information from the ExternalVariables comes in as an array \r\n#So to print all of the strings in $program we use a foreach loop\r\nforeach ($string in $External_Variables)\r\n{\r\n\tWrite-Host $string\t\r\n}<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"theCode\" style=\"display: none;\">\n<\/div>\n<p>Here is what is in the ExternalVariables.txt file:<\/p>\n<blockquote><p>&#8220;PowerShell Studio&#8221;<br \/>\n&#8220;PrimalScript&#8221;<br \/>\n&#8220;Version Recall&#8221;<\/p><\/blockquote>\n<p>Just like an array, we can store hash tables in text files. To get our hash table from a text file, we will have to pipe the output of the <em><b>Get-Content<\/b><\/em> to the <em><b>ConvertFrom-StringData<\/b><\/em>\u00a0cmdlet to convert the output into a hash table.<\/p>\n<div class=\"wp_syntax\" style=\"width: auto; position: relative;\">\n<table>\n<tbody>\n<tr>\n<td class=\"line_numbers\">\n<pre>1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14<\/pre>\n<\/td>\n<td class=\"code\">\n<pre lang=\"powershell\">$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path\r\n$ScriptDir += \"\\ExternalVariablesHashTable.txt\"\r\n# Getting the contents of the External Variable text file\r\n# This file is store in plan text and is not in any special format\r\n\r\n# We use the \"raw\" parameter here in Get-Content so that when we get the contents\r\n# of the file so that our hashtable is not converted to an object\r\n$program = Get-Content -raw -Path $ScriptDir | ConvertFrom-StringData\r\n\r\nwrite-host \"`nType of the variable `$program`n\"\r\n$program.GetType()\r\n\r\nwrite-host \"`nPrinting `$program\" \r\n$program<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"theCode\" style=\"display: none;\">\n<\/div>\n<p>Here is what is in ExternalVariablesHashTable.txt:<\/p>\n<blockquote><p>Company=Sapien Technologies<br \/>\nProduct=PowerShell Studio<\/p><\/blockquote>\n<p><span style=\"font-size: x-large;\"><span style=\"font-size: medium;\">Storing information in a text file like this is a convenient way to keep information in a human-readable format. Text files also come with the benefit of not being executable, so if there happens to be malicious code stored in a file you don\u2019t regularly manage it won&#8217;t be executed.<\/span><\/span><span style=\"font-size: x-large;\"><span style=\"font-size: medium;\"><br \/>\n<\/span><\/span><\/p>\n<p><span style=\"font-size: x-large;\"><strong>JSON File<\/strong><\/span><\/p>\n<p>It is also possible to store external variables in a JSON format. The only caveat being that we will need to once again pipe the output of <strong><em>Get-Content<\/em><\/strong> to another cmdlet; however this time it\u2019s <strong><em>ConvertFrom-Json<\/em><\/strong> rather than <strong><em>ConvertFrom-StringData<\/em><\/strong>. For those unfamiliar with JSON or need to brush up on the format, please visit <a href=\"http:\/\/www.json.org\" target=\"_blank\" rel=\"noopener\">www.JSON.org<\/a>.<\/p>\n<div class=\"wp_syntax\" style=\"width: auto; position: relative;\">\n<table>\n<tbody>\n<tr>\n<td class=\"line_numbers\">\n<pre>1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17<\/pre>\n<\/td>\n<td class=\"code\">\n<pre lang=\"powershell\">$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path\r\n$ScriptDir += \"\\jsonfile.json\"\r\n#Getting information from the json file\r\n#The we pass the output from Get-Content to ConvertFrom-Json Cmdlet\r\n$JsonObject = Get-Content $ScriptDir | ConvertFrom-Json\r\n\r\n#Right now we have an array which means that we have to index\r\n#an element to use it\r\n$JsonObject.Users[0]\r\n\r\n#When indexed we can call the attributes of the elements\r\nWrite-Host \"Attributes individually printed\"\r\n$JsonObject.Users[0].Name\r\n$JsonObject.Users[0].Age\r\n$JsonObject.Users[0].City\r\n$JsonObject.Users[0].Country\r\n$JsonObject.Users[0].UserId<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"theCode\" style=\"display: none;\">\n<\/div>\n<p>Here is what is in the JSON File:<\/p>\n<blockquote><p>{<br \/>\n&#8220;Users&#8221;: [{<br \/>\nName:&#8221;John Smith&#8221;,<br \/>\nAge:&#8221;35&#8243;,<br \/>\nCity:&#8221;San Francisco&#8221;,<br \/>\nCountry:&#8221;USA&#8221;,<br \/>\nUserId:&#8221;52917&#8243;<br \/>\n},<br \/>\n{<br \/>\nName:&#8221;Jane Wellington&#8221;,<br \/>\nAge:&#8221;28&#8243;,<br \/>\nCity:&#8221;Seattle&#8221;,<br \/>\nCountry:&#8221;USA&#8221;,<br \/>\nUserId:&#8221;25589&#8243;<br \/>\n},<br \/>\n{<br \/>\nName:&#8221;Samantha Scott&#8221;,<br \/>\nAge:&#8221;33&#8243;,<br \/>\nCity:&#8221;Los Angeles&#8221;,<br \/>\nCountry:&#8221;USA&#8221;,<br \/>\nUserId:&#8221;11564&#8243;<br \/>\n}<br \/>\n]<br \/>\n}<\/p><\/blockquote>\n<p><span style=\"font-size: x-large;\"><strong>XML File<\/strong><\/span><\/p>\n<p>If we store our variables in an XML format, we can add comments to the variable file if necessary. The only two file formats that we will talk about in this post that allows for comments are XML or PS1. JSON and normal TXT files do not allow for comments. For a concise overview of the XML format, visit <a href=\"https:\/\/www.w3schools.com\/xml\/\" target=\"_blank\" rel=\"noopener\">w3schools.com\/xml<\/a>.<\/p>\n<div class=\"wp_syntax\" style=\"width: auto; position: relative;\">\n<table>\n<tbody>\n<tr>\n<td class=\"line_numbers\">\n<pre>1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9<\/pre>\n<\/td>\n<td class=\"code\">\n<pre lang=\"powershell\">$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path\r\n$ScriptDir += \"\\XMLFile.xml\"\r\n#Read in all of the information from our variables XML file\r\n#We will need to cast the variable as [XML] when we store all of the file information in it\r\n\r\n[xml]$XML_Variable = Get-Content -Path $ScriptDir\r\n\r\n#Referencing the Food Object array stored within the Breakfast Object\r\n$XML_Variable.Breakfast_menu.Food[0] | Format-List<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"theCode\" style=\"display: none;\">\n<\/div>\n<p>Here is what is in the XML file:<\/p>\n<blockquote><p><code><!--?xml version=\"1.0\" encoding=\"UTF-8\"?--><br \/>\nBelgian Waffles<br \/>\n$5.95<br \/>\nTwo of our famous Belgian Waffles with plenty of real maple syrup<br \/>\n650<br \/>\n<!--Your Comment Here--><br \/>\nStrawberry Belgian Waffles<br \/>\n$7.95<br \/>\nLight Belgian waffles covered with strawberries and whipped cream<br \/>\n900<\/code><\/p>\n<p>Berry-Berry Belgian Waffles<br \/>\n$8.95<br \/>\nBelgian waffles covered with assorted fresh berries and whipped cream<br \/>\n900<\/p><\/blockquote>\n<p>When choosing between XML and JSON storage formats, it comes down to which one is more familiar. Since the main difference between them is that XML allows comments, it is just a matter of preference. All of these options are viable ways to store information in external files to either be read by another program or used by the same program at a later time. How complex, whether it is dynamic or not, and how much information needs to be stored will dictate the format to use.<\/p>\n<p><span style=\"font-size: x-large;\"><strong>Exporting to Files<\/strong><\/span><\/p>\n<p>Just like importing information with PowerShell, it is also possible to export information and objects to an external file from the program we are using. PowerShell Studio 2018 comes with <em><strong>snippets<\/strong><\/em> that make exporting information much easier\u2014simply pass the path of the external file and the object to the corresponding export function and the <em><strong>snippet<\/strong><\/em> will take care of everything else. We will cover <em>Exporting to Files using Snippets<\/em> in a future blog post.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>On our PowerShell community forums, we have recently received questions asking if it is possible to store PowerShell variables in external files, and if so, how is it done. It is indeed possible to store variables in external files for PowerShell to use. These external variables can be stored in a variety of file types. [&hellip;]<\/p>\n","protected":false},"author":45,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[932,2,283,1143,25],"tags":[354,28,57,80,237],"class_list":["post-13982","post","type-post","status-publish","format-standard","hentry","category-beginners","category-general","category-howto","category-powershell","category-windows-powershell","tag-external","tag-powershell","tag-scripting","tag-scripts","tag-variables"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/posts\/13982","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/users\/45"}],"replies":[{"embeddable":true,"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/comments?post=13982"}],"version-history":[{"count":116,"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/posts\/13982\/revisions"}],"predecessor-version":[{"id":15026,"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/posts\/13982\/revisions\/15026"}],"wp:attachment":[{"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/media?parent=13982"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/categories?post=13982"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dev.sapien.com\/blog\/wp-json\/wp\/v2\/tags?post=13982"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}