我试图找出哪些网站正在运行应用程序池。 MicrosoftIISv2/WebServerSetting
仅提供AppPoolId属性,所有valuse都是 DefaultAppPool 。我可以看到所有这些应用程序池在IIS上运行不同的网站。如何让WMI在应用程序池上运行网站?
答案 0 :(得分:1)
我发现可以使用EnumAppsInPool
方法完成。这是代码:
public static IEnumerable<string> GetWebSitesRunningOnApplicationPool(ManagementScope scope, string applicationPoolName)
{
//get application names from application pool
string path = string.Format("IIsApplicationPool.Name='W3SVC/APPPOOLS/{0}'", applicationPoolName);
ManagementPath managementPath = new ManagementPath(path);
ManagementObject classInstance = new ManagementObject(scope, managementPath, null);
ManagementBaseObject outParams = classInstance.InvokeMethod("EnumAppsInPool", null, null);
//get web server names from application names
IEnumerable<string> nameList = (outParams.Properties["Applications"].Value as string[]) //no null reference exception even there is no application running
.Where(item => !String.IsNullOrEmpty(item)) //but you get empty strings so they are filtered
.ToList() //you get something like /LM/W3SVC/1/ROOT
.Select(item => item.Slice(item.NthIndexOf("/", 2) + 1, item.NthIndexOf("/", 4))); //your WebServer.Name is between 2nd and 4th slahes
//get server comments from names
List<string> serverCommentList = new List<string>();
foreach (string name in nameList)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, new ObjectQuery(string.Format("SELECT ServerComment FROM IIsWebServerSetting WHERE Name = '{0}'", name)));
serverCommentList.AddRange(from ManagementObject queryObj in searcher.Get() select queryObj["ServerComment"].ToString());
}
return serverCommentList;
}
public static int NthIndexOf(this string target, string value, int n)
{
int result = -1;
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");
if (m.Success)
{
result = m.Groups[2].Captures[n - 1].Index;
}
return result;
}
public static string Slice(this string source, int start, int end)
{
if (end < 0)
{
end = source.Length + end;
}
int len = end - start;
return source.Substring(start, len);
}