Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have been trying to get a regular expression right for the powershell match command. I am looping through all site collections in a web application (my sites have URLs SC followed by exactly 4 digits, For example, SC0001, SC0002, SC0003, etc.)

I am matching on the $site.url and not the $site.title, the $site.title is a longer string that is the true title of the site.

I can match on "SC0" but I also get sites that are named SC0001backup and SC0001test.

$sites = Get-SPWebApplication https://<webapplication url> | Get-SPSite -Limit All
foreach($site in $sites) 
{     
    if ($site -match "SC0")

    {
        Write-Host $site.Url, $site.RootWeb.Title
    } 
}

I am trying to get the regular expression correct that will give me all sites that have exactly 6 characters starting with SCxxxx and I can't quite seem to get it correct.

Any regular expression gurus able to assist me with the syntax.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Try the following: /SC\d{4,}$

I have added a / since you are doing the entire URL. I assumed you had parsed the string out. I have tested it against these

/SC0001
/SC0001backup
/SC0001test
/SC0002
/XZ0001derp
/badsiteSC0001

And it matched the first and fourth only.

share|improve this answer
    
If I have SC0001, SC0002, SC0003, SC0001backup, SC0001test, XZ0001derp, I want it to match ONLY the first 3. –  lwbecker2 Mar 17 at 21:00
1  
Ok, I have fixed it. ^ matches the start of a string and $ matches the end. –  Robert Kaucher Mar 17 at 21:03
    
is the , after the 4 necessary? –  lwbecker2 Mar 17 at 21:05
    
No, I do that just as a habit I picked up. –  Robert Kaucher Mar 17 at 21:07
    
Is my current edit acceptable? Technically you need the ^ as not having it would also match somesiteSC0001. –  Robert Kaucher Mar 17 at 21:08

I know you've already got a great answer using regex, but you also could have parsed the string out to leave only what's remaining after the "SC", and tried to parse that as an integer.

Like

$shouldBeInteger = $site.Url.Substring($site.Url.LastIndexOf("/") + 3)

try
{
    $siteNumber = [System.Int32]::Parse($shouldBeInteger)
}
catch
{
    # oops, guess there were more than just numbers in that string
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.