Quite often PowerPacks need to store some configuration/user preferences: like domain name, of virtual machine host, or SharePoint server being managed. I had a few folks asking me how I do it in my packs so I wanted to share the code samples I use. Basically, what I do boils down to:
- Keeping all configuration parameters in one dictionary structure (
$parameters
in the code sample below), and - Saving this parameters data structure as an xml file into PowerGUI’s user profile folder.
The code below is quite straight-forward and self explanatory so hopefully it will help you get started:
# Assign unique folder and config names # This would sore data in: # C:\Users\username\AppData\Roaming\Quest Software\PowerGUI\MyAddOn.Config.xml # or in Pro version: # C:\Users\username\AppData\Roaming\Quest Software\PowerGUI Pro\MyAddOn.Config.xml # For PowerGUI, it makes sense to store data in PowerGUI config folder # For non-PowerGUI solutions, you would probably create a subfolder in # $env:appdata $FolderName = $Host.PrivateData.UserAppData $ConfigName = "MyAddOn.Config.xml" # keep all add-on parameters in a map $parameters = @{} # read parameters if ( Test-Path -Path "$FolderName\$ConfigName") { $parameters = Import-Clixml -Path "$FolderName\$ConfigName" # now you can use them, e.g. "Hello, " + $parameters['User name'] "Isn't your birthday on " + $parameters['Birthday'] + "?" } else { # Your add-on specific code, to get user preferences $parameters['User name'] = Read-Host "I don't know you yet. What's your name?" $parameters['Birthday'] = Read-Host "And your birthday is?.." } # store parameters $parameters | Export-Clixml -Path "$FolderName\$ConfigName"
Depending on your add-on/powerpack, you might tweek it a little to have some of the variables declared as global (e.g. $global:parameters
) and maybe wrapped some code into functions. Leave your comments or ask questions at the forums at PowerGUI.org if you need any help.
[UPDATE] Tweaked the script based on Oleg’s tip on locating PowerGUI configuration folder.
[UPDATE 2] Updated the text and the script based on Harley’s feedback.