If you have a PowerShell script running/scheduled in your environment, there are settings that may require editing from time to time, most commonly SMTP settings. If you prefer not to have people edit these settings and mess around with the code within the Script, then you can utilize the "ConvertFrom-StringData" cmd which converts string data into a hash table.
For those who do not know what hash table is,
A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key\/value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses are the keys and the computer names are the values, or vice versa.
An example method of how a hash table can be created is shown below.
Example: Student Information saved in a Hash Table
Further, we can fetch specific details from the hash table by calling the Name key.
$Student.Name would return "Sunil Chauhan" for example.
Now let's say we are building a script below where SMTP settings will be required to be changed based on the environment. We have saved these settings in a text file parameter and value delimited with "=". As all the settings that may require modification are stored in a "Settings.txt" file, it will be a simple matter to edit any required settings.
To=Sunil.email@example.com From=Sender@domain.com SmtpServer=MySmtpServer.com Port=587
Next, if we fetch the contents of this text file in a PowerShell array, we will have data in string format as shown in the picture below.
As this data is currently in string format, fetching any particular details from the file would require us to do more complex string manipulation, editing, and splitting etc.
To make things simple, convert the string data that was saved in the "Settings.txt" file into a hash table.
So to convert the string data saved in $TextData array as shown in the previous step (Picture above) use the ConvertFrom-StringData cmd.
$settings = $TextData | ConvertFrom-StringData
Now that StringData has been successfully converted to a hash table, this can further be used by simply calling the Key Name to get the required values.
For instance, $Settings.to will return the Email address stored in "TO" field and $Settings.SmtpServer will return the SMTP server value and so on.
Example: Sending emails using the settings from Hash Table.
Send-MailMessage -To $settings.To -From $settings.from -SmtpServer $settings.SmtpServer -Port $settings.Port
In this post I have demonstrated how settings can be saved in a text file to manage them easily and then converting the StringData from the text file into a hash table. I hope this post was informative, please feel free to leave your feedback.
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.