我如何得到在WMI当前应用程序池中运行的网站

本文关键字:程序池 应用程序 运行 网站 应用 何得 WMI | 更新日期: 2023-09-27 18:09:39

我想找出哪些网站正在运行一个应用程序池。MicrosoftIISv2/WebServerSetting只提供AppPoolId属性,所有的值都是DefaultAppPool。我可以看到所有这些应用程序池都在IIS上运行不同的网站。如何通过WMI使网站在应用程序池上运行?

我如何得到在WMI当前应用程序池中运行的网站

我发现它可以用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); 
    }
相关文章: