Given that custom PS cmdlets are assemblies I can't provide them config information via the normal App.config route. What is the conventional way of providing config info to a custom cmdlet?
-
possible duplicate of [PowerShell App.Config](http://stackoverflow.com/questions/17960/powershell-app-config) – Howli May 11 '14 at 23:29
-
Reference this thread: http://stackoverflow.com/questions/17960/powershell-app-config – Taylor Bird Mar 11 '11 at 20:50
-
Note that PowerShell cmdlets do not have to be assembly based. You can create cmdlets in pure PowerShell. – oɔɯǝɹ Jan 09 '15 at 23:38
2 Answers
Normally i would suggest just using parameters for passing data.
Get-MyData -connectionstring $connectionString -table Test ...
When that is not practical (too many parameters, etc..), then you can always provide the path to a configuration file by a parameter:
Get-MyData -Config .\My.config
You can then read the specified configuration file from inside the cmdlet.
This allows users of the cmdlet to define their own configuration files to use.

- 7,219
- 7
- 58
- 69
PowerShell is a shell. The normal way of passing information between parts of the shell are shell variables. For powershell that would look like:
$global:MyComponent_MySetting = '12'
# i.e.
$PSDefaultParameterValues
$ErrorActionPreference
If settings is expected to be inherited across processes boundaries the convention is to use environment variables. I extend this to settings that cross C# / PowerShell boundary. A couple of examples:
$env:PATH
$env:PSModulePath
If you think this is an anti-pattern for .NET you might want to reconsider. This is the norm for PAAS hosted apps, and is going to be the new default for ASP.NET running on server-optimized CLR (ASP.NET v5).
See https://github.com/JabbR/JabbRv2/blob/dev/src/JabbR/Startup.cs#L21
Note: at time of writing I'm linking to .AddEnvironmentVariables()
I've revisited this question a few times, including asking it myself. I wanted to put a stake in the ground to say PowerShell stuff doesn't work well with <appSettings>
. IMO it is much better to embrace the shell aspect of PS over the .NET aspect in this regards.
If you need complex configuration take a JSON string. POSH v3+ has ConvertFrom-JSON built-in. If everything in your process uses the same complex configuration put it in a .json file and point to that file from an environment variable.
If a single file doesn't suffice there are well established solutions like the PATH
pattern, GIT .gitignore resolution, or ASP.NET web.config resolution (which I won't repeat here).

- 4,224
- 3
- 39
- 57