【问题标题】:values in this csv are not being edited - Powershell此 csv 中的值未被编辑 - Powershell
【发布时间】:2020-08-12 01:24:05
【问题描述】:
$users = Import-Csv -Path "C:\scripts\door-system\test\testChange.csv" -Encoding UTF8
$users | ft

$output = forEach ($user in $users)
{
     if ($user.GroupName -like "Normal")
    {
        $output.GroupName = "edited"
    }
}

$output | export-csv .\modified.csv -noTypeInformation

【问题讨论】:

  • 如果你想让$output看到你的改变,你只需要在你的循环中更新$user.groupname
  • 你得到什么样的输出,你期望什么。任何错误按摩?请阅读how-to-ask
  • @AdminOfThings 它不在分配中它只会打印$users的状态
  • 如果组名是“Normal”,您应该使用-eq 而不是-like。否则,您可以使用-like "Normal*" .. 与星星! ;-) 您应该将新值分配给 $User.GroupName 而不是 $output.GroupName

标签: powershell csv if-statement foreach export-to-csv


【解决方案1】:

您的代码中有两个故障。 [咧嘴一笑]

第一个是修改循环内的$Output 集合并将循环的输出分配给$Output 集合。做一个或另一个,而不是两者兼而有之。

第二个没有输出任何东西放在$Output 集合中。这会给你一个空集合,因为你给它分配了 什么都没有

这是我的版本和它的作用......

  • 在 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:TEMP\Connor 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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 2021-09-23
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多