0

我试图找出哪些网站正在运行应用程序池。MicrosoftIISv2/WebServerSetting仅提供 AppPoolId 属性,所有值均为DefaultAppPool。我可以看到所有这些应用程序池都在 IIS 上运行不同的网站。如何通过 WMI 让网站在应用程序池上运行?

4

1 回答 1

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); 
    }
于 2011-09-25T18:51:21.763 回答