If you write code that you publish in a public repository on a site such as GitHub, a combination of config files and your .gitignore
file can be very useful for keeping things secure and preventing you from accidentally publishing usernames, passwords, etc. for all to see.
I've been writing scripts primarily in PowerShell these days and I wasn't sure of a good way to create and use config files. Various website suggest using XML for this, but I'm a fan of using JSON whenever possible (it seems way more natural to me). This is a solution I've found that works well for me.
Caveats
- You need PowerShell 3.0 or later (included in Windows Management Framework 3.0)
Make your config file
You can structure this pretty much however you want/need. Just make sure it is in standard JSON format and you should be fine.
{
"mail": {
"server": "smtp.gmail.com",
"port": "587",
"username": "user1",
"password": "Passw0rd!"
},
"settings": {
"setting1": 25,
"setting2": "Joe"
}
}
Loading the JSON into PowerShell
Use the Get-Content
cmdlet and pipe it into the ConvertFrom-Json
cmdlet, like this:
$config=Get-Content -Path .\config.json -Raw | ConvertFrom-Json
Once loaded, you can access the info just like a standard PSObject. So continuing on with the example code above, accessing the port
property would look like this:
$config.mail.port
That's pretty much it.