1

I need to import a CSV file and then replace full usernames domain\username with username.

The following lines work but I only receive the amended usernames as the output and not the full file.

Could you please advise?

$TestFile = Import-Csv .\file.csv 
$NewFile = $TestFile | ForEach-Object {$_."Username" -replace 'domain\\',''}

3 Answers 3

5

When processing CSV input with a ForEach-Object loop you need to output the data back to the pipeline. Also, the -replace operator doesn't modify variables or properties in-place. It takes the value, does the work, and outputs the modified string to the success output stream. If you want to update a property you need to assign the modified value back to that property.

Change this:

$TestFile = Import-Csv .\file.csv 
$NewFile = $TestFile | ForEach-Object {$_."Username" -replace 'domain\\',''}

into this:

$NewFile = Import-Csv .\file.csv | ForEach-Object {
    $_.Username = $_.Username -replace 'domain\\', ''      # update username
    $_                                    # feed data back into the pipeline
}

and the code will do what you want.

Sign up to request clarification or add additional context in comments.

Comments

4

You can perform the replace on the string data, then convert it into an object using ConvertFrom-Csv.

$TestFile = (Get-Content .\file.csv) -replace 'domain\\',''
$NewFile = ConvertFrom-Csv $TestFile

3 Comments

Good answer, keeping in mind that the pattern replacement is global (i.e., not specific to a column).
dude how to make it as specific to a column?
@SumithChalil that's a different problem to this so you'll need to ask your own question.
1

Here's one way - get the column names from the input table, iterate each row in the table, and output new custom objects with needed changes.

$table = Import-Csv "Test.csv"

# Get column names
$columnNames = ($table | Select-Object -First 1).PSObject.Properties |
  Select-Object -ExpandProperty Name

# Iterate each row in the table
foreach ( $row in $table ) {
  $outputObject = New-Object PSObject
  foreach ( $columnName in $columnNames ) {
    if ( $columnName -eq "Username" ) {
      $outputObject | Add-Member NoteProperty "Username" ($row.Username.Split('\')[1])
    }
    else {
      $outputObject | Add-Member NoteProperty $columnName $row.$columnName
    }
  }
  $outputObject
}

To create a new CSV file as output, put the above code in a script and pipe to Export-Csv.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.