此csv中的值未被编辑-Powershell


$users = Import-Csv -Path "C:scriptsdoor-systemtesttestChange.csv" -Encoding UTF8
$users | ft
$output = forEach ($user in $users)
{
if ($user.GroupName -like "Normal")
{
$output.GroupName = "edited"
}
}
$output | export-csv .modified.csv -noTypeInformation

您的代码中有两个小故障。[grin]

第一个是修改循环内的CCD_ 1集合并将循环的输出分配给CCD_。做一个或另一个,而不是两者都做。

第二个不输出任何要放入CCD_ 3集合中的内容。这将给你一个空的集合,因为你根本没有分配给它。

这是我的版本&它的作用。。。

  • 在CSV文件中伪造读取
    当您准备好使用真实数据时,删除整个#region/#endregion块并使用Import-CSV
  • 设置目标字符串和替换字符串
  • 遍历导入的集合
  • 在每个对象的.GroupName属性中测试目标
  • 如果找到,它将用替换字符串替换该值
  • 将修改后的对象发送到$Results集合
  • 在屏幕上显示$Results
  • 将$Results保存到CSV文件

代码。。。

#region >>> fake reading in a CSV file
#    in real life, use Import-CSV
$UserList = @'
UserName, GroupName
ABravo, Normal
BCharlie, Abnormal
CDelta, Other
DEcho, Normal
EFoxtrot, Edited
FGolf, Strange
'@ | ConvertFrom-Csv
#endregion >>> fake reading in a CSV file
$TargetGName = 'Normal'
$ReplacementGName = 'Edited'
$Results = foreach ($UL_Item in $UserList)
{
if ($UL_Item.GroupName -eq $TargetGName)
{
$UL_Item.GroupName = $ReplacementGName
}
# send the modified data to the $Results collection
$UL_Item
}
# show on screen
$Results
# send to CSV
$Results |
Export-Csv -LiteralPath "$env:TEMPConnor Tuohy_-_Modified.csv" -NoTypeInformation

屏幕输出。。。

UserName GroupName
-------- ---------
ABravo   Edited   
BCharlie Abnormal 
CDelta   Other    
DEcho    Edited   
EFoxtrot Edited   
FGolf    Strange

CSV文件["C:\Temp\Connor Tuohy__Modified.CSV"]内容。。。

"UserName","GroupName"
"ABravo","Edited"
"BCharlie","Abnormal"
"CDelta","Other"
"DEcho","Edited"
"EFoxtrot","Edited"
"FGolf","Strange"

最新更新