You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取IIS虚拟目录的完整虚拟路径?

如何获取IIS应用的完整虚拟路径(而非相对路径)

你遇到的问题是因为VirtualDirectory.Path的设计本身就是相对于所属应用的相对路径,每个应用的根虚拟目录默认就是"/"——这和IIS管理器里显示的完整路径不是一回事,完整路径其实是应用本身的Path属性加上虚拟目录的相对路径。

解决方法

要得到完整虚拟路径,只需要把应用的Path和虚拟目录的Path拼接起来即可。对于应用的根虚拟目录,拼接后的结果就是你预期的完整路径。

修改你原有的代码,调整输出部分:

#! python3

import clr
import os
webAdmin = "system32\inetsrv\Microsoft.Web.Administration.dll"
clr.AddReference(os.path.join(os.environ["SystemRoot"], webAdmin))
from Microsoft.Web.Administration import ServerManager

def main():
    manager = ServerManager.OpenRemote("localhost")
    site = manager.Sites["Default Web Site"]
    poolName = "test-app-pool"
    manager.ApplicationPools.Add(poolName)
    newApp = site.Applications.Add("/another-test", "C:\\some\\path")
    newApp.ApplicationPoolName = poolName
    manager.CommitChanges()

    # 拼接应用路径和虚拟目录相对路径,去除末尾多余斜杠
    full_virtual_path = f"{newApp.Path}{newApp.VirtualDirectories[0].Path}".rstrip("/")
    print(full_virtual_path)
    # 输出: /another-test

if __name__ == "__main__":
    main()

遍历所有应用和虚拟目录的场景

如果需要批量获取站点下所有应用及虚拟目录的完整路径,可以用以下代码:

def get_all_full_virtual_paths():
    manager = ServerManager.OpenRemote("localhost")
    for site in manager.Sites:
        print(f"站点: {site.Name}")
        for app in site.Applications:
            for vdir in app.VirtualDirectories:
                # 拼接并去除末尾多余的斜杠
                full_path = f"{app.Path}{vdir.Path}".rstrip("/")
                print(f"  完整虚拟路径: {full_path} | 物理路径: {vdir.PhysicalPath}")

get_all_full_virtual_paths()

补充说明

  • 每个IIS应用(Application)都会默认创建一个根虚拟目录,这个根目录的Path固定为"/",它的完整路径就是应用的Path。
  • 如果应用下还有子虚拟目录(比如给应用/app1添加了子虚拟目录/subdir),那子虚拟目录的Path是"/subdir",拼接后就是/app1/subdir,和IIS管理器里显示的一致。

内容的提问来源于stack exchange,提问作者jabbequbs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:12:30