PowerShell: How to export values into table format .csv file?

Again I’m no expert in PowerShell, it took me few hours to figure it out. Searched many articles but are difficult for me to understand.

However, the answer was right under my nose. Please refer to the reference I’ve include below this blog. Sorry about the attribute naming, well this is only an example. Hope this helps.

*Note:

  • Always run this(PowerShell) on a test account before moving production (bulk).
  • This script only supports PowerShell version 3.0 or above

Here is an example of what I’m saying;

#Purpose: This powershell is to get the office phone and copy 
#the last 4 digit into a temporary programming attribute and than 
#merge with a string value with the last 4 digits
#Export the user's name, office phone and New Phone

#Merge value
$merge= "123"

#Get the filename
$users = import-csv .\file.csv -delimiter ","

foreach ($i in $users)
{
#Attributes
$name = $i.Name
$officephone = $i.OfficePhone

#If the user's OfficePhone has value
if ($officephone -ne "")
{
#Copy the last 4 digit of the OfficePhone
$lastfourdigit = $officephone.substring($officephone.length - 4)
#Merge the string value with the 4digit to create a new phone number
$newvalue= $merge + $lastfourdigit

#Table format for csv
$content = [PSCustomObject]@{Name = $name; OfficePhone = $officephone; NewPhone= $newvalue}
#Export the table to new csv file
$content | Export-csv newfile.csv -Append

}
else{
#Table format for csv
$content = [PSCustomObject]@{Name = $name; OfficePhone = $officephone; NewPhone= ""}
#Export the table to new csv file
$content | Export-csv newfile.csv -Append

}

}

So the end result is;

newfile

 

I prefer to keep my codes simple and understandable.

Reference

  1. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-6

Author: sabrinaksy

Just an ordinary lady who love what she does best.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: