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

使用PowerShell编写正则提取tf.exe perm(TFS2008)权限块信息

用PowerShell正则提取TFS 2008 tf.exe perm输出的权限信息

嘿,我来帮你搞定这个TFS权限提取的问题!首先得先明确tf.exe perm的典型输出结构,这样正则才能精准匹配。先给你模拟一段常见的输出格式,方便理解:

Server Item: $/MyTeamProject/Source
Identity: DOMAIN\JohnDoe
Allow: Read, Write
Deny: None
Allow (Inherited): Read, Checkin
Identity: DOMAIN\JaneSmith
Allow: Read
Deny: None
Allow (Inherited): Read, Merge
Server Item: $/MyTeamProject/Tests
Identity: DOMAIN\TestGroup
Allow: Read, Run
Deny: None
Allow (Inherited): Read

接下来直接上PowerShell的实现代码,我已经帮你写好带注释的正则和处理逻辑:

# 先把tf.exe的输出读到变量里(也可以从文件读取)
# 示例:$tfPermOutput = tf.exe perm /collection:http://your-tfs-server:8080/tfs/YourCollection $/YourPath | Out-String

# 定义正则表达式,匹配每个Server Item块及其内部字段
$regexPattern = @'
(?s)(Server Item: (?<ServerItem>.+?))
(?:\s+Identity: (?<Identity>.+?)
\s+Allow: (?<Allow>.+?)
\s+Deny: (?<Deny>.+?)
\s+Allow \(Inherited\): (?<AllowInherited>.+?))+?(?=\nServer Item:|\Z)
'@

# 执行正则匹配
$matches = [regex]::Matches($tfPermOutput, $regexPattern)

# 把匹配结果转换成结构化的PowerShell对象,方便后续处理
$permissionData = foreach ($match in $matches) {
    $currentServerItem = $match.Groups['ServerItem'].Value.Trim()
    
    # 遍历每个Identity的捕获结果
    $identityPermissions = for ($i = 0; $i -lt $match.Groups['Identity'].Captures.Count; $i++) {
        [PSCustomObject]@{
            Identity         = $match.Groups['Identity'].Captures[$i].Value.Trim()
            Allow            = $match.Groups['Allow'].Captures[$i].Value.Trim()
            Deny             = $match.Groups['Deny'].Captures[$i].Value.Trim()
            AllowInherited   = $match.Groups['AllowInherited'].Captures[$i].Value.Trim()
        }
    }

    # 组装当前Server Item的完整数据
    [PSCustomObject]@{
        ServerItem = $currentServerItem
        Identities = $identityPermissions
    }
}

# 查看结果,用Format-List更清晰
$permissionData | Format-List

正则表达式关键说明

  • (?s):开启单行模式,让.能匹配换行符,这样可以跨多行匹配整个Server Item块
  • (?<ServerItem>.+?):非贪婪捕获Server Item的路径,避免不小心匹配到下一个块的内容
  • (?:...)+?:非捕获组,重复匹配每个Identity及其对应的三个权限字段,+?确保匹配到下一个Server Item开头或者文本结尾就停止
  • (?=\nServer Item:|\Z):正向预查,精准定位每个Server Item块的结束边界

小提示

  • 如果你的tf.exe输出有空行或者格式略有差异,可以把正则里的\s+改成\s*,适配不同的空白字符情况
  • 可以先把输出保存到文件再处理:tf.exe perm ... > perm-output.txt,然后用$tfPermOutput = Get-Content perm-output.txt -Raw读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:41:44