Matt
Matt

Reputation: 379

Changing just one value in a csv file with powershell

I am writing a powershell script that takes in phone numbers stored in a csv file. The csv file has a "taken" field, indicating that the phone number is in use or not. Right now, I have a simple foreach loop that reads in the values of the taken field and changes the no to a yes:

Import-Csv '\\papertransport.com\files\UserDocuments\mneis\Code\phone_numbers2.csv' | ForEach-Object 
{
    if ($_.taken -eq 'no') 
    {
        $_.taken = 'yes'
        break
    }
    $_
} | Export-Csv \\papertransport.com\files\UserDocuments\mneis\Code\phone_numbers.csv -NoTypeInformation

My question is: how can I get it so the loop stops when when it hits the first no? The break obviously does not work. Also, is it possible to write to the same csv file instead of writing to a second one? When I write to the original it erases all the values inside of it.

Upvotes: 0

Views: 595

Answers (1)

G42
G42

Reputation: 10019

To get the loop, replace break with return, or change your code to the below.

Writing to the same file is possible; also in the code below. I would recommend making a backup of your existing file to ensure you don't lose any data. Added a try/catch statement that will do that, and stop the script if the copy cannot be created (you can also see a return in action there)

$myFile       = '\\papertransport.com\files\UserDocuments\mneis\Code\phone_numbers2.csv'
$backup       = '\\papertransport.com\files\UserDocuments\mneis\Code\$((Get-Date).ToString"yyyyMMdd")_phone_numbers2.csv'

try{
    Copy-item $myFile $backup -ErrorAction Stop
}catch{
    Write-Host "File could not be copied"
    return;
}


$phoneNumbers = Import-Csv $myFile

Foreach($number in $phoneNumbers)
{
    if ($number.taken -eq 'no') 
    {
        $number.taken = 'yes'
        break
    }

    # you will need to ensure all of the headers in your original file are here, otherwise they will not be in your output file
    [array]$myNewPhoneNumbers += New-Object psobject -Property{
             taken        = $number.taken
             FirstHeader  = $number.FirstHeader
             SecondHeader = $number.SecondHeader
    }

}


$myNewPhoneNumbers | Export-Csv '\\papertransport.com\files\UserDocuments\mneis\Code\$((Get-Date).ToString"yyyyMMdd")_phone_numbers.csv'

# I would recommend ensuring the code works how you want before uncommenting this.
#$myNewPhoneNumbers | Select-Object FirstHeader, SecondHeader, ThirdHeader |Export-Csv $myFile -Force

Upvotes: 1

Related Questions