Run web.config-dependant code in PowerShell
By Anatoly Mironov
PowerShell is a great tool. It helps in SharePoint administration and tasks automation. Today I needed to provision a webpart on many similar pages. This third-party webpart’s constructor instantiates a dataaccess service and uses a connectionstring which is stored in the web.config file. So the webpart creation failed until I found a way to load the configuration into powershell. First you can create a simple file powershell.exe.config
, put it into $pshome
(C:\Windows\System32\WindowsPowerShell\v1.0). In that file you can specify the connectionstring in the same way like in the web.config (or app.config). But it is not secure: the connectionstring can be changed in the future, and you really don’t want to copy your connectionstrings around. So there is a better way: Check out Ohad Israeli’s blog post about how a configuration file can be bound dynamically in a .net assembly: Binding to a custom App.Config file. In PowerShell you can do the same, all we need is to modify the syntax: StackOverflow: Powershell Calling .NET Assembly that uses App.config:
\[System.AppDomain\]::CurrentDomain.SetData("APP\_CONFIG\_FILE", $config\_path)
```In SharePoint the web.config file resides in:
C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config
$config_path = “C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config”
[System.AppDomain]::CurrentDomain.SetData(“APP_CONFIG_FILE”, $config_path)
```The ability to bind the configuration file dynamically can be even helpful in another part of the SharePoint world - timerjobs. The timer jobs are executed by owstimer.exe. This service has an own configuration file: {hive}\BIN\OWSTIMER.EXE.CONFIG
If the timer job configuration shares connectionstrings or appSettings with web.config, it should be theoretically possible to bind the web.config to owstimer. Leave a comment below if you find this information useful.