Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

shell - Concatenate text in PowerShell based on a condition while exporting data to CSV

I have data in AD like below:

DisplayName TelephoneNumber
Alex        111-1111
John        222-2222
Peter       333-3333,2051

I have a powershell script like below:

Get-ADUser -SearchBase 'OU=Domain Users,DC=nxcc,DC=local' -Filter {(enabled -eq $true) -and (mail -like "*.*") -and (PhysicalDeliveryOfficeName -like "*")} -Properties displayname, telephonenumber | select displayname, telephonenumber |  Export-csv -NoTypeInformation -encoding UTF8 -Path "\myserverc$AllUserContactInfo.csv"

What I want to do is to add ,0000 at the end of TelephoneNumber field if the field does not contain a comma character, while exporting to CSV. So expected output is:

DisplayName TelephoneNumber
Alex        111-1111,0000
John        222-2222,0000
Peter       333-3333,2051

How can I achieve this? I appreciate any help.

Regards.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of:

| select displayname, telephonenumber

Use a calculated property:

| Select-Object DisplayName,
    @{n='TelephoneNumber'; e={($_.TelephoneNumber.Split(',', 2) + '0000')[0,1] -Join ','}}

In the expression, the telephone number is split (using the comma as delimiter). This will return only one item in case there is no comma and two items otherwise. Then add '0000' to the list (as a second or a third item), than only take the first two items and join them again with a comma.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...