简体   繁体   中英

Replace string in an imported CSV file

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\\',''}

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM