Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dbname from multiple web.config files with powershell

I would like to issue a powershell command to return me the connection string (specifically I am looking for the db name value) for all the web sites on a web server...

So I would like to see something like

site1 dbname=Northwind

site2 dbname=Fitch

site3 dbname=DemoDB

I have tried using the IIS Powershell snap-in... I thought I was close with this:

PS C:\Windows\system32> Get-WebApplication | Get-WebConfiguration -filter /connectionStrings/*

but... after looking at the results... my answer doesn't appear to be in there

I am very new to powershell - so excuse my ignornance and inexperience

Any help appreciated!

thanks!

like image 885
John Mc Avatar asked Aug 13 '11 22:08

John Mc


1 Answers

Hopefully, this will get you started. This just assumes there will be a web.config file at the physical path of the web application's physical path. It does not recurse to find other web.config files in the web application. It also assumes your connection strings are in the connectionStrings configuration element.

Import-Module WebAdministration

Get-WebApplication | `
ForEach-Object {

$webConfigFile = [xml](Get-Content "$($_.PhysicalPath)\Web.config")
Write-Host "Web Application: $($_.path)"
foreach($connString in $webConfigFile.configuration.connectionStrings.add)
{
  Write-Host "Connection String $($connString.name): $($connString.connectionString)"
  $dbRegex = "((Initial\sCatalog)|((Database)))\s*=(?<ic>[a-z\s0-9]+?);"
  $found = $connString.connectionString -match $dbRegex
  if ($found)
  {
   Write-Host "Database: $($Matches["ic"])"
  }

}
Write-Host " "
}
like image 157
dugas Avatar answered Nov 15 '22 06:11

dugas