简体   繁体   中英

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!

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 " "
}

This post may give you an idea to start with. Basically load in the web.config file as an XML file and then just find the node where the connection string is.

Do something like $myFile = ([xml] Get-Content web.config). You can then pipe that to Get-Member ( $myFile | Get-Member -MemberType Property) to start working your way into the file to see what node has it. I'm not at a computer where I can show you some screenshots to explain it more, but you can check this chapter out from PowerShell.com "Master PowerShell" e-book that explains working with XML very well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM