Author Posts

September 8, 2014 at 8:42 am

Hey everyone,

I have managed to get myself into a confused haze trying to figure out a specific regex for Powershell.

I have a csv file that I am going to import into Active Directory, however the Phone number is just an extension and I need to prepend the beginning of the number.

Simple enough until I realise that if the extension starts with a 3 it is one number, but if it is a 6 it is another number.

Here is what I have got so far:

$Tel1 = "+44 1481 705" #Ext begins with a 3
$Tel2 = "+44 1481 731" #Ext begins with a 6

Import-csv C:\Gerry\GALSync\SCGSY_GAL.csv | ForEach {If ($_.Phone -match "3" ){
Write-Host $Tel1 $_.Phone
}
else {
Write-Host $Tel2 $_.Phone
}
}

The problem I have is that it will match 345 but also 635.

How do I phrase the RegEx to just check the first number for a match and not the second or third?

Thanks in advance.

September 8, 2014 at 8:44 am

Use the beginning-of-string anchor:

^3

Matches a three only at the start of the string.

September 8, 2014 at 8:05 pm

So do you want to strip the 3 or 6 from the beginning of the extension and replace it with "+44 1481 7"? (I'm a little confused exactly what you're trying to replace.) If so, you can do this:

Import-csv C:\Gerry\GALSync\SCGSY_GAL.csv | ForEach { $_.Phone = $_.Phone -replace "^(3|6)","+44 1481 7" }

The -replace operator matches a 3 or 6 at the beginning of the phone number, and replaced it with "+44 1481 7".

September 9, 2014 at 2:06 am

Thanks Don, that is exactly what I was looking for! My Googlefu phrasing needs an update...

Aaron – luckily I don't need to strip the 3 or 6 , but I am sure someone else will, so thanks for the tip!

I just need to prepend the correct number, so it should look like this:

$Tel1 = "+44 1481 705" #Ext begins with a 3
$Tel2 = "+44 1481 731" #Ext begins with a 6
Import-csv C:\Gerry\GALSync\SCGSY_GAL.csv | ForEach {If ($_.Phone -match "^3" ){
{$_.Phone -replace $Tel1 + $_.Phone} } |Export-csv C:\Scripts\GALSync\SCGSY_GAL1.csv -append -NoTypeInformation
}
else {
{$_.Phone -replace $Tel2 + $_.Phone} } |Export-csv C:\Scripts\GALSync\SCGSY_GAL1.csv -append -NoTypeInformation
}
}

Thanks for both of your responses 🙂

September 9, 2014 at 3:29 am

After testing I realised I wasn't putting anything in the pipeline for Export-CSV to grab, so this is my revised script:


$Tel1 = "+44 1481 705" #Ext begins with a 3
$Tel2 = "+44 1481 731" #Ext begins with a 6
$CSV = Import-csv C:\Scripts\GALSync\SCGSY_GAL.csv
ForEach ($line in $CSV) {
    If ($line.Phone -match "^3" ) { 
        $line.Phone = $Tel1 + $line.Phone
        Export-csv -path C:\Scripts\GALSync\SCGSY_GAL1.csv -InputObject $line -Append -NoTypeInformation -Force
        } 
    else { 
        $line.Phone = $Tel2 + $line.Phone
        Export-csv -path C:\Scripts\GALSync\SCGSY_GAL1.csv -InputObject $line -Append -NoTypeInformation -Force
        } 
    } 

Also, sorry to Don for using Write-Host instead of Write-Output...