Get dbname from multiple web.config files with powershell

时光总嘲笑我的痴心妄想 提交于 2019-12-22 06:29:16

问题


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!


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7053595/get-dbname-from-multiple-web-config-files-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!