简体   繁体   English

替换导入的CSV文件中的字符串

[英]Replace string in an imported CSV file

I need to import a CSV file and then replace full usernames domain\\username with username . 我需要导入CSV文件,然后将完整的用户名domain\\username替换为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. 使用ForEach-Object循环处理CSV输入时,您需要将数据输出回管道。 Also, the -replace operator doesn't modify variables or properties in-place. 另外, -replace运算符不会就地修改变量或属性。 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 . 要创建一个新的CSV文件作为输出,请将上面的代码放入脚本中,并通过管道传递到Export-Csv

You can perform the replace on the string data, then convert it into an object using ConvertFrom-Csv . 您可以对字符串数据执行替换,然后使用ConvertFrom-Csv将其转换为对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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