1

I'm just creating a simple powershell script to check if a service is running, and if not, to send an email. (This is already working).

What I would like to do is, to have config file, where I can set some attributes like mail recipient, service name(s), and some more.

Question: Which type should I choose for my config file (is there a better way than .txt?)? The background of this question is, that I don't want to parse a txt file in my powershell script to get all these attribute values. Is there a way to declare these attributes in my config file to get and address them easily in powershell later? (Like a global variable set in the config-file and retrievable in my .ps1-file;)

Tobi123
  • 508
  • 4
  • 8
  • 25

2 Answers2

2

I would create a hashtable of your configuration and store these settings in a json file. You can convert the hashtable using this snippet:

$config = @{
    "mail" = "test@test.com"
    "service names" = @("srv1", "srv2")
}

$config | ConvertTo-Json | Out-File "c:\test.json"

And convert it back using:

$config = (gc "c:\test.json" -raw) | ConvertFrom-Json

Now you can access these values using $config.mail

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • 2
    note that *json cmdlet were introduced in PS V3. You could check this question if you want something similar for V2 http://stackoverflow.com/questions/28077854/powershell-2-0-convertfrom-json-and-convertto-json-implementation – Loïc MICHEL Jul 27 '15 at 08:43
2

I suggest using xml.

create XML file looked like this, Setting.xml

<?xml version="1.0"?>
<Settings>
    <EmailSettings>
        <SMTPServer>smtp.server.net</SMTPServer>
        <SMTPPort>25</SMTPPort>
        <MailFrom>mail@from.net</MailFrom>
        <MailTo>mail@to.net</MailTo>
    </EmailSettings>
</Settings>

then import it in your script, .ps1

[xml]$ConfigFile = Get-Content "your_path\Settings.xml"

$smtpsettings = @{
    To = $ConfigFile.Settings.EmailSettings.MailTo
    From = $ConfigFile.Settings.EmailSettings.MailFrom
    Subject = "I am a subject"
    SmtpServer = $ConfigFile.Settings.EmailSettings.SMTPServer
    }
do_Ob
  • 709
  • 1
  • 6
  • 24
  • This looks nice. Maybe the better solution for me as all our servers have still installed powershell v1.0 :( – Tobi123 Jul 27 '15 at 09:06
  • @Tobi123 this is not because powershell.exe resides in a folder nammed V1.0 that it runs powershell V1. Please use `$PSVersionTable.PSVersion.Major ` to determine the correct installed version – Loïc MICHEL Jul 27 '15 at 09:35
  • This says, a v2.0 is installed. Just trying the xml-solution. Looks good at first sight. – Tobi123 Jul 27 '15 at 09:54