Udostępnij za pośrednictwem


PowerShell Settings file (import/export)

There are hash tables in PowerShell.

The following is a string representation of a hash table, this can be set in a text file to be loaded.

@{

Setting1="test1"

Setting2="test2"

}

When loading the file the following is used:

$settings = Get-Content -path "c:\mypath.settings.txt" -Raw | ConvertFrom-Json

This will load the object with all the properties of the hash table, then you can use it as follows:

$settings.Setting1

Once you set/update the properties you can then save the $settings hash table back to a file.

$settings | ConvertTo -Json | Set-Content "c:\mypath.settings.txt" -Encoding Unicode

NOTE: the encoding is very important, else you will never be able to manually edit the settings file.

If you need to add more properties after the fact (the file that is loaded doesn't have all the properties needed) you can add them either manually before adding, or via PowerShell.

Review the following two examples:

$settings|Add-Member-Name'New Property'-TypeNoteProperty-Value23

$settings|Add-Member-Name'something'-TypeNoteProperty-Value $false

To remove a property, it's even simpler, review the following example:

$settings.Remove("Name of property")

Setting a property is as simple as:

$settings.Setting1 = "Love Live and prosper"

The purpose of all of this is simply so that settings can be placed in a single location, a single file and multiple scripts can use it to do the task the script is designed to do.

There are many instances where you have the same settings (URL's, accounts, etc) that are used throughout various components, and it is not feasible to just put everything in one large script.