如何在 powershell 中使用正则表达式

How to use regex within powershell

我需要遍历所有网站集和所有子网站,并仅打印出具有特定模式的子网站:

/sites/clientcode/oppcode6digits

每个客户端站点集都有很多子站点,但我只需要URL末尾的6位代码。

到目前为止我有这个但没有用:

$SPWebApp = Get-SPWebApplication "https://mylocalurl.com"

foreach ($SPSite in $SPWebApp.Sites) {
    if ($SPSite -ne $null -and $SPSite.Url -notmatch "billing" -and $SPSite.Url -notmatch "administrativedocuments" -and $SPSite.Url -notmatch "documentation" -and $SPSite.Url -notmatch "help" -and $SPSite.Url -notmatch "marketing" -and $SPSite.Url -and $SPSite.Url -notmatch "search" -and $SPSite.Url -ne $rootDMS  ) {
        foreach ($web in $SPSite.AllWebs) {
            $regex = ‘\b[0-9]{6}\b’  
            $patrn = "https://mylocalurl/sites/*/$regex"

            Write-Host $web.Url | select-string -Pattern $patrn
        }
    }
    $SPSite.Dispose()
}

我把最后一行改为:

  if( $web.Url –match  $patrn)
                {
                    Write-Host $web.Url
                }

您可以将我建议的正则表达式与您的代码修复一起使用:

foreach ($web in $SPSite.AllWebs) {
    $patrn ='^https://mylocalurl/sites/(?:[^/]*/)*\d{6}$'
    if( $web.Url –match  $patrn) {
        Write-Host $web.Url
    }
}

正则表达式是

^https://mylocalurl/sites/(?:[^/]*/)*\d{6}$

参见regex demo online

详情

  • ^ - 行首
  • https://mylocalurl/sites/ - 文字子串
  • (?:[^/]*/)* - 除了 / ([^/]*) 之外的 0+ 个字符出现 0+ 次,后跟 /
  • \d{6} - 6 位数
  • $ - 行尾。