Tobi123
Tobi123

Reputation: 548

Powershell - get contents from other file

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;)

Upvotes: 1

Views: 622

Answers (2)

do_Ob
do_Ob

Reputation: 719

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>[email protected]</MailFrom>
        <MailTo>[email protected]</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
    }

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 58991

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" = "[email protected]"
    "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

Upvotes: 2

Related Questions